text:
Q: Prove that there exists $f,g : \mathbb{R}$ to $\mathbb{R}$ such that $f(g(x))$ is strictly increasing and $g(f(x))$ is strictly decreasing. Prove that there exists $f,g : \mathbb{R}$ to $\mathbb{R}$ such that $f(g(x))$ is strictly increasing and $g(f(x))$ is strictly decreasing.
I tried cases by taking $f(x)$ as an increasing function and $g(x)$ as a decreasing function then I am getting both $f(g(x))$ and $g(f(x))$ as decreasing functions.
Further I took both of them as increasing functions, but none of them are yielding results.
Help

A: Here is a construction that uses the axiom of choice. I'm not sure if it can be avoided.
Let $p$ be an increasing bijection ${\mathbb R} \to  \mathbb R$ such that $p(0)=0$ and $0$ is the only fixed point of any iterate of $p$ (for example, $p(x)=2017x$ will do).
Let also $q$ be a decreasing bijection ${\mathbb R} \to \mathbb R$ such that $q(0)=0$ and $0$ is the only fixed point of any iterate of $q$ (for example, $q(x)=-2017x$ will do).
The iterates of $p$ form a group under composition which we call $P$. Then $P$ acts on ${\mathbb R}^*$. By the axiom of choice, there is a transversal $T_p\subseteq {\mathbb R}^*$ containing exactly one element from each orbit, then the map ${\mathbb Z} \times T_p \to {\mathbb R}^*, (k,x)\mapsto p^k(x)$ is bijective.
Similarly, there is a $T_q\subseteq {\mathbb R}$ such that ${\mathbb Z} \times T_q \to {\mathbb R}^*, (k,x)\mapsto q^k(x)$ is bijective.
By a well-known result in cardinality theory, since $T_q$ and $\mathbb Z$ are both infinite and $|T_q|>|{\mathbb Z}|$, we have $|{\mathbb Z} \times T_q|=|T_q|$. It follows that there is a bijective map $b:T_q \to T_p$.
Now, define $f$ by $f(0)=0$ and for nonzero $r$, say $r=q^{k}(t)$ with $t\in T_q$, put $f(r)=p^{k}(b(t))$. Similary, define $g$ by $g(0)=0$ and for nonzero $r$, say $r=p^{k}(b(t))$ with $t\in T_q$, put $g(r)=q^{k+1}(t)$.
By construction, one then has $f\circ g=p$ and $g\circ f=q$.

A: EDITED
Let the domain and range of both $f$ and $g$ be the real line. Furthermore assume that the derivatives exist. Also, assume that they do not have inflexions with zero derivative. If we do not assume that the whole line is the domain then counterexample(s) can be created. (See Han de Bruijn's comment to this post.)

In order for $f(g(x))$ to be strictly increasing we need that the derivative wrt $x$ be positive
$$f(g(x))'=  f'(g(x))g'(x)>0.$$
So, both $f'(g(x)$ and $g'(x)$ have to be positive xor negative.
In order for $g(f(x))$ to be strictly decreasing we need that the derivative wrt $x$ be negative.   $$g(f(x))'=  g'(g(x))f'(x)<0.$$
One of the components has to be negative and the other one has to be positive but not the same sign at the same time.
Above we requested the opposite.

A: To satisfy strict monotonicity in the composites, both functions must be injective (1-to-1). However to product opposite monotonicity, $f$ and $g$ must be discontinuous everywhere, since even a short stretch of monotone behaviour will produce the same behaviour in both compositions.
Also, although this is less certain, since $f \circ g$ and $g\circ f$ are strictly monotone, they are continuous almost everywhere. So essentially we need to  disassemble the real number line into points, and then reassemble it.
This suggests we need to have something like functions that split by eg. rational and irrational numbers in an apparently chaotic fashion. However in the end I think this will be an existence proof rather than a demonstrated example.

A: First, we say two intervals $A$<$B$, if $\forall a\in A, b\in B$ such that $a$<$b$, like $(-1,2]$<$(2,4]$. If $g\circ f(x)$ is increasing on A and B, then we want the image of A, B satisfying $h[A]$<$h[B]$; $f\circ g(x)$ is decreasing on $A$ and $B$, then we just have to let the image of $A, B$ satisfying $k[B]$<$k[A]$, which ensures the monotonicity (more) globally.
Give an example to show how it really works. Eventually we partition the real plain $\mathbb{R}^2$ into integer lattices. In each square, the function $f$, $g$ looks like either $\frac{1}{2}x+\frac{1}{4}$, or $-\frac{1}{2}x+\frac{3}{4}$. We should, however, shift the boxes so that we achieve what we said before.
On even-number-th interval, $f,g$ look like $-\frac{1}{2}x+\frac{3}{4}$; on odd-number-th interval, $f,g$ look like $\frac{1}{2}x+\frac{1}{4}$ inside its square. We have to map correctly from squares to squares i.e. $\mathbb{Z}\to\mathbb{Z}$ such that the local and global monotonicities are satisfied.
I.e. find two functions $i,d:\mathbb{Z}\to\mathbb{Z}$, $i$ is parity-preserving and $d$ parity-reversing, $d\circ i$ increasing, $i\circ d$ decreasing. E.g. It is not hard to check $$i(n)=\begin{cases}2n & \text{even}\\-2n+1&\text{odd}\end{cases}\quad d(n)=\begin{cases}2n+1 & \text{even}\\-2n&\text{odd}\end{cases}$$
satisfy the requirements.
These functions indicate where the squares are vertically.
Finally, put all together,
$$f(x)=\begin{cases}-\frac{1}{2}(x-\lfloor x\rfloor)+\frac{3}{4}+i(\lfloor x\rfloor) & \lfloor x\rfloor\text{ is even}\\\frac{1}{2}(x-\lfloor x\rfloor)+\frac{1}{4}+i(\lfloor x\rfloor)&\lfloor x\rfloor\text{ is odd}\end{cases}$$
$$g(x)=\begin{cases}-\frac{1}{2}(x-\lfloor x\rfloor)+\frac{3}{4}+d(\lfloor x\rfloor) & \lfloor x\rfloor\text{ is even}\\\frac{1}{2}(x-\lfloor x\rfloor)+\frac{1}{4}+d(\lfloor x\rfloor)&\lfloor x\rfloor\text{ is odd}\end{cases}$$
With the same idea, a refined solution:
First, let $f(0)=g(0)=0$. Then, we partition the axis into $\{\pm[{2^n},{2^{n+1}})\}_{n\in\mathbb{Z}}$ for $f$ and
$\{\pm[{2^n\sqrt{2}},{2^{n+1}\sqrt{2}})\}_{n\in\mathbb{Z}}$ for $g$. Then $f,g$ take value from either $\sqrt{2}x$ or $-\sqrt{2}x$ alternatingly on the partitioned intervals respectively starting to take value $\sqrt{2}x$ on $\pm[1,2)$ and $\pm[\sqrt{2},2\sqrt{2})$.


text:
Q: Function that is 1 if input is positive, 0 otherwise I am trying to write a certain matrix neatly for a paper, but I do not know how I would go about writing what I want formally.
I have two variables, x and y, which can assume any value. I want to express a matrix M whose first diagonal component is 1 if x is positive, 0 otherwise. The second diagonal component is 1 if x is negative, 0 otherwise. The third diagonal component is 1 if y is positive, 0 otherwise. The fourth diagonal component is 1 if x is negative, 0 otherwise.
For example:
x = 2, y = 1 -> diag(M) = [1 0 1 0];
x = 0, y = 1 -> diag(M) = [0 0 1 0];
x = -3, y = -2 -> diag(M) = [0 1 0 1];
In code, I would write that as:
diag(M) = [x > 0; x < 0; y > 0; y < 0];
Basically:
$\begin{equation}
M =
\begin{bmatrix}
x>0 &  & &\\
 & x<0 & &\\
 & & y>0&\\
 & & & y<0
\end{bmatrix}
\end{equation}
$
And the boolean comparison is automatically converted to a 1 if true and 0 if false.
Would the latter be a good notation for a paper? Or is this only valid in code? I need to write this a lot of times and I want it to be clear what the matrix represent.
Something maybe along the lines of the sign function, but that is -1 if the number is negative, and not zero so it does not work.
Basically it is not clear to me how to represent a boolean condition that translates to 1 if valid and 0 otherwise
I know that an alternative would be to write
$
\begin{equation}
    \begin{cases}
      1 & \text{if x > 0}\\
      0 & \text{otherwise}\\
    \end{cases}
\end{equation}$
but that would be too much for the matrix I need to write since it is repeated four times slightly differently.
Cheers

A: The Iverson bracket notation is often used for things like this, where $[P] \equiv\begin{cases} 1 & \text{$P$ is true} \\ 0 & \text{$P$ is false} \end{cases}$
So in this case, you could write $[x > 0]$, $[y > 0]$, etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximal ideals of coordinate ring of the circle I am currently a master student taking algebraic geometry and a teaching assistent for undergraduate ring theory.
The students had to make the following easy exercise in ring theory:
Consider the ring $R=\mathbf{R}[x,y]/(x^2+y^2-1)$.
(a) Prove that $(x-a,y-b)\subset R$ is maximal if and only if $a^2+b^2=1$. (b) For which $b\in\mathbf{R}$ is $(y-b)\subset R$ maximal?
From algebraic geometry, I know that $R$ is the coordinate ring of the circle. I was wondering if this exercise (maybe replacing $\mathbf{R}$ by $\mathbf{C}$ since algebraic geometers work over algebraically closed fields) has a more advanced interpretation from an algebraic geometry point of view.
I am very interested in any answer.

A: The interpretation of a) is very simple: if $k$ is a field and $f_1, \dots f_m \in k[x_1, \dots x_n]$ is a system of polynomial equations, then the collection of solutions to those equations over $k$ can be identified with the set of $k$-algebra homomorphisms
$$\text{Hom}_k(k[x_1, \dots x_n]/(f_1, \dots f_m), k)$$
and since any such homomorphism must be surjective the kernels of such homomorphisms are exactly the maximal ideals with residue field $k$. Furthermore if $k$ is algebraically closed the Nullstellensatz implies that every maximal ideal arises in this way. This is the basis of the correspondence between maximal ideals and points on varieties; the quotient $k[x_1, \dots x_n]/(f_1, \dots f_m)$ is the algebra of functions on the affine scheme cut out by the polynomials $f_i$ (I really need to say "affine scheme" here and not just "affine variety" if the ideal $I = (f_1, \dots)$ is not reduced).
b) is a little trickier to understand geometrically, and we actually pass out of the realm of varieties. Quotienting by $(y - b)$ corresponds geometrically to taking the scheme-theoretic intersection of the circle with the line $y = b$. Geometrically there are three possibilities: the intersection can be

*

*two real points (e.g. $y = 0$, corresponding to the quotient $\mathbb{R}[x]/(x^2 - 1) \cong \mathbb{R}^2$),

*one real point with multiplicity two (e.g. $y = 1$, corresponding to the quotient $\mathbb{R}[x]/x^2$), or

*two complex points (e.g. $y = 2$, correspnding to the quotient $\mathbb{R}[x]/(x^2 + 3) \cong \mathbb{C}$).

