text:
Q: D3 dynamically vertically align text I've seen a few post here about using dy to vertically align text, but all of them just pick a random value without explaining it. Surely this value would differ depending on the font size? My text's font size is stored in a variable (fsize), and its value can change depending on other factors. I tried setting .attr("dy", fsize / 2) (not quite exactly that since fsize is a string and in ems, but you get the point), and my text is way off centre. What value should I choose, given a font size of fsize?

A: "Surely this value would differ depending on the font size?"
if you use 'em' units it shouldn't matter what the font size is as they're a relative-size unit
https://www.w3.org/WAI/GL/css2em.htm
So you can use rules of thumb like .attr("dy", "0.7em") which shifts text y-wards by 70% of the font height


text: Q: Is there any anti-hermitian operator in quantum mechanics? I know what are Hermitian operators and anti-hermitian operators.but as i have studied quantum mechanics most of the operators we had dealt with them are hermitian and this question popped up in my mind that does any anti-hermitian operator exists in quantum mechanics?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to build JAR file for my maven PARENT prroject I have created two training projects aiming to the creation of a Java Test Automation Framework with Selenium.
Both projects have been stored in my personal git: https://github.com/omarjmc
Framework: Contains main classes and all the code needed to execute successfuly the tests
Project: Demo project that will use the methods specified in the Framework project
Additionally i added the dependency to the Framework project in the demo Project's POM and I also created a release of the Framework project and attached the JAR file
enter image description here
Currently I have to clone both repositories and run mvn clean install on the framework to get the JAR file and change the packaging back to pom, but I want to just clone the demo project, run mvn clean install there and still get the Framework JAR file.
What am I missing the POM file?

A: Omar you have to create a maven multi module project for this requirement. Project will be the parent project and it should contain framework as child.
The basic code structure for pom.xml for Project should be like this.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>multi</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>project</name>
    <modules>
        <module>framework</module>
    </modules>
</project>

You can refer below the github project for this exact requirement.
https://github.com/jamesward/maven-multi-module-example

A: I created a multi-module proyect, but it only works if you download the original repository, what I want is to have them in separate repositories and just download, and use, the project child


text:
Q: Pandas append text into row i have a single column , i trying to add "," into the row value but always

Getting error, "an int is required"
df = df['Cntr_Number'] + ','

print(df['Cntr_Number'].astype(str))

A: Try this:
df.loc[:,'Cntr_Number'] = df.Cntr_Number.apply(lambda x: str(x)+',')

A: You should just coerce the column to a str type:
df['Cntr_Number'] = df['Cntr_Number'].as_type('str') + ','


text:
Q: How to determine the latest stable TuxOnIce version as compactly as possible So what I'm intending to do here is to determine the latest stable version of TuxOnIce from http://tuxonice.net/downloads/all/ (currently tuxonice-for-linux-3.8.0-2013-02-24.patch.bz2).
What complicates things is that there's no "current" link, so we gotta follow the versioning, which is something like (these don't exist):
tuxonice-for-linux-3.8.0-2013-4-2.patch.bz2
tuxonice-for-linux-3.8-4-2013-4-16.patch.bz2
tuxonice-for-linux-3.8-11-2013-5-23.patch.bz2

The problem is they're gonna be in this order:
tuxonice-for-linux-3.8-11-2013-5-23.patch.bz2
tuxonice-for-linux-3.8-4-2013-4-16.patch.bz2
tuxonice-for-linux-3.8.0-2013-4-2.patch.bz2

My current implemetation (which is garbage) is this. I thought about using the dates but couldn't figure out how to do that either (/tmp/tuxonice is the index file):
_major=3.8 # Auto-generated
_TOI=$(grep ${_major}-1[0-9] /tmp/tuxonice | cut -d '"' -f2 | tail -1)
[ ! $_TOI ] && _TOI=$(grep ${_major}- /tmp/tuxonice | cut -d '"' -f2 | tail -1)
[ ! $_TOI ] && _TOI=$(grep ${_major}.0-2 /tmp/tuxonice | cut -d '"' -f2 | tail -1)

Thanks.

A: Use the webserver's feature to sort the index page by modification date in reverse order, grab the page using lynx -dump, get the first line matching the filename you are interested in and print the respective column. This gives you the absolute URL to the file, from there you can tweak the command to give you the exact output you want (filename, just the version string, ...).
$ lynx -dump 'http://tuxonice.net/downloads/all/?C=M&O=D'|awk '/^[[:space:]]*[[:digit:]]+\..+\/tuxonice-for-linux/ { print $2; exit }'
http://tuxonice.net/downloads/all/tuxonice-for-linux-3.8.0-2013-02-24.patch.bz2

Still not super-robust and will obviously break if the modification dates are not as expected, and you probably also want to tweak the regex a bit to be more specific.