We only get a field in the third case so those are the maximal ideals. Now it's necessary to have a grip on how to think geometrically about a variety over a field that isn't algebraically closed, and scheme-theoretic intersections of such a variety with other varieties that aren't varieties (there's a nilpotent in the second case). To my mind the cleanest way to do it, and the point of view I implicitly adopt in the description above, is that a variety (or scheme) over $k$ is a variety over $\bar{k}$ together with a Galois action. Maximal ideals (in the affine case) correspond not to $k$-points but to Galois orbits of $\bar{k}$-points; above in the "two complex points" case there are two points but they lie in a single Galois orbit which is why we get a single maximal ideal. And then sometimes intersections have multiplicity which turns out to correspond to nilpotents, at least in this simple case.


text: Q: How to fire like and range query on PII encrypted column in mysql I have different encrypted columns in my MySQL table for different PII data like email, date of birth, etc.I am using AES envelope encryption coupled with AWS KMS. The encryption and decryption is handled in the application. No MySQL inbuilt encryption functionalities are used.                       I am able to perform the full-text match of input email by encrypting it but unable to perform like query operation. Please suggest me solutions for performing different MySQL operations on encrypted PII data.


text:
Q: Assign indexes of array to boolean value inside an object - optimal way I am trying to find the best way to assign array indices to an object with boolean value. currently my solution is:
let l = [{t:1, te: "aa"}, {t:2, te: "aa"},{t:2, te: "aa"} ];
let a = {}
l.map((obj, index) => (a[index] = false));
console.log(a)

So if I have an array with 200 objects it will be {0: false, 1:false, ....}
I was looking at Array.reduce() however, I cannot find a way to do it with that and I always get:
var object = Object.assign(...l.map(k => ({ [k]: true })));

{
   [object Object]: false
}

Is there anyway to do this in one line?

A: You can map the objects to an array of entries of [index, false], and turn it into an object:

const l = [{t:1, te: "aa"}, {t:2, te: "aa"},{t:2, te: "aa"} ];
const a = Object.fromEntries(l.map((_, i) => [i, false]));
console.log(a)

A: You can use the index parameter in the map callback.

let l = [{t:1, te: "aa"}, {t:2, te: "aa"},{t:2, te: "aa"} ];
var object = Object.assign(...l.map((x, i) => ({
  [i]: true
})));
console.log(object)

You can use Array#reduce in a similar manner.

let l = [{t:1, te: "aa"}, {t:2, te: "aa"},{t:2, te: "aa"} ];
var object = l.reduce((acc, curr, index) => Object.assign(acc, {
  [index]: true
}), {});
console.log(object)

A: const l = [{t:1, te: "aa"}, {t:2, te: "aa"},{t:2, te: "aa"} ];
const a = l.reduce((acc, obj, index) =>  { return {...acc, [index] : false }}, {})
console.log(a)


text:
Q: VScode: 'updating intellisense' forever I vscode on my Ubuntu 16.04 platform and I've installed C++ Intellisense
austin.code-gnu-global and C/C++ ms-vscode.cpptools extensions for cpp project. Here is a part of my setting.json:
"C_Cpp.updateChannel": "Insiders",
"C_Cpp.intelliSenseEngine": "Default",
"files.trimTrailingWhitespace": true,
"files.exclude": {
    "**/build": true,
    "**/.git*": true,
    "**/.vscode": true,
    "**/.git": true,
    "**/.svn": true,
    "**/.hg": true,
    "**/.DS_Store": true
},

The flame icon has alerted since yesterday. BTW, my project contains a large number of files which exceeds the maximum watchers fs.inotify.max_user_watches=524288, So I wonder how can I cope with the warning:"Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)?

A: Have you tried raising the maximum watchers? It may be related to disk speed. I have the same issue but I am working on a huge codebase. Make sure you have "Limit symbols to included headers" checked and that you have a good "Intelli Sense Cache Size". Workspace parsing priority can also be set to "highest".


text:
Q: View is not displaying returned data from controller in MVC I am sending data through HttpClient (Json) from console app to web app, everything is working well but the only issue Iam facing that data sent from controller to view is not displayed. I debugged the program and i can see that data are returned to the view. Following are the codes:
Constroller:
using ( var db = new MessageDBContext())
{
    try
    {
        db.Messages.Add(model);
        db.SaveChanges();
    }
    catch (DbEntityValidationException e)
    {
        Debug.WriteLine("Saving Messages into db Error 1: " + e.EntityValidationErrors);
    }
}
return View(model);

Controller Debugg:

and here is the view code:

            Message
            Time

        @if (Model != null)
        {

                    @Html.Display(@Model.message)

                    @Html.Display(@Model.time)

        }

View Debugg:

So why the data are not displayed to the html view!?

A: You have to use one of this case:
 @if (Model != null)
    {

                @Html.DisplayFor(model => model.message)

                @* Or *@
                @Model.time

    }

A: I'll add some information to this question. The controller method which (shown in the question) is marked with HttpPost attribute and is called from the console application. Of course, the result is returned to the console and NOT to the browser. In the browser the controller returns empty model return View(); Otherwise, the DisplayFor method would work perfectly. If you want to update the display in your browser you need to write more code to establish server->client communication.


text:
Q: como recibir datos en el cliente (python) desde el servidor (nodejs) usando websocket Actualmente estoy enviando los datos del servidor de la siguiente manera
this.socket.send('playback', Id, playbackData)

donde la 'playback' es el nombre del evento y los otros son los datos enviados desde el servidor
La pregunta es ¿Cómo recibo y manipulo estos datos en el lado del cliente que está en python?
gracias de antemano a quien me pueda ayudar.


text:
Q: ASP .NET Core MVC, Entity Framework, Identity - composite key consisting of foreign keys I have the following model classes. I want that TripId and TouristId would be a composite key of Attendance entity.
For now I get this error while the sql is executed:
CREATE TABLE [Attendance] (
[Id] int NOT NULL IDENTITY,
[TouristId] nvarchar(450) NOT NULL,
[TripId] int NOT NULL,
CONSTRAINT [PK_Attendance] PRIMARY KEY ([Id]),
CONSTRAINT [FK_Attendance_AspNetUsers_TouristId] FOREIGN KEY ([TouristId]) REFERENCES [AspNetUsers] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_Attendance_Trip_TripId] FOREIGN KEY ([TripId]) REFERENCES [Trip] ([Id]) ON DELETE CASCADE);

Introducing FOREIGN KEY constraint 'FK_Attendance_Trip_TripId' on
table 'Attendance' may cause cycles or multiple cascade paths. Specify
ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN
KEY constraints. Could not create constraint or index. See previous
errors.

public class Attendance
    {
        public virtual Trip Trip { get; set; }
        public virtual ApplicationUser Tourist { get; set; }
    }

public class ApplicationUser : IdentityUser
    {

        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string FirstName { get; set; }
        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string Surname { get; set; }

        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string BirthDate { get; set; }
    }

public class Trip
    {
        public int TripId { get; set; }
        public string TripDate { get; set; }
        public int TripDuration { get; set; }
        public int TripLength { get; set; }
        public int TripSeats { get; set; }
        public Trail Trail { get; set; }
        public ApplicationUser Guide { get; set; }
    }

EDIT:
public class Attendance
    {
        public int AttendanceId { get; set; }
        public int? TripId { get; set; }
        public int? TouristId { get; set; }
        public virtual Trip Trip { get; set; }
        public virtual ApplicationUser Tourist { get; set; }
    }

But foreign keys are still set as 'NOT NULL'.

A: In DbContext class into the OnModelCreating overriding do this :
modelBuilder.Entity<Attendance>()
.HasOne(p => p.Tourist)
.WithMany<ApplicationUser>()
.OnDelete(DeleteBehavior.Cascade `or` DeleteBehavior.Restrict);


text:
Q: All-to-all setdiff on two numeric vectors with a numeric threshold for accepting matches What I want to do is more or less a combination of the problems discussed in the two following threads:

*

*Perform non-pairwise all-to-all comparisons between two unordered character vectors --- The opposite of intersect --- all-to-all setdiff

*Merge data frames based on numeric rownames within a chosen threshold and keeping unmatched rows as well
I have two numeric vectors:
b_1 <- c(543.4591, 489.36325, 12.03, 896.158, 1002.5698, 301.569)
b_2 <- c(22.12, 53, 12.02, 543.4891, 5666.31, 100.1, 896.131, 489.37)

I want to compare all elements in b_1 against all elements in b_2 and vice versa.
If element_i in b_1 is NOT equal to any number in the range element_j ± 0.045 in b_2 then element_i must be reported.
Likewise, if element_j in b_2 is NOT equal to any number in the range element_i ± 0.045 in b_1 then element_j must be reported.
Therefore, example answer based on the vectors provided above will be:
### based on threshold = 0.045
in_b1_not_in_b2 <- c(1002.5698, 301.569)
in_b2_not_in_b1 <- c(22.12, 53, 5666.31, 100.1)

Is there an R function that would do this?

A: A vectorized beast:
D <- abs(outer(b_1, b_2, "-")) > 0.045

in_b1_not_in_b2 <- b_1[rowSums(D) == length(b_2)]
#[1] 1002.570  301.569

in_b2_not_in_b1 <- b_2[colSums(D) == length(b_1)]
#[1]   22.12   53.00 5666.31  100.10

hours later...
Henrik shared a question complaining the memory explosion when using outer for long vectors: Matching two very very large vectors with tolerance (fast! but working space sparing). However, the memory bottleneck for outer can be easily killed by blocking.
f <- function (b1, b2, threshold, chunk.size = 5000) {

  n1 <- length(b1)
  n2 <- length(b2)
  chunk.size <- min(chunk.size, n1, n2)

  RS <- numeric(n1)  ## rowSums, to be accumulated
  CS <- numeric(n2)  ## colSums, to be accumulated

  j <- 0
  while (j < n2) {
    chunk.size_j <- min(chunk.size, n2 - j)
    ind_j <- (j + 1):(j + chunk.size_j)
    b2_j <- b2[ind_j]
    i <- 0
    while (i < n1) {
      chunk.size_i <- min(chunk.size, n1 - i)
      ind_i <- (i + 1):(i + chunk.size_i)
      M <- abs(outer(b1[ind_i], b2_j, "-")) > threshold
      RS[ind_i] <- RS[ind_i] + rowSums(M)
      CS[ind_j] <- CS[ind_j] + colSums(M)
      i <- i + chunk.size_i
      }
    j <- j + chunk.size_j
    }

  list(in_b1_not_in_b2 = b1[RS == n2], in_b2_not_in_b1 = b2[CS == n1])
  }

With this function, outer never uses more memory than storing two chunk.size x chunk.size matrices. Now let's do something crazy.
b1 <- runif(1e+5, 0, 10000)
b2 <- b1 + runif(1e+5, -1, 1)

If we do a simple outer, we need memory to store two 1e+5 x 1e+5 matrices, which is up to 149 GB. However, on my Sandy Bridge (2011) laptop with only 4 GB RAM, computation is feasible.
system.time(oo <- f(b1, b2, 0.045, 5000))
#   user  system elapsed
#365.800 167.348 533.912

The performance is actually good enough, given that we have been using a very poor algorithm.
All answers here do exhausted search, that has complexity length(b1) x length(b2). We could reduce this to length(b1) + length(b2) if we work on sorted arrays. But such deeply optimized algorithm can only be implemented with compiled language to obtain efficiency.

A: Here is an alternative approach
in_b1_not_in_b2 <- b_1[sapply(b_1, function(x) !any(abs(x - b_2) <= 0.045))]
in_b1_not_in_b2
#[1] 1002.570  301.569

in_b2_not_in_b1 <- b_2[sapply(b_2, function(x) !any(abs(x - b_1) <= 0.045))]
in_b2_not_in_b1
#[1]   22.12   53.00 5666.31  100.10