A: This isn't a real answer, but I thought this "one-liner"[1] was pretty cool:
HTML=$(wget -qO- http://tuxonice.net/downloads/all/ | grep tuxonice); TIMESTAMP=$(echo "$HTML" | sed 's/.*\([0-9]\{2\}-[A-Za-z]\{3\}-[0-9]\{4\} [0-9]\{2\}:[0-9]\{2\}\).*/\1/' | while read line; do echo $(date --date "$line" +%s) $line; done | sort | tail -n 1 | cut -d' ' -f2-3); LINK=$(echo "$HTML" | grep "$TIMESTAMP" | sed 's/.*href=\"\(.*\)\".*/\1/'); echo "http://tuxonice.net/downloads/all/${LINK}"

Prints:
http://tuxonice.net/downloads/all/tuxonice-for-linux-3.8.0-2013-02-24.patch.bz2

This approach is really just a joke though.  Obviously, there are better ways to do this, perhaps using a scripting language that supports XML parsing.
At the very least, maybe this will give you some insight on how you can use the date/time values of the files to select the "newest".  But I'd caution using this (because upload dates may not coincide with version numbers), and suggest that your version number idea was probably a better idea, if you can somehow handle all of the various naming and version numbering schemes it looks like they've used.
[1] It's not a real one liner


text:
Q: $\mathbb{Q}_p\otimes_{\mathbb{Q}} \mathbb{Q}_q$ and $\mathbb{Z}_p\otimes_{\mathbb{Z}} \mathbb{Z}_q$ Let $p, q$ be prime numbers which may or may not be distinct.
Let $\mathbb{Q}_p$ be the field of $p$-adic numbers.
Let $\mathbb{Z}_p$ be the ring of $p$-adic integers.
We define similarly $\mathbb{Q}_q$ and $\mathbb{Z}_q$.
Let $A = \mathbb{Q}_p\otimes_{\mathbb{Q}} \mathbb{Q}_q$.
Let $\lambda\colon \mathbb{Z}_p \rightarrow A$
and $\mu\colon \mathbb{Z}_q \rightarrow A$ be the canonical ring homomorphisms.
Let $B = \mathbb{Z}_p\otimes_{\mathbb{Z}} \mathbb{Z}_q$.
Let $\psi\colon B \rightarrow A$ be the ring homomorphism induced by $\lambda$ and $\mu$.
Is $\psi$ injective?

A: All rings will be assumed to be commutative with unity.
Lemma 1
Let $A$ be a ring, $M, N$ $A$-modules.
Suppose $N$ is flat over $A$.
Let $a$ be an element of $A$.
Suppose the map $f\colon M \rightarrow M$ defined by $f(x) = ax$ is injective.
Then the map $g\colon M\otimes_A N \rightarrow M\otimes_A N$ defined by $g(z) = az$ is also injective.
Proof:
Let $1_M\colon M \rightarrow M$ be the identity map.
Since $ax\otimes y = a(x\otimes y)$ for $x \in M, y \in N$, $g = f\otimes 1_M$.
Hence $g$ is injective.
Lemma 2
Let $A$ be a ring, $N$ an $A$-module.
Let $(M_i)_{i\in I}$ a direct system of $A$-modules.
Then colim$_i (M_i\otimes_A N) =$ (colim$_i M_i)\otimes_A N$.
Proof:
This is well known.
See, for example, Matsumura's Commutative Ring Theory, Appendix A1.
Remark
Lemma 2 can be proved by using category theory as follows.
$-\otimes_A N$ is a left adjoint functor of Hom$_A(N, -$)(see my answer to this question).
Hence it commutes with colim(see MacLane: Categories for the working mathematician, Chapter V, Section 5, Theorem 1, p.114).
Lemma 3
Let $A$ be a ring.
Let $(M_i)_{i\in I} \rightarrow (N_i)_{i\in I}$
and $(N_i)_{i\in I} \rightarrow (L_i)_{i\in I}$ be maps of direct sytems of $A$-modules.
Suppose each sequence $M_i \rightarrow N_i \rightarrow L_i$ is exact.
Then colim $M_i \rightarrow$ colim $N_i \rightarrow$ colim $L_i$ is exact.
This is well known.
See, for example, Matsumura's Commutative Ring Theory, Appendix A2.
Lemma 4
Let $A$ be a ring.
Let $(M_i)_{i\in I}$ a direct system of flat $A$-modules.
Then colim $M_i$ is flat.
Proof:
This follows immediately from Lemma 2 and Lemma 3.
Lemma 5
Let $G$ be a torsion-free abelian group.
In other words, the order of every nonzero element of $G$ is infinite.
Then $G$ is flat.
In other words, the functor $-\otimes_{\mathbb{Z}} G$ is exact.
Proof:
Let $(G_i)_{i \in I}$ be the family of finitely generated subgroups of $G$.
Since each $G_i$ is torsion-free, it is free.
Hence it is flat.
Hence $G =$ colim $G_i$ is flat by Lemma 4.
Proposition
Let $p, q$ be prime numbers which may or may not be distinct.
Let $A = \mathbb{Q}_p\otimes_{\mathbb{Q}} \mathbb{Q}_q$.
Let $\lambda\colon \mathbb{Z}_p \rightarrow A$
and $\mu\colon \mathbb{Z}_q \rightarrow A$ be the canonical ring homomorphisms.
Let $B = \mathbb{Z}_p\otimes_{\mathbb{Z}} \mathbb{Z}_q$.
Let $\psi\colon B \rightarrow A$ be the ring homomorphism induced by $\lambda$ and $\mu$.
Then $\psi$ injective.
Proof:
Let $S = \mathbb{Z} - \{0\}$.
Then $S^{-1} (\mathbb{Z}_p \otimes_{\mathbb{Z}} \mathbb{Z}_q) \cong \mathbb{Q}_p \otimes_{\mathbb{Q}} \mathbb{Q}_q$ by Lemma 3 of my answer to this question.
Since $\mathbb{Z}_q$ is torsion-free, it is flat by Lemma 5.
Hence $\mathbb{Z}_p \otimes_{\mathbb{Z}} \mathbb{Z}_q$ is torsion free by Lemma 1.
Hence $\psi$ injective.

A: Since $A$ is the localization of $B$ at the elements $p$ and $q$ (by formal nonsense), the question is if $p$ and $q$ are regular elements of $B=\mathbb{Z}_p \otimes \mathbb{Z}_q$. But this is because $p$ is a regular element of $\mathbb{Z}_p$ and $\mathbb{Z}_q$ is torsion-free and hence flat over $\mathbb{Z}$; similarly for $q$.


text:
Q: Big rsync -- push or pull? I'm about to start a big rsync between two servers on my LAN.  Is it better for me to push the files from one server to the other or pull them (backwards)?
There is not anything that would make one work, and the other not work -- I am just wondering if there is a reason (maybe speed) to do one over the other.
Can anyone give me a good reason, or is there no reason to do one over the other?

A: The way rsync algorithm works can be found from here.

The algorithm identifies parts of the source file which are identical
  to some part of the destination file, and only sends those parts which
  cannot be matched in this way. Effectively, the algorithm computes a
  set of differences without having both files on the same machine. The
  algorithm works best when the files are similar, but will also
  function correctly and reasonably efficiently when the files are quite
  different.

So it would not make a difference whether you are uploading or downloading as the algorithm works on checksums of the source and destination files. So, any file can be the source/destination.
I find some more useful information from here. Some of the excerpts are,

RSync is a remote file (or data) synchronization protocol. It allows
  you to synchronize files between two computers. By synchronize, I mean
  make sure that both copies of the file is the same. If there are any
  differences, RSync detects these differences, and sends across the
  differences, so the client or server can update their copy of the
  file, to make the copies the same.

RSync is capable of synchronizing files without sending the whole file
    across the network. In the implementation I've done, only data
    corresponding to about 2% of the total file size is exchanged, in
    addition to any new data in the file, of course. New data has to be
    sent across the wire, byte for byte.
Because of the way RSync works, it can also be used as an incremental
    download / upload protocol, allowing you to upload or download a file
    over many sessions. If the current upload or download fails, you can
    just resume it later.

A: The rsync program actually runs a copy of itself on the remote server. Once rsync is running on both ends, they negotiate between themselves how to best transfer the requested files. I don't think it matters which one is started first.
However, I would usually initiate the transfer from the machine that is closest to me. That way, if something goes wrong I am more likely to be able to monitor the file transfer progress. If both machines are on the same LAN, then this reason wouldn't be a reason to pick one over the other.

A: Push or Pull method can be significant if the transfer uses an ADSL line because bitrates are different when you download or when you upload. In such case, the choice depends on the location of the target machine.

A: With regards to security and backup for public-facing servers, it is usually better to pull than to push from the data backup source.  For example, if the data source becomes compromised in anyway (from hacking), it will expose the credentials to its backup server.  Also pulling instead of pushing isolates the backup process to the backup server, rather than having to maintain backup service on each individual backup source.  It probably makes backup management easier. I imagine one backup server pulling backups from multiple sources and all the backup management would be done on a single server.
However, if it is for doing backups which are not mission critical, I'd prefer push for its simplicity and ease of use.  I use push for all rsync-based backups at home for my personal data (via SFTP/SSH).


text:
Q: MIPS, registers, beginner Just started studying MIPS, could someone explain a detail in this simple code: Here is the code:
main:

    li $v0, 5
    syscall
    move $t0, $v0

    li $v0, 5
    syscall
    move $t1, $v0

    add $t2, $t0, $t1

    move $a0, $t2
    li $v0, 1
    syscall
exit:
    li $v0, 10
    syscall

This is what I understand: li $v0  5  syscall -means to load immediately an integer that is read (in $v0? I think). Then I get the rest moving, adding...
When I start not understanding is when the line: li $v0, 1 syscall - comes up. This would have to mean to print a integer (from $v0?). How does it know to print $a0 or $t2. How does this work?
Like this example:
 la $a0, str1
 li $v0, 4
 syscall

This would print the string from $a0. Why isn't another string printed, but specifically this one? Is the rule that the last string mentioned is printed (in this case.)

A: That's just part of syscall available services:http://courses.missouristate.edu/KenVollmar/mars/Help/SyscallHelp.html
main:

li $v0, 5 #read integer
syscall
move $t0, $v0 #t0 is the integer you intend to read

li $v0, 5#same as above
syscall
move $t1, $v0

add $t2, $t0, $t1 #add two integers and store it in t2

move $a0, $t2 # move sum to integer to print
li $v0, 1 #integer to print
syscall
exit:
li $v0, 10 # terminate execution
syscall


text:
Q: make file multiple executables I have a folder called UnitTest. I have several .c files in it. All files contain function 'main'.
Using makefile, I want to compile all .c files of that folder together.
But these files have dependency on other C files which are in different folder.
How can I write make file for this?
eg.
Common\*.c - generate object file
App\*.c - generate object file. - refers to .o files of Common directory
UnitTest\.c - these files should be compiled as executables. Refer *.o from directory App and Common.
Update:
Header files are in seperate directory called \Include
I need a single makefile for this. Please help.

A: As per the standards every directory will contain one Makefile. So you can have three Makefiles for this job done if you have three directories.
(d) common
 |
 |---(f) common.h
 |---(f) common.c
 |---(f) Makefile --- MAkefile for the common folder.

(d) app
 |
 |---(f) app.h
 |---(f) app.c
 |---(f) Makefile

(d) unittest
 |
 |---(f) unittest.h
 |---(f) unittest.c
 |---(f) Makefile

(f) Makefile --- invoke all makefiles in the mentioned order.

If you want one Makefile to happen all these done, you can do in that way also. Here you have to compile the files by providing paths of the files. order is most impotent.

A: This is complicated, so we will take it in stages. First, building the object files:
CFLAGS += -I/include

vpath %.h /include

This should be enough to build any object file in Common/, Apps/ or UnitTest/. Test this before going further.
Now to build all of the objects in Common/:
COMMONSOURCES := $(wildcard Common/*.c)
COMMONOBJECTS := $(COMMONSOURCES:.c=.o)

all: $(COMMONOBJECTS)

Test this before going further.
Remove that all rule, and put in a rule for the Common library. (We'll use a static library for now, since it's a little simpler.)
Common/libCommon.a: $(COMMONOBJECTS)
    ar -cvq $@ $^

Test that much, tell us in the comments how it worked, then we'll build Apps library and the UnitTest executables.


text:
Q: the latex mark are not shown in the heading of ERDC report I am using a erdc (a modified version which override the mathgifg fonts).
I want to change the header of the report, so it will show the report-number on the inner-side, the the chapter title on the outer-side and the page number on the outer footer.
Here are the short sample code (see below), what I have trying. However, I got some issues:

*

*the \rightmark do not have effect, it printed nothing. Even outside the \mainmatter, as the fancyhdr manual suggested.

*If I include the \reportnum, I got a lot of errors. In this example the statement is commented out.

What do I miss? Please need your advice.
\documentclass{erdcx}
\usepackage[T1]{fontenc}
\usepackage{mathptmx}
\usepackage{bera}
\usepackage{fancyhdr}
\usepackage{blindtext}
%%% FORMAT OF HEADING
    \pagestyle{fancy}
    \fancyhf{}
%       \fancyhead[RE,LO]{\textsf{{\footnotesize\reportnum}}} %inner header
    \fancyhead[LE,RO]{\textsf{{\footnotesize\rightmark}}} %outter header
    \fancyfoot[LE,RO]{\textsf{{\footnotesize\thepage}}}   %outter footer

\begin{document}
%       \mainmatter
    \chapter{Primo}
    \thispagestyle{plain}
    \Blindtext

    \chapter{Secondo}
    \thispagestyle{plain}
    \blindtext
    \blindmathpaper

    \chapter{Terzo}
    \Blindtext

\end{document}

I also tried to add the following to the preamble, but no luck.
\renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{#1}}{}}

A: The erdc class defines \@chapter not to emit \chaptermark, so no marks are found.
\def\@chapter[#1]#2{%
  \if@frontmatter
      \addcontentsline{toc}{chapter}{#1}%
      \@makechapterhead{#2}%
  \else
      \refstepcounter{chapter}%
      \typeout{\@chapapp\space\thechapter.}%
      \if@appendix
         \addcontentsline{toc}{chapter}%
             {\@chapapp\space\thechapter: #1}%
         \@makechapterhead{\@chapapp\space\thechapter: #2}%
      \else
         \addcontentsline{toc}{chapter}%
             {\protect\numberline{\thechapter}#1}%
         \@makechapterhead{\makebox[35\p@]{\thechapter\hfill}#2}%
      \fi
  \fi
  \@afterheading}

Here's a patch for it.
% don't load mathgifg (does not exist)
\expandafter\def\csname ver@mathgifg.sty\endcsname{}
%%%

\documentclass{erdc}
\usepackage[T1]{fontenc}
\usepackage[latin]{babel} % latin just to avoid overfull boxes
\usepackage{bera}
\usepackage{etoolbox}

%\usepackage{fancyhdr}% not needed
\usepackage{blindtext}

%%% FORMAT OF HEADING
%\pagestyle{fancy} % not needed
\fancyhf{}
\makeatletter
\fancyhead[RE,LO]{\textsf{{\footnotesize\@reportnum}}} %inner header
\makeatother
\fancyhead[LE,RO]{\textsf{{\footnotesize\leftmark}}} %outer header
\fancyfoot[LE,RO]{\textsf{{\footnotesize\thepage}}}  %outer footer
\setlength{\headheight}{16pt}

% patch \@chapter to emit \chaptermark
\makeatletter
\patchcmd{\@chapter}{\fi\fi}{\fi\chaptermark{#1}\fi}{}{}
\makeatother

\begin{document}

\mainmatter

\chapter{Primo}
\thispagestyle{plain}

\Blindtext

\chapter{Secondo}
\thispagestyle{plain}

\blindtext
\blindmathpaper

\chapter{Terzo}
\thispagestyle{plain}

\Blindtext

\end{document}


text:
Q: NoMethodError (undefined method `before_validation' for xxx:Class)
*

*I am getting 'after_validation' error when the the code visit ib/better_date_picker/model.rb:21

*Earlier with Ruby 2.3.4 and rails 5.0, the same code was working.

*When I upgraded the version of ruby to 2.5.3 and rails to 5.2.3, I start getting this error of after_validation.


text:
Q: C array struct function pointer How do you create a function pointer with struct table such as
static struct {
  int pid;
  int queue[MAXPROCS];
} semtab[MAXSEMS];

I think I understand how to make OO equivalent in C using function pointer with this post, but how can I do with when my struct is an array. I'm still a little iffy with the syntax.
Would it be something like
static struct {
  int pid;
  int queue[MAXPROCS];

  void (*fncPtr_enqueue)(int) = enqueue;
                 // or is it void(*enqueue)(semtable[]*) ?
  int (*fcnPtr_dequeue)() = dequeue;
} semtab[MAXSEMS];

void enqueue(int i) { /* code */ }
int dequeue() { /* code */ }

// then to use it, it would be like this?
void foo() {
  semtab[5].enqueue(6);
}

A: Use
static struct {
  int pid;
  int queue[MAXPROCS];

  void (*fncPtr_enqueue)(int); // This defines a member fncPtr_enqueue
  int (*fncPtr_dequeue)();     // Note that you had fcnPtr_ in your post.
                               // I have fncPtr_ here.
} semtab[MAXSEMS];

void enqueue(int i) { /* code */ }
int dequeue() { /* code */ }

Each object in semtab that needs to have valid function pointers needs to be updated.
semtab[0].fncPtr_enqueue = enqueue;
semtab[0].fncPtr_dequeue = dequeue;

A: You could use:
static struct
{
    int pid;
    int queue[MAXPROCS];
    void (*enqueue)(int);
    int (*dequeue)(void);
} semtab[MAXSEMS];

void enqueue(int i) { /* code */ }
int dequeue(void) { /* code */ }

void foo(void)
{
    semtab[5].enqueue(6);
}

Changes include:

*

*Systematic names for structure member pointers (instead of mixed fncPtr and fcnPtr prefixes).

*No attempt to initialize in the structure definition.

*Add void to function prototypes to indicate no arguments. In C (and in contrast to C++), an empty pair of brackets (parentheses) means "a function taking an undefined number of arguments, but not one which has a variable argument list with ... ellipsis".

*Because of (1), the original invocation is OK.  (With the original code, you'd have needed semtab[5].fncPtr_enqueue(6); — or even (*semtab[5].fncPtr_enqueue)(6);)

You would still have to ensure that the function pointers in the table are all initialized.
With GCC and C99 or C11 compilation, you could initialize the array using:
static struct
{
    int pid;
    int queue[MAXPROCS];
    void (*enqueue)(int);
    int (*dequeue)(void);
} semtab[MAXSEMS] =
{
    [0 ... MAXSEMS-1] = { .enqueue = enqueue, .dequeue = dequeue }
};

The [0 ... MAXSEMS-1] part is a GCC extension.  Observe that a space is required after the 0 to avoid problems with the 'maximal munch' rule.

A: As JS1 mentioned in the comments, it's actually pretty pointless to do this with the example you have, as you're not achieving anything with the indirection if you're not going to vary the value of those pointers.
That being said, here's an example using a stack (because the logic is easier than a queue, and this is a simple example). Note that you must pass a pointer to the stack to each of your member functions, because while C++ member functions have an implicit this argument, C functions never do. You also need to give your struct a name, otherwise you won't be able to refer to it in the abstract, which you need to do.
This program uses the same struct to implement two variations of a stack, one normal one, and one which unnecessarily shouts at you when you push or pop:
#include <stdio.h>
#include <stdlib.h>

enum {
    STACKSIZE = 1024
};

struct stack {
    int stack[STACKSIZE];
    size_t top;
    void (*push)(struct stack *, int);
    int (*pop)(struct stack *);
    void (*destroy)(struct stack *);
};

void stack_push(struct stack * this, int i)
{
    if ( this->top == STACKSIZE ) {
        fprintf(stderr, "Queue full!\n");
        exit(EXIT_FAILURE);
    }

    this->stack[this->top++] = i;
}

void stack_push_verbose(struct stack * this, int i)
{
    stack_push(this, i);
    printf("** PUSHING %d ONTO STACK! **\n", i);
}

int stack_pop(struct stack * this)
{
    if ( this->top == 0 ) {
        fprintf(stderr, "Stack empty!\n");
        exit(EXIT_FAILURE);
    }

    return this->stack[--this->top];
}

int stack_pop_verbose(struct stack * this)
{
    const int n = stack_pop(this);
    printf("** POPPING %d FROM STACK! **\n", n);
    return n;
}

void stack_destroy(struct stack * this)
{
    free(this);
}

struct stack * stack_create(void)
{
    struct stack * new_stack = malloc(sizeof * new_stack);
    if ( !new_stack ) {
        perror("Couldn't allocate memory");
        exit(EXIT_FAILURE);
    }

    new_stack->top = 0;
    new_stack->push = stack_push;
    new_stack->pop = stack_pop;
    new_stack->destroy = stack_destroy;

    return new_stack;
}

struct stack * stack_verbose_create(void)
{
    struct stack * new_stack = stack_create();
    new_stack->push = stack_push_verbose;
    new_stack->pop = stack_pop_verbose;

    return new_stack;
}

int main(void)
{
    struct stack * stack1 = stack_create();
    struct stack * stack2 = stack_verbose_create();

    stack1->push(stack1, 4);
    stack1->push(stack1, 3);
    stack1->push(stack1, 2);

    printf("Popped from stack1: %d\n", stack1->pop(stack1));

    stack2->push(stack2, 5);
    stack2->push(stack2, 6);

    printf("Popped from stack2: %d\n", stack2->pop(stack2));
    printf("Popped from stack1: %d\n", stack1->pop(stack1));
    printf("Popped from stack1: %d\n", stack1->pop(stack1));
    printf("Popped from stack2: %d\n", stack2->pop(stack2));

    stack1->destroy(stack1);
    stack2->destroy(stack2);

    return 0;
}

with output:
paul@horus:~/src/sandbox$ ./stack
Popped from stack1: 2
** PUSHING 5 ONTO STACK! **
** PUSHING 6 ONTO STACK! **
** POPPING 6 FROM STACK! **
Popped from stack2: 6
Popped from stack1: 3
Popped from stack1: 4
** POPPING 5 FROM STACK! **
Popped from stack2: 5
paul@horus:~/src/sandbox$

Note that we use the exact same struct stack for both types of stack - the differences between them are implemented by having the function pointers point to different functions in each case. The only visible difference to the user is that one is created with stack_create(), and the other is created with stack_create_verbose(). In all other respects, they're used identically, so you can see the polymorphism at work.


text:
Q: Regarding WPF & attractive UI i am learning WPF. i saw a very beautiful application called Blu Twitter client developed with WPF. their UI is really glossy.

can anyone give me some tips that how could i create this type of glossy UI with WPF. what i need to do.......need concept.
thanks

A: Get Expression Blend (it's free if you are student), it is fairly easy to create some fancy UIs with it - it has really nice graphical designer.
Here is tutorial, which explains how to make such glossy control: http://blogs.msdn.com/b/mgrayson/archive/2007/02/16/creating-a-glass-button-the-complete-tutorial.aspx . This covers basics of how to compose the graphics from gradients and similar graphical primitives and how to make it react on mouse actions.
But be warned: it takes some graphical talent to actually create original graphics! The design above is clearly a work of graphical artist, even though I don't like it - I hate the preudo-3D effect on the navigation buttons, window state controls and message boxes. And similar window transparency tends to be counter-productive.
EDIT:
Note that Expression Blend is since the 2012 release part of the Visual Studio.

A: Or in addition to mzabsky's suggestion, if you want a more programming approach, the key here is to restyle some of the existing WPF controls. The UI in your picture is not too complex, a main list, a toolbar perhaps at the bottom, a decorator in the upper left corner, some grid/panel layout, nothing unusual, but they are heavily re-styled. Other than that, a couple well-chosen colors with transparency (maybe some color animations for hovering too).
As a starting point, you should get yourself familiar with control restyling in WPF.


text:
Q: Quoting a bash script I am trying to run the following command
echo `grep -o "<\/div><div class\=\".*" $1` |
grep -o "title=\\"\(.*\?\)\\" aria-describedby" -> title.txt

from script test.sh.
However, every time I check my file title.txt, it is empty.
I tested the first part of the command,
echo `grep -o "<\/div><div class\=\".*" $1`

and it works fine.
The second part is the one with the problem"
grep -o "title=\\\"\(.*\?\)\\\" aria-describedby" -> title.txt

Just to keep in mind, this is not being run from the terminal itself, but from a bash script file being called from the terminal.
I believe my problem lies in how I am quoting or escaping the quotes.

A: I do not know if your expressions do what you want them to do, but there is an issue with this one :
"title=\\"\(.*\?\)\\"

When the shell sees to consecutive backslashes (basically an escaped backslash), it will read them as one literal backslash.  The first twin backslashes in your expression are read like this, and the double quote that follows ends the string.  In other words, the following is a string :
"title=\\"

And the rest of the line :
\(.*\?\)\\"

ends with a double quote (not escaped once again due to the twin backslashes that become one literal backslash), but has no initial double quote.


text:
Q: How to pass a parameter from JSP to Struts 2 action I have an application and I want to pass item id to the action every time the button for that item is pressed.
My JSP :
<s:submit  value="addToCart" action="addToCart" type="submit">
<s:param name="id" value="%{#cpu.id}" />
</s:submit>

Action:
public class ProductsCPU extends BaseAction implements Preparable, SessionAware {
private static final long serialVersionUID = 2124421844550008773L;

private List colors = new ArrayList<>();
private List cpus;
private String id;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

When I print id to console, it has the null value. What is the problem?

A: This should do :
<s:url id="myurl" action="addToCart">
    <s:param name="id" value="%{#cpu.id}" />
</s:url>
<s:submit  value="addToCart" action="%{myurl}"/>

A: You need to use form element.
<form action="passId>
    <s:hidden name="id" value="%{#cpu.id}" />
    <s:submit  value="addToCart" action="addToCart" type="submit"/>
</form>

A: The problem is that you can't parametrize <s:submit> tag with <s:param> tag like in your code using  the param tag in the body of  the submit tag.
You also don't want to add <hidden> field because you got multiple values submitted to the action. This is because many hidden fields are rendered with the same name. You could use only one field and update its value before submitting a form.
Probably you have used wrong tag to pass a parameter to the action. You can use anchor tag and parametrize it with <s:param> tag.
The second way is to use JavaScript to modify action attribute. In this way you can also use a <button> tag.
Third way is not recommended because it requires to use multiple forms one per each link. In this way you add a parameter to the form action attribute directly.
Below is the code for the options mentioned above.
3-in-1:
<s:form name="myForm13" namespace="/" action="save?message=Hello param 3" theme="simple">

<s:a cssClass="btn btn-primary" action="test"><s:param name="message">Hello param 1</s:param>   Go   </s:a>

<s:a href="#" cssClass="btn btn-warning" onclick="myForm13.action='test?message=Hello param 2';myForm13.submit()">Submit</s:a>

<s:submit cssClass="btn btn-danger" action="test"/>
</s:form>


text:
Q: How to enable and disable action on switch preference in android This is not working with switch preference please help .......to write another code..
SwitchPreference uiTestModePref = (SwitchPreference) findPreference("switch");
uiTestModePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object o) {
        boolean check = (preference).isEnabled();
        if (check) {
            android.provider.Settings.System.putInt(getContentResolver(),
            android.provider.Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
            Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "No", toast.LENGTH_LONG).show();
        }
        return false;
    }
});

A: It should be isChecked() instead of isEnabled()


text:
Q: "java.lang.RuntimeException: Could not launch intent" for UI with indeterminate ProgressBar Are there any known issues with displaying indeterminate ProgressBars with the AndroidJUnitRunner?  I'm hitting this error during tests:

05-26 15:22:48.504    1003-1016/? I/TestRunner﹕
  java.lang.RuntimeException: Could not launch intent Intent {
  act=android.intent.action.MAIN flg=0x14000000
  cmp=com.cookbrite.dev/com.cookbrite.ui.HomeListActivity } within 45
  seconds. Perhaps the main thread has not gone idle within a reasonable
  amount of time? There could be an animation or something constantly
  repainting the screen. Or the activity is doing network calls on
  creation? See the threaddump logs. For your reference the last time
  the event queue was idle before your activity launch request was
  1432668122421 and now the last time the queue went idle was:
  1432668122421. If these numbers are the same your activity might be hogging the event queue.

The stack trace is:
05-26 15:22:48.504    1003-1016/? I/TestRunner﹕ java.lang.RuntimeException: Could not launch intent Intent { act=android.intent.action.MAIN flg=0x14000000 cmp=com.cookbrite.dev/com.cookbrite.ui.HomeListActivity } within 45 seconds. Perhaps the main thread has not gone idle within a reasonable amount of time? There could be an animation or something constantly repainting the screen. Or the activity is doing network calls on creation? See the threaddump logs. For your reference the last time the event queue was idle before your activity launch request was 1432668122421 and now the last time the queue went idle was: 1432668122421. If these numbers are the same your activity might be hogging the event queue.
            at android.support.test.runner.MonitoringInstrumentation.startActivitySync(MonitoringInstrumentation.java:274)
            at android.test.InstrumentationTestCase.launchActivityWithIntent(InstrumentationTestCase.java:119)
            at android.test.InstrumentationTestCase.launchActivity(InstrumentationTestCase.java:97)
            at android.test.ActivityInstrumentationTestCase2.getActivity(ActivityInstrumentationTestCase2.java:104)
            at com.cookbrite.step2_functional.ui.homelist.HomeListFragmentLoadingTest.testLoadingSpinner(HomeListFragmentLoadingTest.java:40)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
            at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
            at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
            at com.cookbrite.util.BaseBlackBoxTest.doRunTest(BaseBlackBoxTest.java:300)
            at com.cookbrite.util.BaseBlackBoxTest.access$000(BaseBlackBoxTest.java:44)
            at com.cookbrite.util.BaseBlackBoxTest$1.call(BaseBlackBoxTest.java:271)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)