A: If you are happy to use a non-base package, data.table::inrange is a convenient function.
x1[!inrange(x1, x2 - 0.045, x2 + 0.045)]
# [1] 1002.570  301.569

x2[!inrange(x2, x1 - 0.045, x1 + 0.045)]
# [1]   22.12   53.00 5666.31  100.10

inrange is also efficient on larger data sets. On e.g. 1e5 vectors, inrange is > 700 times faster than the two other alternatives:
n <- 1e5
b1 <- runif(n, 0, 10000)
b2 <- b1 + runif(n, -1, 1)

microbenchmark(
  f1 = f(b1, b2, 0.045, 5000),
  f2 = list(in_b1_not_in_b2 = b1[sapply(b1, function(x) !any(abs(x - b2) <= 0.045))],
       in_b2_not_in_b1 = b2[sapply(b2, function(x) !any(abs(x - b1) <= 0.045))]),
  f3 = list(in_b1_not_in_b2 = b1[!inrange(b1, b2 - 0.045, b2 + 0.045)],
       in_b2_not_in_b1 = b2[!inrange(b2, b1 - 0.045, b1 + 0.045)]),
  unit = "relative", times = 10)
# Unit: relative
#  expr      min       lq     mean   median        uq       max neval
#    f1 1976.931 1481.324 1269.393 1103.567 1173.3017 1060.2435    10
#    f2 1347.114 1027.682  858.908  766.773  754.7606  700.0702    10
#    f3    1.000    1.000    1.000    1.000    1.0000    1.0000    10

And yes, they give the same result:
n <- 100
b1 <- runif(n, 0, 10000)
b2 <- b1 + runif(n, -1, 1)

all.equal(f(b1, b2, 0.045, 5000),
          list(in_b1_not_in_b2 = b1[sapply(b1, function(x) !any(abs(x - b2) <= 0.045))],
               in_b2_not_in_b1 = b2[sapply(b2, function(x) !any(abs(x - b1) <= 0.045))]))
# TRUE

all.equal(f(b1, b2, 0.045, 5000),
          list(in_b1_not_in_b2 = b1[!inrange(b1, b2 - 0.045, b2 + 0.045)],
               in_b2_not_in_b1 = b2[!inrange(b2, b1 - 0.045, b1 + 0.045)]))
# TRUE

Several related, potentially useful answers when searching for inrange on SO.


text:
Q: How to have another row in my Flexdashboard if I'm using {.tabset}? R Here is how my dashboard template looks. I have a {.tabset} to show two different tables for Dec 2020 & Jan 2020. But the table is not as long as the area generated and really only reaches half of it.

My desired ouutput would be something like this.

But I can't figure out how to add another level without it joining the {.tabset} or making a new column.
Here is my Rmarkdown Template
---
title: "Example Demo Dash"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

# Tab 1

Column
-----------------------------------------------------------------------

### Tab 1 Graph

# Tab 2

Column {data-width=450, .tabset}
-----------------------------------------------------------------------

### December 2020

### Janurary 2020

Column {data-width=200}
-----------------------------------------------------------------------

### Tab 2 Col 2 Graph 1

### Tab 2 Col 2 Graph 1

### Tab 2 Col 2 Graph 3

### Tab 2 Col 2 Graph 3

Column {data-width=350}
-----------------------------------------------------------------------
### Col 3 graph 1

### Col 3 graph 2

# tab 3

A: As answered here & mentioned in this GitHub issue, creating a tab set at or below a level-3 heading is not currently supported.
To work around this, we could use tabsetPanel() to manually construct the tab set. Note that we will need to pass the content of the tab directly to the tabPanel() as an argument.
Updated R Markdown based on your example:
---
title: "Example Demo Dash"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

# Tab 1

Column
-----------------------------------------------------------------------

### Tab 1 Graph

# Tab 2

Column {data-width=450}
-----------------------------------------------------------------------

### Tabs

```{r}
tabsetPanel(
  tabPanel("December 2020",
           "Things about December 2020"),
  tabPanel("Janurary 2020",
           "Things about Janurary 2020")
)
```

### Col 3 Graph 1

Column {data-width=200}
-----------------------------------------------------------------------

### Tab 2 Col 2 Graph 1

### Tab 2 Col 2 Graph 1

### Tab 2 Col 2 Graph 3

### Tab 2 Col 2 Graph 3

Column {data-width=350}
-----------------------------------------------------------------------
### Col 3 graph 1

### Col 3 graph 2

# tab 3

Screenshot:


text:
Q: Разница между .NET 5 и 7 Взялся за, возможно, устаревшую книгу 2022 года издания по C# 9 и .NET 5 от Марка Прайса и думаю, следует ли по ней изучать C# на 5 версии платформы .NET или же можно изучать эту программу уже на 7 версии. Те, кто имел опыт с обеими версиями: будет ли большая разница и можно ли смело изучать эту книгу на 7 версии, или же изменения слишком значительны для изучения нового C# и .NET по книге, предназначенных для старой версии?
Видел описание метки "книги" и понимаю, что есть список нужной литературы, но тут всё же больше вопрос о актуальности книги/платформы чем о нахождении какой-либо нужной мне литературы.


text:
Q: Perl's diamond operator: can it be done in bash? Is there an idiomatic way to simulate Perl's diamond operator in bash? With the diamond operator,
script.sh | ...

reads stdin for its input and
script.sh file1 file2 | ...

reads file1 and file2 for its input.
One other constraint is that I want to use the stdin in script.sh for something else other than input to my own script. The below code does what I want for the file1 file2 ... case above, but not for data provided on stdin.
command - $@ <<EOF
some_code_for_first_argument_of_command_here
EOF

I'd prefer a Bash solution but any Unix shell is OK.
Edit: for clarification, here is the content of script.sh:
#!/bin/bash
command - $@ <<EOF
some_code_for_first_argument_of_command_here
EOF

I want this to work the way the diamond operator would work in Perl, but it only handles filenames-as-arguments right now.
Edit 2: I can't do anything that goes
cat XXX | command

because the stdin for command is not the user's data. The stdin for command is my data in the here-doc. I would like the user data to come in on the stdin of my script, but it can't be the stdin of the call to command inside my script.

A: Sure, this is totally doable:
#!/bin/bash
cat $@ | some_command_goes_here

Users can then call your script with no arguments (or '-') to read from stdin, or multiple files, all of which will be read.
If you want to process the contents of those files (say, line-by-line), you could do something like this:
for line in $(cat $@); do
    echo "I read: $line"
done

Edit: Changed $* to $@ to handle spaces in filenames, thanks to a helpful comment.

A: Kind of cheezy, but how about
cat file1 file2 | script.sh

A: I am (like everyone else, it seems) a bit confused about exactly what the goal is here, so I'll give three possible answers that may cover what you actually want.  First, the relatively simple goal of getting the script to read from either a list of files (supplied on the command line) or from its regular stdin:
if [ $# -gt 0 ]; then
  exec < <(cat "$@")
fi
# From this point on, the script's stdin is redirected from the files
# (if any) supplied on the command line

Note: the double-quoted use of $@ is the best way to avoid problems with funny characters (e.g. spaces) in filenames -- $* and unquoted $@ both mess this up. The <() trick I'm using here is a bash-only feature; it fires off cat in the background to feed data from files supplied on the command line, and then we use exec to replace the script's stdin with the output from cat.
...but that doesn't seem to be what you actually want.  What you seem to really want is to pass the supplied filenames or the script's stdin as arguments to a command inside the script.  This requires sort of the opposite process: converting the script's stdin into a file (actually a named pipe) whose name can be passed to the command.  Like this:
if [[ $# -gt 0 ]]; then
  command "$@" <<EOF
here-doc goes here
EOF
else
  command <(cat) <<EOF
here-doc goes here
EOF
fi

This uses <() to launder the script's stdin through cat to a named pipe, which is then passed to command as an argument.  Meanwhile, command's stdin is taken from the here-doc.
Now, I think that's what you want to do, but it's not quite what you've asked for, which is to both redirect the script's stdin from the supplied files and pass stdin to the command inside the script.  This can be done by combining the above techniques:
if [ $# -gt 0 ]; then
  exec < <(cat "$@")
fi

command <(cat) <<EOF
here-doc goes here
EOF

...although I can't think why you'd actually want to do this.

A: The Perl diamond operator essentially loops across all the command line arguments, treating each as a filename. It opens each file and reads them line-by-line. Here's some bash code that will do approximately the same.
for f in "$@"
do
   # Do something with $f, such as...
   cat $f | command1 | command2
   -or-
   command1 < $f
   -or-
   # Read $f line-by-line
   cat $f | while read line_from_f
   do
      # Do stuff with $line_from_f
   done
done

A: You want to take the first argument and do something with it, and then either read from any files specified or stdin if no files?
Personally, I'd suggest using getopt to indicate arguments using the "-a value" syntax to help disambiguate, but that's just me.  Here's how I'd do it in bash without getopts:
firstarg=${1?:usage: $0 arg [file1 .. fileN]}
shift
typeset -a files
if [[ ${#@} -gt 0 ]]
then
  files=( "$@" )
else
  files=( "/dev/stdin" )
fi
for file in "${files[@]}"
do
  whatever_you_want < "$file"
done

The ?: operator will die if there are no args specified, since you seem to want at least one arg either way.  After grabbing that, shift the args over by one, and then either use the remaining args as your file list, or the bash special filehandle "/dev/stdin" if there were no other args.
I think that the "if no files are specified, use /dev/stdin - otherwise use the files on the command line" piece is probably what you're looking for, but the rest of the code is at least useful for context.

A: Also a little cheezy, but how about this:
if [[ $# -eq 0 ]]
then
  # read from stdin
else
  # read from $* (args)
fi

If you need to read and process line-by-line (which is likely) and don't want to copy/paste the same code twice (which is likely), define a function in your script and just pass the lines one-by-one to this function, and process them in said function.

A: Why not use ``cat @* in the script? For example:
x=`cat $*`
echo $x


text:
Q: Validating collection elements in WPF I would like to know how people are going about validating collections in WPF. Lets say for example that I have an observable collection of ViewModels that I am binding to the items source of a grid, and the user can add new rows to the grid and needs to fill them.
First of all I need to validate on each row to ensure that required fields of each ViewModel are filled in. This is fine and simple to do for each row.
However, the second level of validation is on the collection as a whole. For example i want to ensure that no two rows of the collection have the same identifier, or that no two rows have the same name. Im basically checking for duplicate properties within different rows. I also have more complex conditions where I must ensure that there is at least one item within the collection that has some property set.
How do I get a validation rule that would allow me to check these rules, validating on the whole collection rather than the individual items. I also want to print any validation error above the datagrid so that the user can fix the problem and the message will update or disappear as the user fixes each different rule.
Anyone have any experience of the proper way to do this?

A: The trick is to place your collection validation logic such that it's called when the ItemsControl's ItemsSource property changes.  If you're using IDataErrorInfo on your view-model, then set ValidatesOnDataErrors=True on the ItemsSource binding and, when the bound collection property's name is passed into the interface's error indexer, run the logic to determine if the property is still valid or not.  If you're using custom validation rules, then putting the rules into the ItemsSource binding should be fine, to.
Next, in your view-model, raise the PropertyChanged event for the ItemsSource-bound property whenever an event occurs which changes the collection's valid/invalid state.  For example, if the collection needs a certain number of elements, then listen to the CollectionChanged event.  Whenever the collection changes, raise the PropertyChanged event for the ItemsSource-bound property.  This tells WPF that the property changed, which leads to its revalidation.  Thus, your collection validation logic will run whenever the collection changes and, if the collection is invalid, WPF displays the error adorner or, if the collection becomes valid, WPF removes the adorner.


text:
Q: Getting week started date using MySQL If I have MySQL query like this, summing word frequencies per week:
SELECT
  SUM(`city`),
  SUM(`officers`),
  SUM(`uk`),
  SUM(`wednesday`),
  DATE_FORMAT(`dateTime`, '%d/%m/%Y')
FROM myTable
WHERE dateTime BETWEEN '2011-09-28 18:00:00' AND '2011-10-29 18:59:00'
GROUP BY WEEK(dateTime)

The results given by MySQL take the first value of column dateTime, in this case 28/09/2011 which happens to be a Saturday.
Is it possible to adjust the query in MySQL to show the date upon which the week commences, even if there is no data available, so that for the above, 2011-09-28 would be replaced with 2011/09/26 instead? That is, the date of the start of the week, being a Monday. Or would it be better to adjust the dates programmatically after the query has run?
The dateTime column is in format 2011/10/02 12:05:00

A: It is possible to do it in SQL but it would be better to do it in your program code as it would be more efficient and easier. Also, while MySQL accepts your query, it doesn't quite make sense - you have DATE_FORMAT(dateTime, '%d/%m/%Y') in select's field list while you group by WEEK(dateTime). This means that the DB engine has to select random date from current group (week) for each row.  Ie consider you have records for 27.09.2011, 28.09.2011 and 29.09.2011 - they all fall onto same week, so in the final resultset only one row is generated for those three records. Now which date out of those three should be picked for the DATE_FORMAT() call? Answer would be somewhat simpler if there is ORDER BY in the query but it still doesn't quite make sense to use fields/expressions in the field list which aren't in GROUP BY or which aren't aggregates. You should really return the week number in the select list (instead of DATE_FORMAT call) and then in your code calculate the start and end dates from it.


text:
Q: Is there a way to extract all values by some key from a list of maps using SpEL? Let's assume there's a map corresponding to the following structure:
{
  "lists": [
    {
      "list": [
        {
          "letter": "a"
        },
        {
          "letter": "b"
        }
      ]
    },
    {
      "list": [
        {
          "letter": "c"
        },
        {
          "letter": "d"
        }
      ]
    }
  ]
}

There's an easy way to get all lists using SpEL (#root['lists']) or all letters of the first list ("#root['lists'][0]['list']") or the first letter of the first list ("#root['lists'][0]['list'][0]"). Also, there's a projection mechanism which allows using construction like "#root['lists'].![#this['list']]" to convert each item of lists to a result of the projection expression.
However, given all these possibilities, I still failed to come up with an expression allowing me to extract all letters from both lists. For the example above, I'd like to get
[
  {
    "letter": "a"
  },
  {
    "letter": "b"
  },
  {
    "letter": "c"
  },
  {
    "letter": "d"
  }
]

I tried to use the projection mechanism to achieve my goal but it didn't really help. The problem I see is that every time SpEL detects a list, it applies the projection expression to each element of the list so any structure of nested lists can't be changed this way.
The problem I solve can be easily solved using JsonPath, however, I assume I could get something wrong and didn't notice a way to achieve the same result using SpEL. I would be happy to listen to any ideas.


text:
Q: I cant get my mailto contact form to work I have tried to make a contact form in a modal window. I thought I had done everything correctly but when I click send, I don't receive the email. Can anybody please show me where I'm going wrong?
Thanks very much in advance. Merry Xmas!

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Contact McGregor Beauty

<form id="contact" method="post" action="mailto:aka_pipsqueak@msn.com">
Your Name    <input class="input-xlarge" type="text" placeholder="Please write your name here" required>

Your Email    <input class="input-xlarge" type="email" placeholder="Please enter your email address here" required>

Phone(Optional)   <input class="input-large" type="number" placeholder="Add a telephone number">

Treatments of Interest

<input type="checkbox" value="Waxing & Tinting">Waxing & Tinting

<input type="checkbox" value="Massage">Massage

<input type="checkbox" value="Reflexology">Reflexology

<input type="checkbox" value="Manicure/Pedicure">Manicure & Pedicure

<input type="checkbox" value="MLD">MLD

Your Questions/Comments
<textarea rows="2" style="width:500px" type="text" required></textarea>

<button class="btn btn-primary" type="submit" data-dismiss="modal" aria-hidden="true">Send</button>

</form>

A: what mail server are you using?
where is the server side code used to handle the http request of the form?
Just having a form in html isn't going to do anything, and an action of mailto: is not correct, nor would you want to do this because this email address can be seen in the markup and will be spammed until you close it.
what programming language are you planning to use?
Here's a basic example you can follow using php:
http://www.w3schools.com/php/php_mail.asp


text:
Q: Let $A$ be an $m \times n$ real matrix and $b \in \Bbb R^m$ with $b \neq 0$ . Then

*

*The set of all real solutions of $Ax=b$ is a vector space.

*If $u$ and $v$ are two solutions of $Ax=b$, then $\lambda u+ (1-\lambda)v$ is also a solution of $Ax=b$ $\forall \lambda \in \Bbb R$.

*For any two solutions $u$ and $v$ of $Ax=b$, the linear combination $\lambda u+(1-\lambda)v$ is also a solution of $Ax=b$ only when $0 \le \lambda \le 1$

*If rank of $A$ is $n$, then $Ax=b$ has at most one solution.

Option 2 is correct because $A(\lambda u +(1-\lambda)v)=\lambda Au+ Av -\lambda Av=b$. Hence option 3 is false.
Option 1 seems to be incorrect because $x \neq 0$ by hypothesis.
How can I check whether option 4 is true or not?
Am I right so far?

A: What you have done is correct. For option $4$:
Since $\operatorname{Rank} A=n\implies \operatorname{Nullity} A=0$ by Rank-Nullity Theorem.
Hence $Ax=0$ has only solution as $x=0$.Hence if $Ax=b$ has a solution then it is unique.


text:
Q: Swift2 Huge delay in many UIEvents I usually don't ask questions here, but this makes no sense.
After I load and parse a Json (with swiftyjson) I call this methods:
 //remove a loadin screen
 uiviewLoader?.removeFromSuperview()
 print("uiview loader removed")

 self.collectionView.reloadData()
 print("refresh table")

And thats its.
The thing is, it prints boths msgs (both in emulator and in physical device) but it takes like 15 seconds to see the effects of this lines.
Do I need an extra call??  I have the latest xcode..
Thanks for any tips or advices.
****** More Info ******
I load a json in another class.  when completed loading and parsing, it calls a method in my viewController
func jsonParseado(res:Bool){
   print("json result = \(res)")
   if res {
   uiviewLoader?.removeFromSuperView()
   print("loading uiview removed from superview")
   self.collectionView.reloadData()
   print("refresh data with new values")
   ...
   else{
     ...
   }

And after I see the results prints, it takes about 10-15 seconds to remove the loading view and show the collection controller.

A: Ok. luk2302 u were right.
the problem is that Im no longer in the main thread.
I solve the problem with
dispatch_async(dispatch_get_main_queue()) {
            self.collectionView.reloadData()
            self.uiviewLoader?.removeFromSuperview()

            print("reload in main thread..")
        }
//this actually works!!

I did load the json with swifty json, wich uses another thread to do so.
but im not sure when I left the main thread...
Thank you all.


text:
Q: Jasmine + AngularJS resourceService is removing `$promise` I request some resources from the server with resourceService.newOrGet(...). Then I nest the promise resolutions with then so that a callback triggers after all have been resolved.
This works fine in my browser, but when I run it with karma + jasmine, the $promise elements get removed after the first then:
$scope.a = resourceService.newOrGet('/a.json');
$scope.b = resourceService.newOrGet('/b.json');
$scope.c = resourceService.newOrGet('/c.json');

console.log([!!$scope.a.$promise, !!$scope.b.$promise, !!$scope.c.$promise]);
// => [true, true, true]
$scope.a.$promise.then(() => {
  console.log([!!$scope.a.$promise, !!$scope.b.$promise, !!$scope.c.$promise]);
  // => [true, true, false]
  $scope.b.$promise.then(() => {
    // => [true, true, false]
    $scope.c.$promise.then(() => {
      myCallback();
    }
  }
}

In the browser, all of the promises get printed for each console.log invocation. But in karma-jasmine, the last $scope.c.$promise is undefined in all but the first invocation, and I get a

Cannot read property 'then' of undefined

error when I reach $scope.c.$promise.then.
Any idea why or what I can do about that?
AngularJS v1.5


text:
Q: Area of n overlapping circle I have n circles with individual radius and center point. Some or all of the circles might or might not overlap. How can I calculate their area in total, so that overlapped areas are only counted once?
I know how to do it for 2 circles:
https://www.desmos.com/calculator/ztx7frvvh6


text:
Q: Integration in python containing some parameter I want to perform integration of an equation with one variable and few constants in the form of symblos namely, A,k,p whose values I have planned to enter after integration. Integrating equation with only one variable but with no other symbol(containing some constant value) is simple and direct, but for the case in which symbols are present, integration using quad from scipy.integrate gives an error. Actually quad() requires the values of all symbols to be pre-defined. I want a solution where I don't have to enter the values for symbols beforehand but take an input and substitue them afterwards.
To make the problem even more clear,
I want to integrate a wave equation

A * sin(kx + wt) , where A is amplitude, w is angular velocity, t is time and x is position (x is only variable )

quad() requires to define the values for A, k and p before integrating but what I want to do is first integrate A * sin(kx + wt) and then substitue the values for A, k and p in the result by taking user input
.
Please suggest a method to do so :)

A: We can use sympy library for integrating a function without assigning values for its symbols(having some constant real number as its value) (A,k,p and s).
Example code from one of my projects:
from sympy import *
A = symbol('A')
k = symbol('k')
p = symbol('p')
x = symbol('x')
s = symbol('s')

f = integrate(exp(-1*s*x)*A*sin(k*x+p),(x,0,oo))

f = f.subs(A,50)

print str(f)

(x,0,oo) means integrate wrt x from zero (0) to infinty(oo)

What the code requires to be done is, first define constants A, k, p and s as well as the variable x as symbols and then use integrate() to integrate the expression.
integrate() returns the integrated expression and now, f.subs(symbol,value) is used to substitue the values of symbols.

in f.subs(symbol,value) , f is the variable containing the integrated expression, symbol is the symbol defined earlier(like A,k,p) and value is the constant value for that symbol.

This method also helps to get definite integration(from x=a to x=b) of equations. What one has to do is substitute the value of x with b and store it in some variable m using m = f.subs(x,b) and then use n = f.subs(x,a) to substitute the value of x with a and store it in some variable n. Now, substract m and n using m - n to get the definite integral of the expression

There is one more possibe solution to the question.

What can be done is define a function which takes user inputs for A, k and p and then use quad() to integrate the expression, this will wipe out the need to first integrate the expression and then take user input to substitue the values of symbolic constants

A: It appears you are not defining the variable "A", try doing
A=15

Or anything  like that, just make sure you define A before calling it.


text:
Q: Converting UTF-16BE to UTF-8 in Java ME I am writing an app in Java ME for old Symbian devices (and not only them). I have a problem. I am trying to draw emojis using png images. They are stored on some server in 2 folders. The first folder does not contain new emojis after year 2017 and I have to change my code.
Old code to guess the filename:
Integer.toHexString((int) text.toCharArray()[ii-1]).toUpperCase()+Integer.toHexString((int) text.toCharArray()[ii]).toUpperCase()+".png"

This helps me to convert  emoji with integer codes of 2 symbols 55356 57147 to D83CDF3B.png
Now I need to get
f09f8cbb.png from the same emoji.
The website
https://unicode-table.com/en/1F33B/ says that UTF-8 F0 9F 8C BB and
UTF-16BE D8 3C DF 3B is the same. How can I convert from UTF16BE to UTF-8 ? All the code I had found on the net is in C or Javascript and does not suite to me.
On StackOverflow, I also found this code
try {
    // Convert from Unicode to UTF-8
    String string = "\u003c";
    byte[] utf8 = string.getBytes("UTF-8");

    // Convert from UTF-8 to Unicode
    string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}

But it returns the same String as I give to it.

A: This helped me in Java ME, in compliance to Java 1.3.
static String bytesToHex(byte[] bytes) {
        final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

String HexOfString(String str) {
   byte[] utfString = str.getBytes("UTF-8");
   return bytesToHex(utfString);
}

From  emoji I got "F09F8CBB"


text:
Q: Makefile with different header directories? //Root
Main.c
makefile
objs/  //I want to store the .o files here if possible.
refs/
    - header1.h
    - header1.c
    - up to 8 headers

So this is my file structure, I know it's not the best but it's just for a school project. The header files are included in the Main.c,
CC = gcc

INCLUDES = -I/refs

CFLAGS = -g $(INCLUDES)

ODIR = /objs

HLOC = /refs

main.o: main.c
    $(CC) $(CFLAGS) main.c -o $(wildcard *.o)

main: main.o
    $(CC) $(CFLAGS) main.c -o main

#clean:
    #rm $(wildcard *.o)

I am unsure how to actually do this, this is what I have so far but I unsure how to proceed or how to get this to work. I have searched extensively and cannot find an answer.
Thanks!

A: I'm assuming "Main.c" at the top is a typo. I put this together without testing but it should at least convey the idea well enough. I used some GNU Automatic Variables in here, if you don't know about them you should read the manual.
I made a target default which is going to build objs and then bins
# default target, will be called if no target provided
default: objs bins

CC = gcc
INCLUDES = -I./refs
CFLAGS = -g $(INCLUDES)
ODIR = ./objs
HLOC = ./refs

OBJS = $(ODIR)/main.o
BINS = main

# target called from default
objs: $(OBJS)

# target to build your object files
$(ODIR)/%.o: %.c
    $(CC) $(CFLAGS) -c $< -o $@

#target for your binary
main: $(ODIR)/main.o
    $(CC) $< -g -o $@

#clean build artifacts
clean:
    rm -f $(BINS)
    rm -f $(OBJS)

Don't forget that tabs are required on recipe lines. If you run into issues paste the errors you're getting!


text:
Q: Unknown object in Python and Boolean operation Consider this Unknown class:
class Unknown:
    def __add__(self, other):
        return self
    def __radd__(self, other):
        return self

unknown = Unknown()
assert (unknown + 1) is unknown
assert (1 + unknown) is unknown

This also works for __mul__, __rmul__, etc.
However, for Boolean operators e.g.:
assert (unknown or True) is True
assert (unknown or False) is unknown

Attempts such as -
def __or__(self, other):
    return self if not other else other

- or any other combination did not work for me.
Note that I am also unable to define __bool__(self) since it's return value isn't True nor False and returning NotImplemented is not allowed.
So my question: is it possible to override the or, and and operators so that it might return something other than True or False?

Edit: Thanks to @CoryKramer and @Martijn Peters comment below.
I was under the impression that __or__ is for the logical or operator. It is not. It is for the bitwise | and in fact there is no way to override the logical or operator.

A: Why not? Did you try? Seems to work just fine...
class Unknown:
    def __add__(self, other):
        return self
    def __radd__(self, other):
        return self
    def __or__(self, other):
        return self

unknown = Unknown()
assert (unknown or unknown) is unknown


text:
Q: Report of Pages Author (Publisher) name I'm working on a large scale content-base website
in this website many Users produce content in many type of pages, and i want to know how many users(author) create how many page and produce content (for example in this month)
(no difference on reports or front-end)
is there any add-on?

A: There is no addon for this.  First you have to define what "create how many page" and "produce content".. is this the the act of adding a page? or publishing the page?  it editing the page at all producing content?
There is a "core" report in the cms module named Recently Edited.  You can examine this to determine how reports work.  Then you will need to add various extension "hooks" to track the operations required...

*

*onBeforeWrite

*onAfterWrite

*onBeforePublish

*onAfterPublish

Within these methods you will probably need to log the data you wish to report on along with Member::currentUserID() and remember while in an extenstion to access the object you need to use $this->owner->FieldName (instead of ($this->FieldName).


text:
Q: Naxsi - blacklist and whitelist setup with Nginx Opened this issue:

https://github.com/nbs-system/naxsi/issues/486

But is seems not to be active there.
I am using in my project currently modsecurity to filter out bad IPs and allow good ones:
Something like this:
modsecurity_rules '
      SecRuleEngine On
      SecRule REMOTE_ADDR "@ipMatchFromFile /etc/modsecurity/whitelist.txt" id:1,phase:1,allow
      SecRule REMOTE_ADDR "@ipMatchFromFile /etc/modsecurity/blacklist.txt" id:2,phase:1,deny,status:429,msg:\'blacklist\'

What would be the best approach to add this functionality to NAXSI?
Should I add a Rule or modify the code? Can you give some tips on either one, both or none, when this is not possible (are there any performance implications or implications in general)
Any other possibility to achieve this goal in NGINX setup?
Tried this approach:
############################
## Block rules: 1700-1800 ##
############################

MainRule "str:1.1.1.1" "msg:IP Blacklist" "mz:$HEADERS_VAR:X-Forwarded-For" "s:$BLACK:8" id:1701;
MainRule "str:2.2.2.2" "msg:IP Blacklist" "mz:$HEADERS_VAR:X-Forwarded-For" "s:$BLACK:8" id:1702;

Where 1.1.1.1 and 2.2.2.2 will be IP I want to block (from Blacklist) - I will generate the config/list daily.
However, I still don't know how to whitelist some IPs, so that they will never be blocked (through block rules but also through other rules). Any ideas?
Was thinking about Whitelist rule for all:
MainRule wl:0 "mz:$HEADERS_VAR|X-Forwarded-For:xxx.xxx.xxx.xxx";

BUT it is also not a valid rule ....
What approach would you suggest?

A: I think for this purpose you could use ngx_stream_access_module module.
You could create two lists and include them to your projects nginx config file.
For example:
include /path/to/file/blacklist.conf
include /path/to/file/whitelist.conf


text:
Q: How does the heater circuitry work? I have this BreadMaker that I want to modify. I do not have the schematics or the sources. Below is the schematic I draw of the circuitry of the heating element. The microcontroller is 5V and output is only digital I/O or ADC. This is used as an output digital to control the heater element. I see that the schematic around relay is not complete but that's not important for the uncertainties. What I do not understand is:
1) why there are 2 transistors in series
2) the voltage measured with multimeter at microcontroller pin is arround 2V instead of 5V
3) why there is a capacitor in series with microcontroller's output
4) how does the whole circuitry work
5) what's with D4

For reference the microcontroller is SH69P55A and the output is PIN 7. Both transistors are model SS8050. All three diods are same model 1n4148.

A:
1) why there are 2 transistors in series

There's a good possibility that they are two MOSFETs wired as a solid state relay or SSR. If they are two NPN transistors as shown this may be some kind of fail-safe-under-one-fault circuit (after all you don't want one BJT to fail short circuit for possible reasons of creating a fire). If that's the case then having two BJTs in series offers some extra protection against this.

2) the voltage measured with multimeter at microcontroller pin is
  arround 2V instead of 5V

That's likely because the MCU is producing a square wave drive.

3) why there is a capacitor in series with microcontroller's output

It's a safety feature in case the MCU crashes - because it's likely that under normal operation the MCU is producing a square wave output, this can pass through the capacitor and be converted back to a DC level on C3.

4) how does the whole circuitry work

Well, given that there are schematic parts that don't make sense I can't really tell you other than the MCU produces a square wave and this gets through a capacitor and is rectified to produce a control voltage for the SSR (solid state relay) which turns on the heater.

5) what's with D4

This is one area where your schematic is probably wrong or lacking information.

A: *

*It's probably for fail-safe. There is no need of a flyback diode when the transistor is driven from the emitter as shown, by the way. The charge pump (C2/C3/D3/D3) means that even if the MCU output gets stuck high or low, the relay will drop out.

*Probably a square wave as Andy says. Average voltage will be about 1/2 Vcc, minus a bit because of loading.

*See 1.

*It's probably to deal with a transistor failing short, but requires more analysis. There may be something wrong with your tracing wrt the relay connections, also needs values for the resistors.
These are all cheap jellybean parts, but you are clearly messing with a safety-critical part of the circuitry so be careful in any modifications. In particular do NOT remove or bypass any hardware safety cutoffs such as thermal fuses or mechanical thermostats.


text:
Q: return value to main In the code below I am trying to have the variable fullName be populated with whatever I enter during the operation of the function namecheck. I am not sure where I am going wrong. Please help and thank you for it.
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>

using namespace std;

string namecheck();

int main()
{
    cout<<fixed;

    string firstName;
    string lastName;
    string fullName;
    char action;
    int pin;
    int pinTry =1;
    int actionsTaken =0;
    int joeyPin = 4433;
    int mildredPin = 2849;
    double joeyTotal = 3742.55;
    double mildredTotal = 19.36;
    double withdraw;
    double deposit;

    namecheck();
    cout<<fullName;
}

string namecheck(){
    string firstName;
    string lastName;
    string fullName;
    string completeName;
    double joeyTotal = 3742.55;
    double mildredTotal = 19.36;

    cout<<"Welcome to Blah National Bank!\n";
    cout<<"What is your first name?\n";
    cin>>firstName;
    if (firstName == "END"){
        cout<<"User totals: \n"
            <<"Joey Stowy:\t"<<setprecision(2)<<joeyTotal<<endl<<endl
            <<"Mildred Moredebt:\t"<<setprecision(2)<<mildredTotal<<endl<<endl;
    }
    if (firstName != "END"){
        cout<<"What is your last name?\n";
        cin>>lastName;
    }
    fullName = firstName+" "+lastName;

    return fullName;
}

A: Change:
namecheck();
cout<<fullName;

to:
fullname = namecheck();
cout<<fullName()

.

A: When you call namecheck() in main, assign the result to fullName:
fullName = namecheck();


text:
Q: PHP post failed cloudflare api i'm trying to update my DNS domain record through cloudflare api using PHP Post, but the cloudflare api send response that POST method is not allowed for the api_token authentication scheme, i already tried the the api using postman and it works, but somehow in PHP the api does not work, is PHP does not support POST using token ?, some variable is stored inside env.php and i hide it because it sensitive information.
PHP code :
    include("../../env.php");

    //variable input by POST
    $domain = $_POST['domain'];
    $recordID = $_POST['recordID'];
    $content = $_POST['content'];
    $zoneID = $_POST['zoneID'];

    //for update record
    $linkRecord = "https://api.cloudflare.com/client/v4/zones/$zoneID/dns_records/$recordID";

    $header = array(
        "Content-Type: application/json",
        "Authorization: Bearer $authToken"
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $linkRecord);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $bodyArray = array("type"=>"A","name"=>$domain,"content"=>$content,"proxied"=>true);

    $body = json_encode($bodyArray);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    $resp = curl_exec($curl);

    print_r($resp);

linkRecord Variable Value:
https://api.cloudflare.com/client/v4/zones/{{my_secret_zone_id}}/dns_records/{{id_of_the_record}}

Cloudflare response of POST :
{
  "success": false,
  "errors": [
    {
      "code": 10000,
      "message": "POST method not allowed for the api_token authentication scheme"
    }
  ]
}


text:
Q: on mouse over change image on html I was trying to make an image to change on mouse over. This piece of code works for IE but not for the other browsers like chrome, opera, safari, etc. Any ideas?

A: You should be using a ID, not a NAME, and using document.getElementById to select the element.
IMG elements, not being FORM elements, should not be able to take on a NAME property, but Microsoft managed to screw this up.

Also, it's much easier and cleaner to use a CSS background and a :hover declaration and skip doing this using JavaScript completely.
Here's how:
HTML:

CSS (adjust dimensions accordingly):
.myButton {
     width:100px;
     height:50px;
     display:block;
     background-image:url(../img/login_button_11.jpg);

}

.myButton:hover {
     background-image:url(../img/login_button_22.jpg)
}

A:

Demo
http://jsfiddle.net/W6zs5/

A: Try this:


text:
Q: My recursive function seems to be using the original list instead of creating a new one in python I'm pretty new to python and I've been trying to write a minimax algorithm for tic-tac-toe. But I can't get my program to return the expected value and I'm not sure what's going on. My minimax method should be returning 1, but instead pretty much broken. I believe it's using the original list instead of creating a new one. I tried using copy() but it didn't work, unless I used it wrong. Here is my code:
import copy

def checkWin(board):
    if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'y', 'x']]:
        return 't'
    if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'x', 'y']]:
        return 'y'
    return '0'