The thread dump triggered by the above timeout shows the ProgressBar appears to be involved:
05-26 15:22:48.135    1003-1018/? E/THREAD_STATE﹕ Thread[main,5,main]
    android.graphics.Canvas.native_drawBitmap(Native Method)
    android.graphics.Canvas.drawBitmap(Canvas.java:1160)
    android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:440)
    android.graphics.drawable.RotateDrawable.draw(RotateDrawable.java:88)
    android.graphics.drawable.LayerDrawable.draw(LayerDrawable.java:345)
    android.widget.ProgressBar.onDraw(ProgressBar.java:1052)
    android.view.View.draw(View.java:13944)
    android.view.View.draw(View.java:13825)
    android.view.ViewGroup.drawChild(ViewGroup.java:3086)
    android.view.ViewGroup.dispatchDraw(ViewGroup.java:2923)
    android.view.View.draw(View.java:13823)
    android.view.ViewGroup.drawChild(ViewGroup.java:3086)
    android.view.ViewGroup.dispatchDraw(ViewGroup.java:2923)
    android.view.View.draw(View.java:13947)
    android.view.View.draw(View.java:13825)
    android.view.ViewGroup.drawChild(ViewGroup.java:3086)
    android.view.ViewGroup.dispatchDraw(ViewGroup.java:2923)
    android.view.View.draw(View.java:13823)
    android.view.ViewGroup.drawChild(ViewGroup.java:3086)
    android.view.ViewGroup.dispatchDraw(ViewGroup.java:2923)
    android.view.View.draw(View.java:13947)
    android.widget.FrameLayout.draw(FrameLayout.java:467)
    android.view.View.draw(View.java:13825)
    android.view.ViewGroup.drawChild(ViewGroup.java:3086)
    android.view.ViewGroup.dispatchDraw(ViewGroup.java:2923)
    android.view.View.draw(View.java:13823)
    android.view.ViewGroup.drawChild(ViewGroup.java:3086)
    android.view.ViewGroup.dispatchDraw(ViewGroup.java:2923)
    android.view.View.draw(View.java:13947)
    android.widget.FrameLayout.draw(FrameLayout.java:467)
    com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2224)
    android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:2482)
    android.view.ViewRootImpl.draw(ViewRootImpl.java:2395)
    android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2239)
    android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1872)
    android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
    android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
    android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
    android.view.Choreographer.doCallbacks(Choreographer.java:562)
    android.view.Choreographer.doFrame(Choreographer.java:532)
    android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
    android.os.Handler.handleCallback(Handler.java:730)
    android.os.Handler.dispatchMessage(Handler.java:92)
    android.os.Looper.loop(Looper.java:137)
    android.app.ActivityThread.main(ActivityThread.java:5103)
    java.lang.reflect.Method.invokeNative(Native Method)
    java.lang.reflect.Method.invoke(Method.java:525)
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    dalvik.system.NativeStart.main(Native Method)
    Thread[Binder_2,5,main]
    dalvik.system.NativeStart.run(Native Method)
    Thread[JDWP,5,system]
    dalvik.system.NativeStart.run(Native Method)
    Thread[pool-1-thread-1,5,main]
    java.lang.Object.wait(Native Method)
    java.lang.Object.wait(Object.java:364)
    android.app.Instrumentation.startActivitySync(Instrumentation.java:403)
    android.support.test.runner.MonitoringInstrumentation.access$101(MonitoringInstrumentation.java:69)
    android.support.test.runner.MonitoringInstrumentation$3.call(MonitoringInstrumentation.java:265)
    android.support.test.runner.MonitoringInstrumentation$3.call(MonitoringInstrumentation.java:262)
    java.util.concurrent.FutureTask.run(FutureTask.java:234)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    java.lang.Thread.run(Thread.java:841)
    Thread[pool-5-thread-1,5,main]
    dalvik.system.VMStack.getThreadStackTrace(Native Method)
    java.lang.Thread.getStackTrace