def minimax(board, player):
    status = checkWin(board)
    if status == 't':
        return 0
    if status == 'y':
        return 1

    if player == 'y':
        value = -100000
        for i in range(3):
            for k in range(3):
                if board[i][k] == '':
                    board2 = copy.deepcopy(board)
                    board2[i][k] == 'y'
                    bestMove = minimax(board2, 'x')
                    if bestMove > value:
                        value = bestMove
        return value

    else:
        value = 100000
        for i in range(3):
            for k in range(3):
                if board[i][k] == '':
                    board2 = copy.deepcopy(board)
                    board2[i][k] == 'x'
                    bestMove = minimax(board2, 'y')
                    if bestMove < value:
                        value = bestMove

        return value

board = [
            ['y', 'x', 'y'],
            ['x', 'y', 'x'],
            ['x', 'x', '']
        ]
bestMove = minimax(board, 'y')
print(bestMove)

Any help is appreciated, thanks.
Edit. Thanks to the people who helped, I'm sorry I'm such an idiot. But I will make sure to learn how to debug my programs more carefully and thoroughly.

A: You want to assign value not compare board2[i][k] == 'x' should be board2[i][k] = 'x' same with y.
import copy

def checkWin(board):
    if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'y', 'x']]:
        return 't'
    if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'x', 'y']]:
        return 'y'
    return '0'

def minimax(board, player):
    status = checkWin(board)
    if status == 't':
        return 0
    if status == 'y':
        return 1

    if player == 'y':
        value = -100000
        for i in range(3):
            for k in range(3):
                if board[i][k] == '':
                    board2 = copy.deepcopy(board)
                    board2[i][k] = 'y'
                    bestMove = minimax(board2, 'x')
                    if bestMove > value:
                        value = bestMove
        return value

    else:
        value = 100000
        for i in range(3):
            for k in range(3):
                if board[i][k] == '':
                    board2 = copy.deepcopy(board)
                    board2[i][k] = 'x'
                    bestMove = minimax(board2, 'y')
                    if bestMove < value:
                        value = bestMove

        return value

board = [
            ['y', 'x', 'y'],
            ['x', 'y', 'x'],
            ['x', 'x', '']
        ]
bestMove = minimax(board, 'y')
print(bestMove)


text:
Q: Add new polygon below everything in Google Maps API I have a Google.Map object with a set of polygons and polylines already being displayed on that.
I want to add a new google.maps.Polygon object that should be displayed below all elements (more or less like a "background" polygon).
I tried to add it with an absurd low zIndex value (-999999), but it still is displayed above all other elements.
This is what I have done so far:
            whiteBackground = new google.maps.Polygon({
                path: [ {lat:40.1, lng:-97.1},
                        {lat:40.1, lng:-89.8},
                        {lat:44.5, lng:-89.8},
                        {lat:44.5, lng:-97.1} ],
                strokeColor: "#FF0000",
                fillColor: "#FFFFFF",
                strokeOpacity: 1.0,
                strokeWeight: 1.5,
                fillOpacity: 1.0,
                zIndex: -999999
            });

            // add to map and to list
            whiteBackground.setMap(my_map);

Is there a way to force new polygon whiteBackground to have the smallest zIndex value in the Google.Map in which it is going to be add?
Or there is an way to iterate over all current elements in a Google.Map object?

A: It works if you set the zIndex properties of all the polygons.
proof of concept fiddle (moves smaller polygon above/below larger polygon on click of the button)
code snippet:

// This example creates a simple polygon representing the Bermuda Triangle and a small polygon that starts above it, toggles above/below by clicking the button (large polygon has zIndex=0; small polygon is +/-1.

var map;
var infoWindow;
var poly2;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5,
    center: {
      lat: 24.886,
      lng: -70.268
    },
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });
  // Define the LatLng coordinates for the polygon.
  var triangleCoords = [{
    lat: 25.774,
    lng: -80.190
  }, {
    lat: 18.466,
    lng: -66.118
  }, {
    lat: 32.321,
    lng: -64.757
  }];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    zIndex: 0
  });
  bermudaTriangle.setMap(map);

  var poly2Coords = [{
    lat: 26.78484736105119,
    lng: -72.24609375
  }, {
    lat: 27.059125784374068,
    lng: -68.8623046875
  }, {
    lat: 23.926013339487024,
    lng: -71.806640625
  }];

  poly2 = new google.maps.Polygon({
    paths: poly2Coords,
    strokeColor: '#0000FF',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    zIndex: 1
  });
  poly2.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}

<input id="btn" type="button" value="click" onclick="if (poly2.get('zIndex') > 0) poly2.setOptions({zIndex:-1}); else poly2.setOptions({zIndex:1});" />


text:
Q: Make VSCode python debug print output to terminal When debugging, vscode will not print output to terminal when print(..). I try to set "console": "externalTerminal",but it does not work, neither with "console": "IntegratedTerminal".
I figure out why this happends, since python will not print output until it meets newline. For example,
print("hello", end=" ") # will not output
print("world") # will output "hello world"

A: To see printed outputs in your terminal, make sure that your panel is showing first off ('view' -> 'appearance' -> 'show panel').
Then check that you are viewing the right part of the panel. VSC has a 'debug console' and a 'terminal'. The 'debug console' is a place to test inputs and outputs with your code, but any print statements will be output to your terminal.
screenshot here


text:
Q: .JSON file creates NULL value via PHP So I'm trying to figure out why I get a NULL value in my .json file after I try to write the array to it. It only happens with the 'array_push' line after creating a new file. If there is a .json file already there with a value in it, it'll write to it correctly. The only thing I could guess was the file is missing the '{' and '}' in it upon creation.
I've got a small work around so far, but not sure that this is the right way to do it. Can someone tell me if this is good or bad?
Just to clarify, the .json document only holds the vault of NULL, there are no array elements or anything in the file besides the word NULL.
//CHECK IF FILE EXISTS, ELSE CREATE IT
$log_filename = "./site_files/logs/error-404-log.json";
if(!file_exists($log_filename)) {
    touch($log_filename);
    //LINE BELOW IS MY WORK AROUND, I'M NOT SURE IF THIS IS THE RIGHT WAY
    file_put_contents($log_filename, json_encode(json_decode("{}")));
    echo "$log_filename was created.
";
}

$log_array = array();
$new_data =  array(
    'current_date_stamp' => $current_date_stamp,
    'current_page_trail' => $current_page_trail
);

$json_data = file_get_contents($log_filename);
if($log_array != "") { $log_array = json_decode($json_data, true); }
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);

file_put_contents($log_filename, $json_data);

A: $log_filename = "error-404-log.json";                // establish the path/to/filename.json
if (file_exists($log_filename)) {                    // if path/to/filename.json exists
    $json = file_get_contents($log_filename);        // access PRETTY json string
    echo "pre-existing data:

$json

";  // display json string
    $array = json_decode($json, true);               // decode to prepare for new data
}

// data always maintains the same structure: an array of 2-element arrays
$array[] = [
    'current_date_stamp' => date('Y-m-d H:i:s'),
    'current_page_trail' => "foo"
];

// create/update the file
$new_json = json_encode($array, JSON_PRETTY_PRINT);  // re-encode updated array data
echo "new data:

$new_json

";    // display new json string
file_put_contents($log_filename, $new_json);         // create or overwrite file

A: Your code is failing because you are comparing $log_array with an empty string, this condition will always pass because this array will never be an empty string. In the if statement you decode the contents of the file, when the file has no content this will be an empty string and it will return NULL, after this you write this NULL value to your file. If you check if $json_data is an empty string your code should work, I would also recommend doing it like this:
$log_array = array();
$new_data =  array(
 'current_date_stamp' => $current_date_stamp,
 'current_page_trail' => $current_page_trail
);

$json_data = file_get_contents($log_filename);
if($json_data != "") {
    $log_array = json_decode($json_data, true);
    //WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
    array_push($log_array, $new_data);
    $json_data = json_encode($log_array, JSON_PRETTY_PRINT);

    file_put_contents($log_filename, $json_data);
}

This is better since if the string is empty all other actions are irrelevant.


text:
Q: Disconnecting unwanted remote access If someone is remotely connected to my single ARM board computer with Debian 32-bit OS, (example: thru hijacking the browser), which connects through a firewall on a separate Orange Pi board, and I run shutdown, I have been told that the remote users/ hackers will "immediately" be disconnected from my computer and  they can't see what I do before shutdown completes in the next 60 seconds.
1) In order for the first premise to ring true, do I need to be in admin "#", for example:  # shutdown  ?
2) After reading more, it seems that by NOT including "-h" (shutdown -h now) it does not actually halt the system; it still allows the administrator to remain logged in as root. If I omit the -h, will the remote hackers still be disconnected immediately with just shutdown now?
3) If I type shutdown +90, will the remote hackers be disconnected immediately, and then for the next 90 minutes as well?


text:
Q: Array serialize issue in smarty tpl I want save the output of an array in a hidden div in smarty tpl. I used {$product|@print_r} to do that. But I want that array to be serialized. Is there any way to get serialized $product array. Pls help.

A: best practice for serializing:
//serialize
$string = base64_encode(serialize($array));

//unserialize
$array = unserialize(base64_decode($string));

A: Have you tried {$product|@serialize}?


text: Q: How to add custom command to the command menu of chrome devtools? I want to write some helper functions in my web app or chrome extension. And I found chrome devtool command menu is really helpful. So I wander if I could add some costom command to invoker my helper function like adding custom commads into vscode command-palette. Thanks.


text:
Q: Phrase for use in written communications"no more information" In written formal letter should I say"I have no more information about his health state?"

A:
I have no further information about the state of his health.

would be more idiomatic.


text:
Q: Can't receive gmail repeatly with javamail Someone asked the same question here, but I  think it has not been solved yet.
I doubt the result  is due to google mail server policy.