A: I don't think you can actually test progress bars to see if they finish.
We used progress bars just as a way to show how far we were in time (for example day 7 out of a 30 day cycle so our progress bar never finished). To avoid this issue we had to use a different API level for our app. We seemed to only have this problem with an emulator with an API level of 21. Once we switched our emulator to API level of 19 our tests succeeded.
Note: We also had some success with changing the progressBar with plain views for the tests, but we decided that was more hacky than we liked.


text:
Q: Using TikZ in a browser like MathJax I'm guessing this has been done in a thread before, but I've just spent two hours reading various threads and cannot get my head around a very basic question.
Long story short:
I'm trying to create dynamic equations/diagrams in a web browser for a homework generator.  So far I've been using MathJax and loving it for the equation side of things.  It's very simple as I just need to include a single line of Javascript code and then I'm good to start coding:
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({tex2jax: {inlineMath: [['|','|'], ['\\
(','\\)']]}});
</script>
<script type="text/javascript"
  src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX- AMS-MML_HTMLorMML">
</script>

<?
$x = rand(2,5);
echo "x|^2| = ".pow($x,2).", so x = |\pm|$x";
?>

And it correctly turns that into the equation form on the browser.
Now, my goal is to do the same sort of thing with TikZ so I can create triangles and so forth on the fly using code like:
<?
$vertex1 = rand(2,5);
$vertex2 = rand(2,5);
?>
\documentclass[12pt, border=5mm]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw (0,0) node[anchor=north]{$A$}
  -- (<? echo $vertex1; ?>,0) node[anchor=north]{$C$}
  -- (<? echo $vertex1; ?>,<? echo $vertex2; ?>) node[anchor=south]{$B$}
  -- cycle;
\end{tikzpicture}
\end{document}

So my first question, which I think is answered "no" but is worth checking anyhow - is there a simple way to call TikZ in Javascript as with MathJax? Because that would be amazing.
If not, how can I get to a place where I can actually use TikZ from HTML/Javascript?  I believe that some websites show TikZ code, but I cannot find any documentation on this (everything just assumes I'm using a LaTeX program that can summon TikZ with a simple \usepackage{tikz} call, which I don't think MathJax can do).
For now, I'm running my scripts on a localhost my Macbook via MAMP, but eventually I would like to move it to an actual web server - but if it comes down to needing to install it at a root level, I can look into that. Just need some clear explanations since I'm really new to the technical side of LaTeX.

A: Yes, you can run TikZ in JavaScript via https://github.com/kisonecat/tikzjax and get SVG output.  After loading the appropriate CSS and JavaScript, it converts
<script type="text/tikz">
  \begin{tikzpicture}
    \draw (0,0) circle (1in);
  \end{tikzpicture}
</script>

into the expected SVG.
TikZJax works by actually running TeX itself in the browser.  With web2js the Pascal source of e-TeX
is compiled down to WebAssembly; running under node, the latex format is loaded (without all the hyphenation data), and
\documentclass[margin=0pt]{standalone}
\def\pgfsysdriver{pgfsys-ximera.def}
\usepackage{tikz}

is executed.  Then memory is dumped; by reloading the dumped memory in the browser, it is possible to very quickly get to a point where TikZ has been loaded.  (This amounts to playing the virtex and initex game, but in the browser.) By using an SVG driver for PGF along with dvi2html, the DVI output is converted to an SVG.
All of this really happens in the browser!  If you go to http://tikzjax.com/ and open the web console, you'll see the familiar output
This is e-TeX, Version 3.14159265-2.6 (preloaded format=latex 2019.2.22)


text:
Q: Python lxml tostring not print nsmap I'm working in a Doxygen XML parser. My problem is actually simple, I need to use LXML's tostring to get the raw contents of an XML element.
I have it working with ETree, but I switched to LMXL so I get strip_tags.
Let's say I have this XML file:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.16">
  <child2/>
  <child3/>
</root>

And I do this:
tree = ET.parse('new1.xml')
root = tree.getroot()
child3 = root.find("./child3")

objectify.deannotate(child3, cleanup_namespaces=True, xsi=True, pytype=True)
etree.cleanup_namespaces(child3)
child3.nsmap.clear()
etree.strip_attributes(child3, 'nsmap')

print(ET.tostring(child3, encoding='unicode', pretty_print=True))

This is what I get:
<child3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

This is what I WANT:
<child3/>

Is there an option to tostring to NOT print nsmap?
I tried:
If I try
root.nsmap = None

I get an exception:
AttributeError: attribute 'nsmap' of 'lxml.etree._Element' objects is not writable

I'm using Python 3.7 64 bits with Windows 10.
Thank you.

A: In the XML document, the http://www.w3.org/2001/XMLSchema namespace is in use. The xsi:noNamespaceSchemaLocation attribute is bound to that namespace.
In order to get the wanted output, you must 1) remove the xsi:noNamespaceSchemaLocation attribute and 2) remove the declaration of the namespace.
from lxml import etree

tree = etree.parse('new1.xml')
root = tree.getroot()

# Remove the xsi:noNamespaceSchemaLocation attribute
del root.attrib["{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation"]

# Remove the declaration for the now unused namespace. Must be done on the root element
etree.cleanup_namespaces(root)

child3 = root.find("./child3")

# Print child3
print(etree.tostring(child3, encoding='unicode', pretty_print=True))

# Print the whole document
print(etree.tostring(root, encoding='unicode', pretty_print=True))

Output:
<child3/>

<root version="1.8.16">
  <child2/>
  <child3/>
</root>


text:
Q: Accessing K8S Service in AWS Private Subnet not working Scenario in AWS EKS Service:

*

*Pods are running on service "web-ui-svc" in public subnet

*Another pods were running on service "web-api-svc" which is in private subnet

*Created Ingress for "web-ui", say "web-ui-ing"
Now Ingress "web-ui-ing" routes trafic to "web-ui-svc".
Expected:
"web-ui-svc" pods wants to communicate "web-api-svc" on port 1000 for API calls.
I tried by passing ENV like "web-api-svc:1000". Not working. But i could curl inside the Node.
Also when i access ingress url of "web-ui-ing", UI page is comming up but connectivity to web-api-svc is not happening..
Note: Both subnets are in same VPC which EKS Cluster using.
Do i need to configure proxy?, to route traffic to corresponding svc?
web-ui YAML(in AWS public subnet):
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    io.kompose.service: web-ui
  namespace: web
  name: web-ui
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: web-ui
  strategy: {}
  template:
    metadata:
      labels:
        io.kompose.network/net: "true"
        io.kompose.service: web-ui
    spec:
      containers:
        - env:
            - name: WEB_API_ENDPOINT
              value: "http://web-api:1000"
          image: ****.dkr.ecr.us-east-1.amazonaws.com/web/ui:latest
          name: web-ui
          ports:
            - containerPort: 3000
          resources: {}
      restartPolicy: Always
      nodeSelector:
        web_group: "web_group"
status: {}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    io.kompose.service: web-ui
  namespace: web
  name: web-ui
spec:
  ports:
    - name: "3000"
      port: 3000
      targetPort: 3000
  type: NodePort
  selector:
    io.kompose.service: web-ui
status:
  loadBalancer: {}

web-api.yaml(in AWS Private Subnet)
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    io.kompose.service: web-api
  namespace: web
  name: web-api
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: web-api
  strategy: {}
  template:
    metadata:
      labels:
        io.kompose.network/webui_net: "true"
        io.kompose.service: web-api
    spec:
      containers:
        - image: ****.dkr.ecr.us-east-1.amazonaws.com/test/webapi:latest
          name: web-api
          ports:
            - containerPort: 1000
          resources: {}
      restartPolicy: Always
      nodeSelector:
        web_api_group: "web_api_group"
status: {}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    io.kompose.service: web-api
  namespace: web
  name: web-api
spec:
  ports:
    - name: "1000"
      port: 1000
      targetPort: 1000
  selector:
    io.kompose.service: web-api
status:
  loadBalancer: {}

Do i need to create Proxy kind of thing here?


text:
Q: How sync data to a SQL server in multi-tenant setup from local sqlite I have a scenario where N clients connect to a central server (PostGres based). All of the N clients can get offline, and store everything in sqlite database. Is a service like fresh books, to make invoices.
Each client have a local copy of the main data (customers, products) filtered for that user. All client can update customers, products and each one work for their own invoices (i.e.: each client edit only his own invoices, but see aggregated data for everyone).
I know about add timestamp and GUID IDs, but not how approach this task. About how detect conflicts and auto-solve it, or if exist a sample code I can look about this..
P.D: Only sqlite is fixed. Because I'm in the planning stage, I could switch to any tech necessary that could solve better this task... I'm work with .net, python, django, obj-c

A: have a look at Sync Framework. although in your case, you may have to write a custom provider to work with the non-MS databases.
here's a sample using PostGres: InfoQ: Making Microsoft Sync Framework work with PostgreSql.
some links to Sync Framework to give you an idea how it works:
Synchronizing SQL Server and SQL Express
How to: Handle Data Conflicts and Errors for Database Synchronization (SQL Server)
Synchronizing Other ADO.NET Compatible Databases
Offline-Only Scenarios
How to: Use a Custom Change Tracking System


text:
Q: How do I set a generic type inside a generic class I have a few classes
class Parameters{..}
class CalculationParameters : Parameters{..}
class CalculatorParameters<T> : Parameters where T:CalculationParameters{..}

class FourierTransformParameters : CalculationParameters
{
    public double FourierTransformCoefficient{ get; set; }
}

class Calculation{..}
class FourierTransform : Calculation{..}

class Calculator<T> where T:Calculation
{
    public CalculatorParameters<?> Parameters{ get; private set; }

    public Calculator(T calculation,int p1)
    {
        Parameters = new CalculatorParameters<?>(calculation.Parameters,p1);
    }
}

In place of the questionmark, I would like to do something like T.TRelatedCalculationParameters,
because at the time of construction, I know what T is and the questionmark type is fully defined by T. This way I could call:
var ft         = new FourierTransform()
var calculator = new Calculator<FourierTransform>(ft,3);
calculator.Parameters.FourierTransformCoefficient = 3;

I there a way to achieve this somehow?
Thanks, Jan

A: Here you are constraining T to be type Calculation:
class Calculator<T> where T:Calculation

You then want to do:
class Calculator where T:Calculation
{
    public CalculatorParameters Parameters{ get; private set; }
In both cases T is contrained as type Calculation.
But you also have this, which contrains T to type CalculationParameters:
class CalculatorParameters : Parameters where T:CalculationParameters{..}
You cannot constrain T to both Calculation and CalculationParameters, as there is no inheritance relationship between them.


text:
Q: Permission denied in getting spanner session create in a java spring boot project using spanner emulator I am trying to run a basic spring boot application with JPA by using spanner emulator. However, I am getting the below error after startup after hitting any exposed end point.
PERMISSION_DENIED: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
Project has been cloned from https://github.com/GoogleCloudPlatform/google-cloud-spanner-hibernate/tree/master/google-cloud-spanner-hibernate-samples/spring-data-jpa-sample
and the only change I have done is updated the application.properties file.
as per my understanding spanner emulator should not have any IAM related issues as it doesn't need any. I am not sure what is causing this issue here. I have verified that the emulator config is the active config and hence I would expect the code to connect to emulator.
# Application configuration to use Cloud Spanner with Spring Data JPA

# Spanner connection URL.
# - ${PROJECT_ID} Replace with your GCP project ID
# - ${INSTANCE_ID} Replace with your Spanner instance ID
# - ${DATABASE_NAME} Replace with your Spanner database name within your Spanner instance
spring.datasource.url=jdbc:cloudspanner:/projects/test-project/instances/test-instance/databases/test-database

# Specify the Spanner JDBC driver.
spring.datasource.driver-class-name=com.google.cloud.spanner.jdbc.JdbcDriver

# Specify the Spanner Hibernate dialect.
spring.jpa.properties.hibernate.dialect=com.google.cloud.spanner.hibernate.SpannerDialect

#spring.jpa.hibernate.ddl-auto=update //same error even if I uncomment this line

# Settings to enable batching statements for efficiency
spring.jpa.properties.hibernate.jdbc.batch_size=100

# You may display SQL statements and stats for debugging if needed.
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true

Please find the console logs below:
2021-10-06 12:59:12.549  INFO 9747 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-10-06 12:59:12.556  INFO 9747 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-10-06 12:59:12.556  INFO 9747 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.53]
2021-10-06 12:59:12.617  INFO 9747 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-10-06 12:59:12.617  INFO 9747 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 694 ms
2021-10-06 12:59:12.707  INFO 9747 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-10-06 12:59:12.737  WARN 9747 --- [           main] c.g.a.oauth2.DefaultCredentialsProvider  : Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts, see https://cloud.google.com/docs/authentication/.
2021-10-06 12:59:14.558  INFO 9747 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-1 - Driver does not support get/set network timeout for connections. (Network timeout is not supported)
2021-10-06 12:59:22.165  INFO 9747 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-10-06 12:59:22.197  INFO 9747 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-06 12:59:22.231  INFO 9747 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.29.Final
2021-10-06 12:59:22.337  INFO 9747 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-06 12:59:22.396  INFO 9747 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: com.google.cloud.spanner.hibernate.SpannerDialect
2021-10-06 12:59:22.851  INFO 9747 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-06 12:59:22.857  INFO 9747 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-06 12:59:23.060  WARN 9747 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-10-06 12:59:23.184  INFO 9747 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
2021-10-06 12:59:23.290  INFO 9747 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-06 12:59:23.298  INFO 9747 --- [           main] com.example.CoffeeApplication            : Started CoffeeApplication in 12.957 seconds (JVM running for 13.227)
2021-10-06 12:59:33.646  INFO 9747 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-10-06 12:59:33.646  INFO 9747 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-10-06 12:59:33.647  INFO 9747 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Hibernate:
    select
        customer0_.id as id1_1_,
        customer0_.email as email2_1_,
        customer0_.name as name3_1_
    from
        customer customer0_
2021-10-06 12:59:35.650  WARN 9747 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 7, SQLState: null
2021-10-06 12:59:35.650 ERROR 9747 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : PERMISSION_DENIED: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
2021-10-06 12:59:35.668 ERROR 9747 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause

io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
        at io.grpc.Status.asRuntimeException(Status.java:535) ~[grpc-api-1.40.1.jar:1.40.1]
        at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:533) ~[grpc-stub-1.40.1.jar:1.40.1]
        at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39) ~[grpc-api-1.40.1.jar:1.40.1]
        at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23) ~[grpc-api-1.40.1.jar:1.40.1]
        at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40) ~[grpc-api-1.40.1.jar:1.40.1]
        at com.google.cloud.spanner.spi.v1.SpannerErrorInterceptor$1$1.onClose(SpannerErrorInterceptor.java:100) ~[google-cloud-spanner-6.12.5.jar:6.12.5]
        at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:557) ~[grpc-core-1.40.1.jar:1.40.1]
        at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:69) ~[grpc-core-1.40.1.jar:1.40.1]
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:738) ~[grpc-core-1.40.1.jar:1.40.1]
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:717) ~[grpc-core-1.40.1.jar:1.40.1]
        at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) ~[grpc-core-1.40.1.jar:1.40.1]
        at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133) ~[grpc-core-1.40.1.jar:1.40.1]
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_281]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_281]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_281]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.8.0_281]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_281]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_281]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_281]

A: The error is a clear indication that your application is not trying to connect to the emulator, but to a real Spanner database. In order to connect to the emulator instead of 'real' Cloud Spanner, you should do one of the following:

*

*Set the environment variable SPANNER_EMULATOR_HOST=localhost:9010

*OR: Edit the JDBC connection URL to include the autoConfigEmulator=true property. Your JDBC URL would then become jdbc:cloudspanner:/projects/test-project/instances/test-instance/databases/test-database;autoConfigEmulator=true
The advantage of the second alternative is that the autoConfigEmulator property will not only ensure that the JDBC driver is connecting to the emulator, it will also automatically create the test-instance and test-database on the emulator if they do not already exist.


text:
Q: Is there any single word that means "let people know of my presence" Sometimes we need to write a long expression in a single word. I need to know the single word or verb that means, "letting people know of one's own presence".
Here goes the context: There was this pair of macaws very close to me and I didn't notice them. They cried so loud all of a sudden that I felt they were trying to make me aware of their presence. And while writing about it I couldn't figure out the exact word to narrate the macaws' action.

A: Yes, it is, you can use to manifest oneself.

manifest - to show something clearly, through signs or actions

Source.

A: I can't think of a single word that means all that. You could use 'announcing myself' if you have arrived somewhere, or 'revealing myself' if you have come out of hiding.