A: It would be much better if you asked your own question, with your own details about what you're doing, what you've tried, what the results were, etc.
While you're working on that, see the JavaMail FAQ entries related to GMail and debugging.

A: replace 'username@gmail.com' in the 'Username' or 'Email' field with 'recent:username@gmail.com' . see Using POP on multiple clients or mobile devices


text:
Q: How to set default scroll position for LazyColumn without any feedback or animation in Jetpack Compose I want my LazyColumn to show items in the list from the middle so I can scroll up or down. I used rememberLazyListState but it has some delay and I don't want the scrolling action to happen in the UI.

A: val scrollState = rememberLazyListState(initialFirstVisibleItemIndex = 50)
val scrollState = rememberLazyListState(initialFirstVisibleItemScrollOffset = 3700)

You can use anyone of the parameter to start from a default position if you have 100 items in the list you could set initialFirstVisibleItemIndex = 50 so it starts from middle also you can set the offset but just use any one of them.
It works for me without any delay


text:
Q: move stdout out of the console, in portable C The target application can be used in "pipe" mode, which means it accepts input from stdin, and can output into stdout.
However, there is always a risk of a user making a mistake, directing output to stdout, without actually directing stdout towards "something" (a file, or a consumer program).
As a consequence, the console screen gets garbaged displaying binary data (since by default, stdout outputs to the screen).
Bottom line : I want to avoid binary output to be displayed into the console, automatically. It must be done in portable C, and not depend on external script.
A few potential ways of doing it :
1) Is it possible to detect that stdout is going to console, in order to redirect it somewhere else instead ? (including /dev/nul). Note that the code must be portable, and work for Windows and Linux (and BSD, OpenSolaris, etc.)
2) Alternative : is it possible to redirect stdout to "somewhere else" (such as /dev/nul) by default without actually harming a correct usage of the program, redirecting stdout to a valid consumer process ?

A: On a POSIX (e.g. Linux and OSX) system you can use the isatty function to check if stdout goes to a console or to something else:
if (isatty(STDOUT_FILENO))
    printf("Going to a console\n");
else
    printf("Standard output is redirected or piped\n");

Unfortunately there is no portable way to do this that works on both POSIX systems and Windows.


text:
Q: How to download multiple links in a cell? How can I download the images from a cell which are separated by ; character?
Here is an example cell (A2):
https://lh6.ggpht.com/uxLXvxuncWOm2mgU3ChtdGZ0eMp_WJTD4xrVxAKqCJMiR5ibaBbw-VUPJPjcGiqIDRbm=h310; https://lh3.ggpht.com/N7B7AVDDD0577crgHxHHo15uCkjSr3oimEwZWhF-VVxNYhRMIHd2eoI14WfuTHfMmtNC=h310; https://lh6.ggpht.com/c_pfo3A3fQh40udcyhdgGIVsBa_GB9A09O642Vlwi6ka4fqwyT9044pzU-jF_rjb4VX_=h310; https://lh5.ggpht.com/KqUgPKrZYuVa_AAOLtR0URf_8pJ_lX6au7UH2pcHzs7G3eLL9Vt7hAk83JgkqVMBIQ=h310; https://lh6.ggpht.com/uxLXvxuncWOm2mgU3ChtdGZ0eMp_WJTD4xrVxAKqCJMiR5ibaBbw-VUPJPjcGiqIDRbm=h900; https://lh3.ggpht.com/N7B7AVDDD0577crgHxHHo15uCkjSr3oimEwZWhF-VVxNYhRMIHd2eoI14WfuTHfMmtNC=h900; https://lh6.ggpht.com/c_pfo3A3fQh40udcyhdgGIVsBa_GB9A09O642Vlwi6ka4fqwyT9044pzU-jF_rjb4VX_=h900; https://lh5.ggpht.com/KqUgPKrZYuVa_AAOLtR0URf_8pJ_lX6au7UH2pcHzs7G3eLL9Vt7hAk83JgkqVMBIQ=h900

There are so many cells in A column which contains image links like this one.
How can I save those images to a local folder?
It will be great if images rename to their URL, for example: The first image in cell A2:
uxLXvxuncWOm2mgU3ChtdGZ0eMp_WJTD4xrVxAKqCJMiR5ibaBbw-VUPJPjcGiqIDRbm.png

I've tested this VBA script:
Sub Save_image()
Dim oHTTP As Object
Dim sDestFolder As String
Dim sSrcUrl As String
Dim sImageFile As String

sDestFolder = "C:\Users\adale\Desktop\Compendium Images\"
sSrcUrl = ActiveCell.Value
If Left(sSrcUrl, 2) = "//" Then
    sSrcUrl = "https:" & sSrcUrl
End If

sImageFile = Right(ActiveCell.Value, Len(ActiveCell.Value) - InStrRev(ActiveCell.Value, "/"))
Debug.Print sImageFile
ActiveCell.Offset(0, 2).Value = sImageFile

Set oHTTP = CreateObject("msxml2.XMLHTTP")
oHTTP.Open "GET", sSrcUrl, False
oHTTP.send

Set oStream = CreateObject("ADODB.Stream")
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
oStream.Type = adTypeBinary
oStream.Open

oStream.write oHTTP.responseBody
oStream.savetofile sDestFolder & sImageFile, adSaveCreateOverWrite

Set oStream = Nothing
Set oHTTP = Nothing
End Sub

But it returns an error on this line:
oHTTP.Open "GET", sSrcUrl, False

A: Use the Split() method and use ; as the delimeter, then use a For Each loop to run a block of code for each URL:
'// Create single dimension array of image URLs
myImages = Split(ActiveCell.Value, ";")

For Each img In myImages
    '// Do whatever you want with each image URL here...
    '// If there are spaces inbetween then perhaps use Trim(img)
Next

'// Rest of code...


text:
Q: How to connect to an application that using kubernetes and is running in a docker container from local machine? I feel I have created an abomination. The goal of what I am doing is to run a docker image and start the AWX web application an be able to use AWX on my local machine. The issue with this is that AWX uses kubernetes to run. I have created an image that is able to run kubernetes and the AWX application inside a container. The final output after running my bash script in the container to start AWX looks like this:
NAMESPACE             NAME                                               READY   STATUS      RESTARTS        AGE
awx-operator-system   awx-demo-586bd67d59-vj79v                          4/4     Running     0               3m14s
awx-operator-system   awx-demo-postgres-0                                1/1     Running     0               4m11s
awx-operator-system   awx-operator-controller-manager-5b4fdf998d-7tzgh   2/2     Running     0               5m4s
ingress-nginx         ingress-nginx-admission-create-pfcqs               0/1     Completed   0               5m33s
ingress-nginx         ingress-nginx-admission-patch-8rghp                0/1     Completed   0               5m33s
ingress-nginx         ingress-nginx-controller-755dfbfc65-f7vm7          1/1     Running     0               5m33s
kube-system           coredns-6d4b75cb6d-4lnvw                           1/1     Running     0               5m33s
kube-system           etcd-minikube                                      1/1     Running     0               5m46s
kube-system           kube-apiserver-minikube                            1/1     Running     0               5m45s
kube-system           kube-controller-manager-minikube                   1/1     Running     0               5m45s
kube-system           kube-proxy-ddnh7                                   1/1     Running     0               5m34s
kube-system           kube-scheduler-minikube                            1/1     Running     0               5m45s
kube-system           storage-provisioner                                1/1     Running     1 (5m33s ago)   5m43s

go to http://192.168.49.2:30085 , the username is admin and the password is XL8aBJPy16ziBau84v63QJLNVw2JGmnb

So I believe that it is running and starting properly. The IP address 192.168.49.2 is the IP of one of the kubernetes pods. I have been struggeling to forward the info coming from this pod to my local machine. I have been trying to go from Kubernetes pod -> docker localhost -> local machine local host.
I have tried using kubectl proxy, host.docker.internal curl and a few other with no success. However I might be using these in the wrong form.
I understand that docker containers run in a very isolated environment so is it possible to forward this information from the pod to my local machine?
Thanks for your time!


text:
Q: How to prove error rate of ensemble model by using the Hoeffding's inequality? Under Binary classification situation,
error between function $f$ and basic learner(classifier) $h_i(x)$ is
$$P(h_i(x)≠f(x))=\mathcal{E}$$
It is assumed that T basic classifiers are combined by a voting method, and if more than half of the basic classifiers get the correct answer, it is assumed that the ensemble classifier gives the correct answer.
(Assume T is odd intger for convenience.)
$$H(x) = sign(\sum_{i=1}^T h_i(x))$$
If the error rates of the basic classifier are assumed to be independent of each other, the error rate of the ensemble classifier can be known by the Hoeffding inequality.
$$ P(H(x) ≠ f(x)) = \sum_{k=0}^{\lfloor T/2\rfloor} {}_T \mathrm{ C }_k (1-\mathcal{E})^k \mathcal{E}^{(T-k)} \le exp(-\frac{1}{2}T(1-2\mathcal{E})^2) $$
I can't understand how the result(exponential part) is derived.
I think $\lfloor T/2\rfloor = \frac{(T-1)}{2}$ because T is odd integer by the assumption above.
and given basic concept of the Hoeffding inequality of binary classification is
$$P(H(n) \le k) = \sum_{i=0}^{k} {}_n \mathrm{ C }_i \: p^i (1-p)^{(n-i)}
\le exp(-2\mathcal{E}^2n), \; (k=(p- \mathcal{E})n \; and \; \mathcal{E}>0)$$


text:
Q: Log4js not write into the file from the catch block I want to log errors on try catch construct using log4js. I have next code:
let log4js = require('log4js')
log4js.configure({
  appenders: {
    asterisk: {type: 'file', filename: 'filename'},
    out: {type: 'stdout'},
  },
  categories: {default: {appenders: ['asterisk', 'out'], level: 'all'}}
})
const logger = log4js.getLogger('asterisk')
async function myFunc() {
  try {
    let tmp = await someFunc()
  }
  catch (err) {
    logger.error(err)
    process.exit(1)
  }
}
myFunc()

When an error occurs, I see it in the console, but it is not written to the file. If I use logger outside try..catch block then everything works fine.
What could be the problem?

A: As suggested to me on GitHub, the problem is in the process.exit - this causes node to exit before the logger.error call (which is asynchronous behind the scenes) has written to the file.
Right code will be like this:
logger.error(err)
logger.shutdown(() => process.exit(1))

and it works fine.


text:
Q: JointPlot in seaborn My code-
num=[5,4,3,2,4,6,7,8,9]
df = pd.DataFrame({'abc':num})
da = seaborn.jointplot('abc', 'abc', data=df, kind="kde", space = 0.1, color="r", height=12)