A: I think you need the expression to make one's presence felt/heard/known:

If someone or something makes their presence felt, they do something that makes you notice them or pay attention. (free dictionary)

I am not sure you can find a single word for this meaning.


text:
Q: Is the countable product of normed spaces a normed space with this "norm" Consider the product $\mathcal{N} = \mathcal{N}_{1} \times \mathcal{N}_{2} \times \mathcal{N}_{3} \times \dots$ where $\mathcal{N}_{1}, \mathcal{N}_{2}, \mathcal{N}_{3}, \dots$ are normed spaces with norms $\| \cdot \|_{1}, \| \cdot \|_{2}, \| \cdot \|_{3}, \dots,$ respectively. I would like to know if the function $$ \| \vec{u} \| =  \left( \sum_{n \in \mathbb{N}} \| u_{n} \|_{n} ^{p} \right)^{\frac{1}{p}}, \text{ defined for } \vec{u} = \left( u_{1}, u_{2}, u_{3}, \dots \right) \in \mathcal{N}$$ is a norm on $\mathcal{N}.$
The function defined above satisfies the two first conditions to be a norm. However I am having a hard time figuring out if it satisfies the Triangle Inequality since the only method I know uses the Cauchy-Schwarz Inequality, but this requires a product between vectors and I don't have this concept in $\mathcal{N}.$ So I would like to ask here if somebody knows how to prove it does, or has a counterexample showing it doesn't.


text:
Q: Revert to the page's original CSS with jQuery I have a page with a 'printer friendly' button that uses jQuery's .css() method to remove some backgrounds and border from specific elements, and change the font size. I can set another .css() method to change everything back to the way it was, but is there any easy way to revert everything on the page to its original CSS (aside from refreshing the page)?

A: You should define your print friendly styles as selector rules in your main css file
body.printfriendly .selector .rule
{
  font-size:bigger;
}

And then you can add and remove the printfriendly class on the body tag to show or hide the rules.
You can also use the @media print section to declare rules that only get applied when the user prints.
@media print
{
   .selector .rule
   {
     font-size:bigger;
   }
}

A: You can remove all inline styles by doing something like
$('*[style]').removeAttr('style');

It will remove all styles set by jQuery, but also potentially any other inline styles set in the HTML. Not that I recommend it though.
I understand that you might not want to use a print style sheet. Some users would like to print the page as they see it, and you might want to add a preview before actually printing.
I recommend using a .printfriendly class that you can toggle to the body tag. That way you have full control in the CSS, and presentation layer.

A: You can use .removeClass to remove the class you attached
.addClass('printFriendly');

.removeClass('printFriendly');

A: Why you don't use a print style sheet that builds on top of you screen stylesheet?
This would be much cleaner:
in your HTML template:
<link href="/stylesheets/screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/print.css" media="print" rel="stylesheet" type="text/css" />

in your print.css:
@import "screen.css";
// overwrite disired parts of your screen.css

Now you can add a button with the following javascript command:
document.print();

to open the browsers default print promt.

A: The printer friendly button is pretty old school.  CSS 2 has a media rule mechanism.
@media print {
  /* style sheet for print goes here */
}


text:
Q: Method not launching I just started c#, thank you all for your patience.  I am following a course on udemy and i dont understand why my method is not launching.
Here is my code:
public class Program
{
    public void Exercise1()
    {
        Console.Write("Enter a number between 1 to 10: ");
        var input = Console.ReadLine();
        var number = Convert.ToInt32(input);
        if (number >= 1 && number <= 10)
            Console.WriteLine("Valid");
        else
            Console.WriteLine("Invalid");
    }

    static void Main(string[] args)
    {
          Exercise1();  // my method is not appearing in intelisense, what am i doing wrong?
    }
}

A: Just mark the method as static:
public class Program
{
    public static void Exercise1()
    {
        Console.Write("Enter a number between 1 to 10: ");
        var input = Console.ReadLine();
        var number = Convert.ToInt32(input);
        if (number >= 1 && number <= 10)
            Console.WriteLine("Valid");
        else
            Console.WriteLine("Invalid");
    }

    static void Main(string[] args)
    {
          Exercise1();
    }
}

The problem is that Main is static, meaning it doesn't need an instance of Program to run. If you want Main to call other methods in Program, those methods also need to be static.
The only other way to do it would be this:
public class Program
{
    public void Exercise1()
    {
        Console.Write("Enter a number between 1 to 10: ");
        var input = Console.ReadLine();
        var number = Convert.ToInt32(input);
        if (number >= 1 && number <= 10)
            Console.WriteLine("Valid");
        else
            Console.WriteLine("Invalid");
    }

    static void Main(string[] args)
    {
          var prog = new Program();
          prog.Exercise1();
    }
}


text:
Q: date-fns how can I calculate the min age? I use DateTimePicker and want to say the minimum age is 13. How can I say it ?
<DateTimePicker
...
minimumDate={new Date()}
/>

A: I solvd it with:
<DateTimePicker
  maximumDate={subYears(new Date(), 13)}
/>


text:
Q: Why can't I save new points created in QField? We are using QField 0.7.5 that seems a really great project to bring QGis on a mobile device.

*

*I prepared a QGis 2016 project : orthophoto + 1 polygon layer (casdatre) + 1 point layer to input data.

*I transferred the project and the data to a Galaxy Tab A (Android 5.0.2).
I open the project with QField and everything displays fine, I can move and query the data, really great.
But when I create a point, I can't save the new point (save don't save the new point).
Do you have any idea what's wrong?

A: There are potentially two things that could trigger this behavior.

*

*The project might be located on an external SD card. Android prevents apps from writing to external SD cards except for an app specific folder. If you save the project on an external SD card, put your data into the folder

/Android/data/ch.opengis.qfield/files

See also: Documentation, Issue report
The second reason no longer applies and is here for reference only

*The layer in which you digitize is not in the same CRS as the project itself. This is mentioned in the documentation. It is also reported as a bug in the current version that newly digitized geometries are not reprojected.
Update: This issue is fixed in QField >= 0.8

A: Thanks for the quick answer.
The pb was that my QGis project and the vector layers where in Lambert93 (SRC 2154).
I used the QGis extension QTiles to transform the raster orthophoto to the .mbtiles format, but the result file was in SCR 3857...
I put everything in SCR 3857 and that rocks !

A: Make sure you have the 'cable layer action' set to 'offline editing'
(Go to the QField tab in the layer properties)
For some reason the default 'cloud layer action' is set to 'offline editing' and the default 'cable layer action' is set to 'copy' - therefore the default 'cable layer action' version of the project (copied to QField via cable and not on through the clouds) does not allow editing until you set it to 'offline editing'.
At least for my version of QField/QGIS anyway...
Also, a few Python errors come up when you change the layer action, not sure what they mean but it doesn't affect the end goal here.


text:
Q: Sort Dates when Dates are missing I have a series of start and end dates that I am trying to sort.  I have instances where there are two start dates without a missing end date that would be between the two start dates.  How can I create a sort that will reflect this and leave the cell between the two dates blank?
I have been able to do a simple bubble sort. but it fills in where the missing date should be.
Given the four dates below I want the vb coding to leave Hire Date 2 blank
HIRE DT1   TERM DT1   HIRE DT2   TERM DT2   HIRE DT3
---------- ---------- ---------- ---------- ----------
04/01/2000 12/01/2005 (Blank)    09/01/2008 08/01/2010

Currently my result shows the correct order for HIRE and TERM separately, but not as it should be above.
HIRE DT1   TERM DT1   HIRE DT2   TERM DT2   HIRE DT3
---------- ---------- ---------- ---------- ----------
04/01/2000 12/01/2005 08/01/2010 09/01/2008 (Blank)


text:
Q: Comparing 2 win32 classes to get related information Ok the code is super simple but I can't seem to pull the manufacturer information. It has been about a year since I last sat scripted with powershell but it doesn't seem like it should be so difficult to get this to work.
$Var1 = GWMI Win32_PhysicalMedia
$Var2 = GWMI Win32_diskdrive |Select model
ForEach ($Item in $var2) {
    $Item |Select model |Where {$_.deviceID -eq $Var1.tag}
}

A: A couple of notes: This bit:
$Var2 = GWMI Win32_diskdrive |Select model
ForEach ($Item in $Var2) {
 $Item |Select model |Where {$_.deviceID -eq $Var1.tag}
}

You're basically saying: "Give me the "model" property of the win32_diskdrive(s), and then later you want to filter on the "deviceId" property (which you don't have because you selected only model).
Also, you're assuming $var1 is an object, not an array of objects (which it very well could be). If you want to iterate each of the items in $var2 and compare it to each of the objects in $var1 and see if you have a match, I would put another loop inside your loop (note that there are other ways to search arrays besides this):
 $Var1 = GWMI Win32_PhysicalMedia
 $Var2 = GWMI Win32_diskdrive
 #Iterate through each item in $var2
 ForEach ($Item in $Var2) {
     #Iterate through each item in $var1
     foreach ($var1item in $var1)
         {
             #look for a match
             $founditem = $Item |Where {$_.deviceID.tostring() -eq $var1item.tag.tostring()}
             if ($founditem)
                 {
                     #if match, return the object
                     $FoundItem
                 }

         }

 }

I would advise you to spend some time debugging these types of problems by looking at the objects PowerShell returns with .Gettype() and | get-member. Understanding the objects you work with is key to understanding PowerShell.

A: In your foreach loop, the variable name you are calling is $var2 not $Var2 as you used earlier. I made the change on my system and  it worked.
$Var1 = GWMI Win32_PhysicalMedia
$Var2 = GWMI Win32_diskdrive |Select model
ForEach ($Item in $Var2) {
    $Item |Select model |Where {$_.deviceID -eq $Var1.tag}
}

Hope this helps!

A: Maybe you want
$drives = gwmi win32_diskdrive
$media = gwmi Win32_PhysicalMedia
foreach ($d in $drives) {
  $media | where {$_.tag -eq $d.deviceID} | select <comma-separated list of properties>
}

or just
gwmi win32_diskdrive | select deviceID, model | ft -auto

Or what manufacturer information are you looking for exactly?


text:
Q: How to use htmlunit + jsoup to scrape websites that uses javascript to load content dynamically https://www.reddit.com/r/buildapcsales/top/ takes like 3~ seconds to load all the content. Currently using jsoup I can only scrape the first 7 threads since the other threads are loaded after a few seconds. I'm trying to make htmlunit load the entire page then use jsoup to scrape all the thread titles.
        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setJavaScriptEnabled(true);
        Page page = webClient.getPage(url.toString());
        WebResponse response = page.getWebResponse();
        String content = response.getContentAsString();

      //  webClient.getOptions().setJavaScriptEnabled(true);
      //  webClient.getOptions().setThrowExceptionOnScriptError(true);
       // webClient.waitForBackgroundJavaScript(50000);
       // webClient.wait(5000);
       // HtmlPage page = webClient.getPage(url.toString());

I keep getting a million errors whenever I setJavascriptEnabled to true, but if I turn it false. It doesn't error out, however I still get the 7 threads with jsoup.
WARNING: Script is not JavaScript (type: 'application/json', language: ''). Skipping execution.
Feb 09, 2020 4:54:36 PM com.gargoylesoftware.htmlunit.javascript.DefaultJavaScriptErrorListener scriptException
SEVERE: Error during JavaScript execution
======= EXCEPTION START ========
Exception class=[net.sourceforge.htmlunit.corejs.javascript.EvaluatorException]
com.gargoylesoftware.htmlunit.ScriptException: syntax error (https://www.redditstatic.com/desktop2x/vendors~Governance~Reddit.791bf381e13bfdc452ab.js#1)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:882)
    at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:624)
    at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:537)
    at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:354)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.compile(JavaScriptEngine.java:713)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.compile(JavaScriptEngine.java:679)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.compile(JavaScriptEngine.java:103)
    at com.gargoylesoftware.htmlunit.html.HtmlPage.loadJavaScriptFromUrl(HtmlPage.java:1104)
    at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:984)
    at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:361)
    at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:234)
    at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:301)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:560)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:419)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:336)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:488)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:469)
    at RedditScraper.main(RedditScraper.java:40)
These are some of the first few errors

A: I was having a hard time with trying to run javascript inside of HtmlUnit. Then I tried Selenium, and it worked like a charm.


text:
Q: How do I decode a PEM-encoded PKIX public key? The example given in Go's official documentation for x509.ParsePKIXPublicKey encounters a runtime error because the Block that pem.Decode() returns is nil.
 (Playground example)
However, the example in the official documentation for pem.Decode() runs just fine. (Playground example)
The only difference I've spotted between the two examples is the the way the public key is initialized and they way it is used in pem.Decode().
First example:
const pubPEM = `
    -----BEGIN PUBLIC KEY-----
    ...
    -----END PUBLIC KEY-----`
block, _ := pem.Decode([]byte(pubPEM))

Second example:
var pubPEMData = []byte(`
    -----BEGIN PUBLIC KEY-----
    ...
    -----END PUBLIC KEY-----`)
block, rest := pem.Decode(pubPEMData)

I've edited the first example so that it is done in the same way as the second, but this did not change the outcome. (Playground example)
What is causing the first to fail but not the second?

A: You have spaces in your string, remove them and it will work: fixed example


text:
Q: why is the output of System.out.println((5/2.0)*2); is 5.0? I think 5 is an int. But there are no variables. I don't know why the output is a double. I tried in Netbeans already.

A: Multiplication and division are done left to right (and regardless, you put parentheses around the first operation), and if you divide any primitive umber by a double, you will get a double out of it.
5/2.0 will clearly be evaluated first.
So, even though '5' is an int, if you do 5/2.0, you'll get a double (namely, 2.5). Now, at this point, your code is already working with a double.
When you multiply 2.5 by 2, you then output 5.0, since 2.5 is a double.


text:
Q: Convert raw SQL to Django QuerySet Could someone show how to convert the following SQL query to the Django QuerySet call? I'm a new to Django and I could use the raw query, but it's interesting for me to know how do this query could be written as a native Django call.
There are 2 models User & Profile 1:1
I need to fetch the emails from the User and the phone from the Profile if the same phone number appears in 2 or more profiles.
SELECT
   GROUP_CONCAT(u.email) as emails, p.phone as phone_number
FROM
    profile AS p JOIN auth_user AS u on u.id = p.user_id
GROUP BY
    phone
HAVING
    COUNT(phone) > 1
Here what I tried to do:
from myapp.models import Profile
from django.db.models import Count

Profile.objects
       .exclude(phone='')
       .annotate(phone_count=Count('phone'))
       .values('phone')

..and the result is:
[
  {
    'phone': '***'
  },
  {
    'phone': '***'
  }
]

If to add .filter(phone_count__gt=1) to the query then an empty result will be returned (don't understand why).
The desired output is:
[
    {
      'phone': '***',
      'emails': 'user1@mail.com'
    },
    {
      'phone': '***',
      'emails': 'user2@mail.com,user3@mail.com'
    }
  ]

UPD
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=100, blank=True, null=True)

A: from myapp.models import Profile
from django.db.models import Count

qs = Profile.objects.exclude(
    phone=''
).exclude(
    phone__isnull=True
).values('phone').annotate(
    phone_count=Count('user_id')
).filter(
    phone_count__gt=1
).values_list('phone', flat=True)
# the above will get you a list of phone numbers that appear more than once
# now get the user_ids, too, and add in the emails
qs = Profile.objects.filter(phone__in=qs).values_list('user__email', 'phone')
# now convert to a dict
from collections import defaultdict
data = defaultdict(list)
for email, phone in qs:
    data[phone].append(email)
# now convert to desired format
result = [{
    'phone': phone,
    'emails': ','.join(emails),
} for phone, emails in data.itervalues()]

# Of course, you could always just use raw and do a raw
# SQL query as described here:  https://docs.djangoproject.com/en/1.9/topics/db/sql/#executing-custom-sql-directly


text:
Q: jOOQ into() / fetchInto() maps properties to null I want to map a resultset of a simple query to my domain object but when I use the into() method then some properties are just null
Result<DepartmentRecord> fetch = dsl.selectFrom(DEPARTMENT).fetch();
List<Department> collect = fetch.stream().map(f -> new Department(f.getId(), f.getName())).collect(Collectors.toList());
System.out.println("collect: " + collect);

// WORKS
// prints: collect: [Department [id=1, name=Mooh], Department [id=2, name=Mooh2]]

List<Department> into = fetch.into(Department.class);
System.out.println("into: " + into);
// DOESN'T WORK: name is null
// prints: into: [Department [id=1, name=null], Department [id=2, name=null]]

Here is my domain object / JPA entity:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {

    @Id
    @GeneratedValue
    private int id;

    private String name;
}

What do I do wrong?
Using Spring Boot 2.1.8, jOOQ 3.11.0, OpenJDK 11

A: Because you have a default constructor and the name of the property is dname but I the database column name is different I assume (e.g. name).

If a default constructor is available and if there are no JPA Column annotations, or jOOQ can't find the javax.persistence API on the classpath, jOOQ will map Record values by naming convention:

https://www.jooq.org/javadoc/3.12.x/org.jooq/org/jooq/impl/DefaultRecordMapper.html


text:
Q: Prove that a function is linear Let $U \subseteq \mathbb R^k$ be an connected open set, and let $f:U\to\mathbb R$.
Suppose that $\forall p\in U$, there exists a closed set $C$ with non-empty interior such that $p\in C$ and $f(x)=a_C\cdot x+b_C$ on $C$ ($a_C \in \mathbb R^k$ is a constant vector and $b_C$ is a constant for each $C$).
Prove that $f$ is linear over $U$ (that is, $f(x)=a\cdot x + b$).
It seems really intuitive and straight forward but I don't even know how to get started.

A: This is false as written. Consider
$f : \Bbb{R}\to\Bbb{R}$ defined by
$$f(x) =\begin{cases} x & x\le 0 \\ 2x & x > 0 \end{cases}$$
Then we can cover $\Bbb{R}$ by the closed sets with nonempty interior $(-\infty, 0]$ and $[0,\infty)$, and $f$ is linear on each of these closed sets. Thus this is a counterexample to the claim.
The claim can be saved by requiring $p$ to be in the interior of your closed sets (which means you may as well just take open sets in the first place), and this can be proved by following the argument given by Will M. in the comments.


text:
Q: Observer runs only once Event only runs once. I am adding custom value in quote after product add in cart through observer on event checkout_quote_init
    it works fine but if customer is logged in and place order then in first order value is inserted well in quote but in second time observer is not runing.
<checkout_quote_init>
    <observers>
        <youva_custom>
            <type>singleton</type>
            <class>custom/observer</class>
            <method>setqoutevalue</method>
        </youva_custom>
    </observers>
 </checkout_quote_init>

 public function setqoutevalue($observer) {
     $event = $observer->getEvent();
     $_quote = $event->getQuote();
     $_quote->setCustomevalue($customevalue);
     $_quote->save();
 }

A: If you take a look at the code that dispatches the event you are using you will see this (Mage_Checkout_Model_Session::getQuote()):
        if (!$this->getQuoteId()) {
            if ($customerSession->isLoggedIn() || $this->_customer) {
                $customer = ($this->_customer) ? $this->_customer : $customerSession->getCustomer();
                $quote->loadByCustomer($customer);
                $this->setQuoteId($quote->getId());
            } else {
                $quote->setIsCheckoutCart(true);
                Mage::dispatchEvent('checkout_quote_init', array('quote'=>$quote));
            }
        }