This shows the error in numpy.linalg.linalgerror: singular matrix
If, I use the default kind argument, it works fine. But not for "kde".
And, I used the python interpreter to code, seaborn latest version 0.10.0
This code works fine in Google colab but not in python interpreter
Error Log-
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ubuntu/.local/lib/python3.6/site-packages/seaborn/axisgrid.py", line 2321, in jointplot
    grid.plot_joint(kdeplot, **joint_kws)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/seaborn/axisgrid.py", line 1785, in plot_joint
    func(self.x, self.y, **kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/seaborn/distributions.py", line 701, in kdeplot
    cbar, cbar_ax, cbar_kws, ax, **kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/seaborn/distributions.py", line 407, in _bivariate_kdeplot
    xx, yy, z = _scipy_bivariate_kde(x, y, bw, gridsize, cut, clip)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/seaborn/distributions.py", line 488, in _scipy_bivariate_kde
    kde = stats.gaussian_kde(data.T, bw_method=bw)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/scipy/stats/kde.py", line 209, in __init__self.set_bandwidth(bw_method=bw_method)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/scipy/stats/kde.py", line 565, in set_bandwidth
    self._compute_covariance()
  File "/home/ubuntu/.local/lib/python3.6/site-packages/scipy/stats/kde.py", line 577, in _compute_covariance
    self._data_inv_cov = linalg.inv(self._data_covariance)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/scipy/linalg/basic.py", line 979, in inv
    raise LinAlgError("singular matrix")
numpy.linalg.LinAlgError: singular matrix

Any suggestion... thanks


text:
Q: How to avoid inheritance in JUnit test cases? I have a number of test cases in JUnit. All of them need the same code to be executed in their @BeforeClass static method. It's a code duplication and I'm trying to get rid of it. A dirty way of doing this is by inheritance. Are there any other mechanisms in JUnit, that may help?
PS. I wrote this blog post about this very subject: http://www.yegor256.com/2015/05/25/unit-test-scaffolding.html

A: The JUnit way to compose reusable code (instead of inheriting from it) are Rules.
See https://github.com/junit-team/junit/wiki/Rules
Here is a dumb sample, but you'll get the point.
import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
import org.junit.runner.Description;

public class MyTestRule implements TestRule {
  @Override
  public Statement apply(final Statement statement, Description description) {
    return new Statement() {
      public void evaluate() throws Throwable {
        // Here is BEFORE_CODE
        try {
          statement.evaluate();
        } finally {
          // Here is AFTER_CODE
        }
      }
    };
  }
}

You can then use your TestRule like this:
import org.junit.Rule;

public class MyTest {
    @Rule
    public MyTestRule myRule = new MyTestRule();
}

BEFORE_CODE and AFTER_CODE will then be executed around each of your test methods.
If you need to run your code only once per class, use your TestRule as a @ClassRule:
import org.junit.ClassRule;

public class MyTest {
    @ClassRule
    public static MyTestRule myRule = new MyTestRule();
}

Now, BEFORE_CODE and AFTER_CODE will be executed around each of your test class.
@Rule field is not static, @ClassRule field is.
A @ClassRule can be declared in a Suite too.
Note that you can declare several rules in a single test class, that's how you compose test lifecycles at test-suites, test-classes and test-methods levels.
A Rule is an object that you instanciate in your test classes (statically or not). You can add contructor parameters if needed.
HTH

A: If the method is some kind of utility, then separate it out to a different class with a static method and call that method in your @BeforeClass.
I emphasize on the fact that don't use inheritance just because it solves your problem, use it when doing so creates sense in your class hierarchy.

A: You may create test runner
public class MyTestRunner extends BlockJUnit4ClassRunner {
  @Override
  protected Object createTest() throws Exception {
     Object test = super.createTest();
     doStuff();
  }

  public void doStuff(){
     //common code
  }
}

@RunWith(MyTestRunner.class)
public class MyTest1{
    @Test
    public void test1(){
      //test method
    }
}

A: Static methods aren't inherited, so inheritance isn't an option by default. If you mean you're moving the method to a common parent class, then that seems a poor choice since you only get one parent in Java. A test support class of some sort would seem more appropriate. It's also possible that you're seeing a need for a parameterized test.

A: There is absolutely nothing wrong with inheritance in this case, it's actually the only way to avoid repeating this code in each subclass. The fact that @BeforeClass methods have to be declared static in JUnit is unfortunate, but that shouldn't stop you. Extend the class and you have the initialization code automatically run for you without having to do anything.

A: If each and every class needs to have a @BeforeClass annotated method that is exactly the same as every other, then inheritance does not feel that wrong to me.  If each of these initializing methods simply share some code, you could make a TestUtil class with some shared behavior and make calls to this shared behavior from each of the @BeforeClass methods.

A: I think if the classes has "is-a" relation, inheritance is reasonable.
If the base class is MyBeforeClass which defines @BeforeClass method, and MyTestClass1 "is-a" MyBeforeClass, MyTestClass1 extends MyBeforeClass is OK.

A: Depending on the nature of the setup code, you can potentially put all your tests in a test suite and have the setup code run there. The downside to this is that you cannot run tests individually (since the test depends on the setup code).


text:
Q: write Rhino Mock Test cases for Web api HI  have created a WEBAPI below. i am trying to write rhino Mocks for below API i have tried a lot but everytime i failed
WEBAPI Client to hit web api
    [HttpPost]
    public ActionResult TestAPI(string test)
    {

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:42327/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync("api/Home/test/test").Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsStringAsync().Result;
                ViewBag.Valid = result;
                return View();
            }
            else
            {
                var result = response.Content.ReadAsStringAsync().Result;
                ViewBag.Valid = result;
                return View();
            }
        }
    }

**WEBAPI Code**

    [Route("api/{Home}/{Username}/{Password}")]
            public HttpResponseMessage Get(string Username, string Password)

            {
                HttpResponseMessage response;
                var display = Userloginvalues().Where(m => m.UserName == Username && m.Password == Password).FirstOrDefault();
                if (display != null)
                {
                    response = Request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent("xxxx.", Encoding.Unicode);
                }
                else
                {
                    response = Request.CreateResponse(HttpStatusCode.NotFound);
                    response.Content = new StringContent("xxxx", Encoding.Unicode);
                }
                return response;

            }
            public static List<LoginModel> Userloginvalues()
            {
                List<LoginModel> objModel = new List<LoginModel>();
                objModel.Add(new LoginModel { UserName = "test", Password = "test" });
                return objModel;
            }

RHIN MOCKS i tried below but dont know how to proceed
            MockRepository mocks = new MockRepository();

            HttpResponseMessage _respone;
            _respone = login.Get("test", "test");


text:
Q: SQL Server 2008 Import Data Wizard doesnt recognize Integer data for a column I have an excel sheet with 10 columns with headers. For a column I can have the data as "FF5" or else 620. The sheet name is IODE.
I am trying to import this data from SSIS Import data wizard into the database of table IODE.
On selecting source and destination in the wizard, when I click on PREVIEW DATA in Select Source Tables and Views window, I see the column with 620 as null. After importing this data, the table will have the NULL Instead of 620.
The data type for this column in table is nvarchar(50), I tried many data types like varchar(100), text/..
Only alpha numeric data is accepting.
I didn't write any code for this.. I am just trying to import data from excel sheet to a table.
Please help me in solving this
Thanks
Ramm

A: Do you mean that you have either FF5 or 620 as the values for that column meaning you have one or the other and nothing else or are there blank fields in that column as well?

A: I tried reading the excel by using the Excel library reference in VB6.0.
As SSIS Import Wizard treats NUMERIC as NULL when the data is exported to the SQL Table.
This procedure works very well for the data insertion and also for the other database operations.

Private Sub AccessExcelData()
  On Error GoTo errHandler
  Dim oXLApp As Excel.Application'Declare the object variable
  Dim oXLBook As Excel.Workbook
  Dim oXLSheet As Excel.worksheet
  Dim strFileName As String
  Dim lCount As Long
  Dim strSCDName As String
  Dim strICDName As String
  Dim intSource_Index As Integer
  Dim strInput_Port As String
  Dim strLabel As String
  Dim strSDI_CID As String
  Dim intWordBitNO As Integer
  Dim strFilter_Type As String
  Dim strPgroup_Input As String
  Dim strParagraph_Input As String
  Dim strSQL As String
  Dim sConnString As String
  Dim cnTest As New ADODB.Connection
  Dim rsTempRecordset As New ADODB.Recordset
  Dim objDataAccess As New FmmtDataAccess.clsDataAccess
  Dim strxmlResult As String
  objDataAccess.Intialize ConString

strFileName = App.Path & "\IODE.xls"
sConnString = "Server=uasql\commonsql;Database=accounts;Driver=SQL Server;Trusted_Connection=Yes;DSN=uasql\commonsql"
With cnTest
      .ConnectionString = sConnString
      .ConnectionTimeout = 4
      .CursorLocation = adUseClient
      .Open
End With
' Creating part of the excel sheet.
Set oXLApp = CreateObject("Excel.Application")
'Create a new instance of Excel
oXLApp.Visible = False
'Donot Show it to the user
Set oXLBook = oXLApp.Workbooks.Open(strFileName) 'Open an existing workbook
Set oXLSheet = oXLBook.Worksheets(1)   'Work with the first worksheet        oXLSheet.Activate
With oXLApp
For lCount = 2 To oXLSheet.UsedRange.Rows.Count
strSCDName = .Cells(lCount, 1).Value
strICDName = .Cells(lCount, 2).Value
intSource_Index = .Cells(lCount, 3).Value
strInput_Port = .Cells(lCount, 4).Value
strLabel = .Cells(lCount, 5).Value
strSDI_CID = .Cells(lCount, 6).Value
intWordBitNO = .Cells(lCount, 7).Value
strFilter_Type = .Cells(lCount, 8).Value
strPgroup_Input = .Cells(lCount, 9).Value
strParagraph_Input = .Cells(lCount, 10).Value
'strSQL = "Insert into XYX  () values (strSCDName ..... )   Here any DB related queries can be used
rsTempRecordset.Open strSQL, cnTest, adOpenForwardOnly, adLockReadOnly                    Next
End With
' Closing part of the excel sheet.
oXLApp.Visible = False               'Donot Show it to the user
Set oXLSheet = Nothing               'Disconnect from all Excel objects (let the user take over)
oXLBook.Close SaveChanges:=False    'Save (and disconnect from) the Workbook
Set oXLBook = Nothing
oXLApp.Quit                        'Close (and disconnect from) Excel
Set oXLApp = Nothing
Exit SuberrHandler:
MsgBox Err.Description
Screen.MousePointer = vbNormalEnd Sub
With this procedure the excel records can be read from vb applicatoin and can be inserted into existing table in the SQL database.
Thanks
Ramm


text:
Q: Not getting the real latitude and longitude? Only getting 0.0 0.0 Here I am using this code in order to get the latitude and longitude of the location but all that I am getting is latitude 0.0 and longitude 0.0 the code to find the latitude and logitude that I am using is given as below , Also I am testing this code in Genymotion emulator and all that is printed in the log is  0.0 0.0 because the if(address.size()>0) is not getting satisfyied can anyone tell where am I going wrong or is it because of emulator.
Geocoder geo = new Geocoder(getActivity());
            try {
                List<Address> address = geo.getFromLocationName(str_ELocation,1);
                if (address.size() > 0) {
                    Log.d("List Size : ", "" + address.size());
                    latitude = address.get(0).getLatitude();
                    longitude = address.get(0).getLongitude();
                } else {
                    Log.d("In Else", "In Else");
                }
            } catch (IOException e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            Log.d("LONGITUDE AND LATITUDE", "" + longitude + "" + latitude);

Also is there any other simpler solution to just find latitude and longitude. I am using this in Fragment and so I am using getActivity() here instead of myClassName.this.

A: I'm guessing you don't have a backend service you are using to obtain this information.
Note The Docs say

The Geocoder class requires a backend service that is not included in
  the core android framework. The Geocoder query methods will return an
  empty list if there no backend service in the platform. Use the
  isPresent() method to determine whether a Geocoder implementation
  exists.

This should also be done on a background Thread if not already being done.
Alternative
You may be better off using LocationManager
Be sure to read those docs on it before beginning to have an understanding of how it works and should be implemented (That portion is short).
Here is an example that can get you started
Anything like this should be done on a background Thread and not on the UI Thread. And there are listeners which can return the values you need.
full disclosure: I haven't used GPS but I read through the docs ;)