This means that the event is dispatched only when the quote is created. and only when the user is not logged in. This means that if there is already a quote id in the session the event won't get dispatched.
You may want to use a different event. For example checkout_cart_product_add_after


text:
Q: Accessing WMS with Basic Authentication? I am trying to access a Basic-Auth secured WMS Service. When requesting the Capabilities document, the service will always list some layers, even without authentication. But with authentications, more layers should be listed.
Unfortunately it won't work, only publicly available layers are listed in ArcGIS Pro. When I look at the HTTP request I can not see an Authorization header.
What kind of authentication is used in ArcGIS Pro (or ESRI products in general) when adding username/password in the "Add WMS Server Connection" Dialog? How is this intended to work?
I am completely in control of said service, it is possible to debug and configure any way we like. At the moment it supports HTTP Basic only but other methods could be implemented. I tested this service with a Browser and QGIS, where everything works as expected.

A: Unlike QGIS for example, ArcGIS Pro won't just happily send user credentials in the initial Request. It tries without Authorization header first, expects a 401 Unauthorized Status and a WWW-Authenticate Basic Header in return. Then, and only then, the Authorization header with user credentials will be set. This is per the Spec, but happens to be a bit inconvenient.
In our case, we always want to answer with a Capabilities document, because we need authentication only for some layers. An unauthorized user will therefore just get a much shorter list of layers. An additional mechanism for distinguishing users is needed, I opted for an additional HTTP GET parameter in the URL.


text:
Q: Is it possible to connect your background script to mongoDB server? If Yes, How? I am creating a google chrome extension. I have a background script from which I want to send and retrieve some data from MongoDB database. How do I do that? I'm new in chrome extension development.

A: YES. It's possible. But, It's not a good idea to expose a database to the public internet at all. Implement a REST like method in your backend code and authorize calls to it using some web standard auth scheme, such as OAuth or HTTP Basic auth. Hitting the DB directly is way too dangerous. You can receive/send data from DB accordingly. Saying That if you still want to go ahead here's a link to help you with that For full REST capabilities, consider using an external REST Interface such as Sleepy.Mongoose.


text:
Q: Ruby One Line Or Conditional with Nil Checks In Ruby, I would like to do a single line conditional with an or statement that has multiple checks for nil. For example:
warn = my_val >= max if max or my_val <= min if min

It's possible that max and/or min will be nil, so I only want to do the comparison if the one or both of the values exist. Is there a way to do this type of logic in one line?

A: warn = (max and my_val >= max) or (min and my_val <= min)

A: Assume the following:
> max = 3;  min = 0; my_val = 0;

@PardeepDhingra's answer seems correct.
> warn = (max && my_val >= max) || (min && my_val <= min)
=> true

The accepted answer by @ThomasHaratyk appears to have a logical flaw with this scenario:
> warn = max ? my_val >= max :  ( min ? my_val <= min : false )
=> false

A: Here is a possible solution :
warn = !my_val.between? (min || -Float::INFINITY), (max || Float::INFINITY)

Old wrong solution for comments context
# warn = max ? my_val >= max :  ( min ? my_val <= min : false )

A: This should work:
warn = my_val >= max or my_val <= min unless max.nil? and min.nil?

A: I don't seriously think that anyone would pull in ActiveSupport just for its try for such a simple task, but I can't just not suggest it. It kind of reminds me of the old "jQuery way of solving everything" and looks almost readable.
warn = max.try(:>=, my_val) || min.try(:<=, my_val)

Just in case it's not clear enough: don't pull in ActiveSupport just for that unless you are already using it (in Rails or for whatever other reason). But if you like the readability, you can add ActiveSupport and require only active_support/core_ext/object/try for a minimal memory footprint.

A: Since I can't use my original answer, let me try a real-life one:
def doit(min, max, my_value)
  case [min.nil?, max.nil?]
  when [false, false] then my_value <= min || my_value >= max
  when [false, true ] then my_value <= min
  when [true,  false] then my_value >= max
  when [true,  true ] then false
  end
end

doit 5,7,8     #=> true
doit 5,7,4     #=> true
doit 5,7,6     #=> false
doit nil,7,8   #=> true
doit 5,nil,4   #=> true
doit 5,nil,8   #=> false
doit nil,nil,4 #=> false


text:
Q: Как узнать какие схемы относятся к tablespace Об оракле имею очень очень приблизительное представление.
Есть название тэйблспейса. Например test_tablespace. Ну и имя сервера известно тоже - test. Как составить запрос, показывающий, какие схемы относятся к указанному тейблспейсу и сколько занимают места?
Не гневайтесь, если в вопросе написал что-то не корректно.

A: select tablespace_name,owner,TRUNC(sum(bytes)/1024/1024) Meg
  from dba_segments s
 where tablespace_name='test_tablespace'
 group by owner,tablespace_name

У меня есть подозрение, что имя tablespace должно быть большими буквами. По крайней мере у меня все большими, но может это я так их называю :)


text:
Q: How to do rails db:migrate on multiple shards that are not master slave relationship at once on rails? I have an app which which uses different database based on the subdomain. So essentially, the schema would be the same, but the data would differ for each databases. But when I release some new features and it would require some schema changes, I would need to run a command that would run on all databases configured in the shards.yml.
database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  pool: 15
  host: localhost
  port: 5432
  username: postgres
  password:

development:
  <<: *default
  database: app_default
production:
  <<: *default
  database: app_default
  username: <%= ENV['BACKEND_DATABASE_USERNAME'] %>
  password: <%= ENV['BACKEND_DATABASE_PASSWORD'] %>

shards.yml
shared: &shared
  adapter: postgresql
  encoding: unicode
  pool: 15
  host: localhost
  username: postgres
  password:
  port: 5432

octopus:
  environments:
    - development
    - test
    - production
  development:
    default:
      <<: *shared
      database: app
    first:
      <<: *shared
      database: first
    second:
      <<: *shared
      database: second
    ....
  test:
    test:
      host: postgres
      adapter: postgresql
      database: app_test
  production:
    default:
      <<: *shared
      database: app
    first:
      <<: *shared
      database: first
    second:
      <<: *shared
      database: second
    ....

I am using Octopus to set the shard based on subdomain, which works fine. The problems I have are:

*

*I cannot do rails db:reset . Getting the error ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR:  cannot drop the currently open database

*I cannot do rails db:migrate that would migrate on all databases

A: You have to add using to your migrations
class CreateComments < ActiveRecord::Migration
  using :first, :second

  def change
    create_table :comments do |t|
      t.belongs_to :page, index: true
      t.text :body

      t.timestamps
    end
  end
end

the above migration will run on both first and second


text:
Q: how can an adjective function as an adverb Yet because the immediate effect of the medicine is to make the patient feel rapidly better and she is not told what might happen later,she goes home happy.
In the last half of this sentence ,the "happy"is used kind of like "happily",but how can it be used this way?in what situation and in what way,an adjective can be put at the end of a sentence this way?

A: From a comment by BoldBen...
The word "happy" is not modifying "goes" it is modifying "she". In other words it is an adjective describing the patient's state of mind. There is, actually, a comma missing from the text; the whole passage from "because" to "later" is parenthetical so the main part of the sentence is "Yet she goes home happy." This makes it much clearer that the adjective refers to the woman.


text:
Q: How to get a property depending on the Role of connected User? I have a Product Entity, want to get all the informations of product if the user connected is SUBADMIN, but I don't want the description to be received if the user connected is a simple ADMIN, I am using this groups annotations, and I know about read and write properties, but I don't know how to get the result I want.
/**
 * @ApiResource(
        itemOperations={
 *          "get"={
 *              "normalization_context"={"groups"="read"}
 *          },
 *          "put"={"access_control"="isgranted('ROLE_ADMIN') or isgranted('ROLE_SUBADMIN')"},
 *          "delete"={"access_control"="isgranted('ROLE_ADMIN') or isgranted('ROLE_SUBADMIN')"}
 *      },
 *      collectionOperations={
 *          "get"={
 *              "normalization_context"={"groups"="read"}
 *          },,
 *          "post"={"access_control"="isgranted('ROLE_ADMIN') or isgranted('ROLE_SUBADMIN')"}
 *      },
 * )
 * @ORM\Entity(repositoryClass="App\Repository\ProduitRepository")
 */
class Produit
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("read")
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("read")
     */
    private $title;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("read")
     */
    private $description;

    // getters and setters here
}

Do I have to use ContextBuilder to customize this ?


text:
Q: Problema con el PHP Undefined index: como soy nuevo con el manejo de php  me salio un error que no pude arreglar, el error que me salto es este "Undefined index: color". Les dejo el HTML, Lo que quiero hacer yo es que del select tomar el valor elegido y subirlo a la base de datos para poder tener un registros de los pedidos que me encargan en la pagina.

<form action="pedidosBuzos.php" class="formularioB formulario">
        Color del Buzo
        <select name="color" id="" class="formulario__input">
            <option SELECTED>Seleccionar color</option>
            <option value="negro">Negro</option>
            <option value="blanco">Blanco</option>
            <option value="rojo">Rojo</option>
            <option value="bordo">Bordo</option>
            <option value="azul">Azul</option>
        </select>
        Talle
        <select name="talla" id="" class="formulario__input">
            <option SELECTED>Seleccionar Talle</option>
            <option value="s">S</option>
            <option value="m">M</option>
            <option value="l">L</option>
            <option value="xl">XL</option>
            <option value="xxl">XXL</option>
        </select>
        <input type="submit" class="formulario__submit" value="Pedir">
    </form>

En el PHP lo que hice fue capturar los datos mediante el metodo POST y desde ahi insertarlo en la base de datos, Lo que no entiendo es que procedimiento hice mal. Desde ya les agradesco su ayuda.
Mi código PHP que procesa la información
<?php

include 'cn.php';

$color = $_POST['color'];
$talla = $_POST['talla'];
$prenda = 'buzo';

$insertar = "INSERT INTO pedi(color, talla, sexo, prenda)
             VALUES ('$prenda', '$color', '$talla')";
$resultado = mysqli_query($conexion, $insertar);

if (!$resultado)
{
    echo '';
}else{
    echo '';
}
mysqli_close($conexion);

A: Eso ocurre por que en tu formulario olvidaste indicar el method a usar; es decir en este caso hacer esto
<form action="pedidosBuzos.php" method="POST">

Ya que tu en tu archivo .php estas indicando que esperas recibir 2 valores enviados por ese verbo HTTP pero en tu formulario no lo indicas, entonces solo agrégalo y funcionará
Para que consultes mas sobre el tema, aquí te dejo una fuente oficial

*

*Trabajo con formualrios