text:
Q: AArch64 relocation prefixes I noticed a GNU asm relocation syntax for ARM 64-bit assembly. What are those pieces like #:abs_g0_nc: and :pg_hi21:? Where are they explained? Is there a pattern to them or are they made up on the go? Where can I learn more?

A: Introduction
ELF64 defines two types of relocation entries, called REL and RELA:
typedef struct
{
    Elf64_Addr r_offset;    /* Address of reference */
    Elf64_Xword r_info;     /* Symbol index and type of relocation */
} Elf64_Rel;

typedef struct
{
    Elf64_Addr r_offset;    /* Address of reference */
    Elf64_Xword r_info;     /* Symbol index and type of relocation */
    Elf64_Sxword r_addend;  /* Constant part of expression */
} Elf64_Rela;

The scope of each relocation entry is to give the loader (static or dynamic) four pieces of information:

*

*The virtual address or the offset of the instruction to patch.
This is given by r_offset.

*The runtime address of the symbol accessed.
This is given by the higher part of r_info.

*A custom value called addend
This value, eventually, as an operand in the expression used to calculate the value that will be written to patch the instruction.
RELA entries have this value in r_addend, REL entries extract it from the relocation site.

*The relocation type
This determines the type of expression uses to calculate the value to patch the instruction. This is encoded in the lower part of r_info.
Relocating
During the relocation phase the loader goes through all the relocation entries and write to the location specified by each r_offset, using a formula chosen by the lower part of r_info to compute the value to be stored from the addend (r_addend for RELA) and the symbol address (obtainable from the upper part of r_info).
Actually the write part has been simplified, contrary to other architecture where the immediate field of an instruction usually occupy entirely separate byes from the ones used to encode the operation, in ARM, the immediate value is mixed with other encoding information.
So the loader should know what kind of instruction is trying to relocate, if it is an instruction at all1, but instead of letting it disassemble the site of relocation, it is the assembler that set the relocation type according to the instruction.
Each relocation symbol can relocate only one or two, encoding-equivalent, instructions.
In specific case the relocation itself even change the type of instruction.
The value compute computed during the relocation is implicitly extended to 64 bits, signed or unsigned based on the relocation type chosen.
AArch64 relocation
Being ARM a RISC architecture with fixed instruction size, loading full width, i.e. 64 bits, immediate into a register is non trivial as no instruction can have a full width immediate field.
Relocation in AArch64 has to address this issue too, it is actually a two fold problem: first, find the real value that the programmer intended to use (this is the pure relocation part of the problem); second, find a way to put it into a register, since no instruction has a 64 bits immediate field.
The second issue is addressed by using group relocation, each relocation type in a group is used to compute a 16 bits part of the 64 bits value, therefore there can only be four relocation type in a group (ranging from G0 to G3).
This slicing into 16 bits comes to fit with the movk (move keeping), movz (move zeroing) and movn (move negating logically).
Other instructions, like b, bl, adrp, adr and so on, have a relocation type specially suited for them.
Whenever there is only one, thus unambiguous, possible relocation type for a given instruction that reference a symbol, the assembler can generate the corresponding entry without the need, for the programmer, to specify it explicitly.
Group relocation doesn't fit into this category, they exist to allow the programmer some flexibility, thus are generally explicitly stated.
In a group, a relocation type can specify if the assembler must perform an overflow check or not.
A G0 relocation, used to load the lower 16 bits of a value, unless explicitly suppressed, check that the value can fit 16 bits (signed or unsigned, depending on the specific type used).
The same is true for G1, that loading bits 31-16 check that the values can fits 32 bits.
As a consequence G3 is always non checking as every value fits 64 bits.
Finally, relocation can be used to load integer values into register.
In fact, an address of a symbol is nothing more than an arbitrary integer constant.
Note that r_addend is 64 bits wide.

1 If r_offset points to a site in a data section the computed value is written as 64 bits word at the location indicated.
Relocation operators
First of all, some references:

*

*The ARM document that describes the relocation types for the ELF64 format is here, section 4.6

*A test AArch64 assembly file that, presumably, contains all the relocation operators available to GAS is here here
Conventions
Following the ARM document convention we have:

S is the runtime address of the symbol being relocated.
A is the
  addend for the relocation.
P is the address of the relocation site
  (derived from r_offset).
X is the result of a relocation
  operation, before any masking or bit-selection operation is applied.
Page(expr) is the page address of the expression expr, defined as
  expr & ~0xFFF, i.e. expr with the lower 12 bits cleared.
  GOT is
  the address of the Global Offset
  Table.
GDAT(S+A) represents a 64-bit entry in the GOT for address S+A. The
  entry will be relocated at run time with relocation
  R_AARCH64_GLOB_DAT(S+A).
G(expr) is the address of the GOT
  entry for the expression expr.
Delta(S) resolves to the difference
  between the static link address of S and the execution address of
  S. If S is the null symbol (ELF symbol index 0), resolves to the
  difference between the static link address of P and the execution
  address of P.
Indirect(expr) represents the result of calling
  expr as a function.
[msb:lsb] is a bit-mask operation
  representing the selection of bits in a value, bounds are inclusive.

Operators
The relocation name is missing the prefix R_AARCH64_ for the sake of compactness.
Expressions of the kind |X|≤2^16 are intended as -2^16 ≤ X < 2^16,  note the strict inequality on the right.
This is an abuse of notation, called by the constrains of formatting a table.
Group relocations
Operator    | Relocation name | Operation | Inst | Immediate | Check
------------+-----------------+-----------+------+-----------+----------
:abs_g0:    | MOVW_UABS_G0    | S + A     | movz | X[15:0]   | 0≤X≤2^16
------------+-----------------+-----------+------+-----------+----------
:abs_g0_nc: | MOVW_UABS_G0_NC | S + A     | movk | X[15:0]   |
------------+-----------------+-----------+------+-----------+----------
:abs_g1:    | MOVW_UABS_G1    | S + A     | movz | X[31:16]  | 0≤X≤2^32
------------+-----------------+-----------+------+-----------+----------
:abs_g1_nc: | MOVW_UABS_G1_NC | S + A     | movk | X[31:16]  |
------------+-----------------+-----------+------+-----------+----------
:abs_g2:    | MOVW_UABS_G2    | S + A     | movz | X[47:32]  | 0≤X≤2^48
------------+-----------------+-----------+------+-----------+----------
:abs_g2_nc: | MOVW_UABS_G2_NC | S + A     | movk | X[47:32]  |
------------+-----------------+-----------+------+-----------+----------
:abs_g3:    | MOVW_UABS_G3    | S + A     | movk | X[64:48]  |
            |                 |           | movz |           |
------------+-----------------+-----------+------+-----------+----------
:abs_g0_s:  | MOVW_SABS_G0    | S + A     | movz | X[15:0]   | |X|≤2^16
            |                 |           | movn |           |
------------+-----------------+-----------+------+-----------+----------
:abs_g1_s:  | MOVW_SABS_G1    | S + A     | movz | X[31:16]  | |X|≤2^32
            |                 |           | movn |           |
------------+-----------------+-----------+------+-----------+----------
:abs_g2_s:  | MOVW_SABS_G2    | S + A     | movz | X[47:32]  | |X|≤2^48
            |                 |           | movn |           |
------------+-----------------+-----------+------+-----------+----------

In the table the ABS version is showed, the assembler can pickup the PREL (PC relative) or the  GOTOFF (GOT relative) version depending on the symbol referenced and the type of output format.
A typical use of this relocation operators is
Unsigned 64 bits                      Signed 64 bits
movz    x1,#:abs_g3:u64               movz  x1,#:abs_g3_s:u64
movk    x1,#:abs_g2_nc:u64            movk  x1,#:abs_g2_nc:u64
movk    x1,#:abs_g1_nc:u64            movk  x1,#:abs_g1_nc:u64
movk    x1,#:abs_g0_nc:u64            movk  x1,#:abs_g0_nc:u64

Usually one one checking operator is used, the one that set the highest part.
That's why checking version relocates movz only, while the non checking version relocates movk (which partially set a register).
G3 relocated both because it is intrinsically non checking as no value can exceed 64 bits.
The signed versions ends with _s and they are always checking.
There is no G3 version because if a 64 bits value is used the sign if sully specified in the value itself.
They are always used only to set the highest part, as the sign is relevant only there.
They are always checking as an overflow in a signed value make the value meaning less.
These relocations change the type of the instruction to movn or movz based on the sign of the value, this effectively sign extend the value.
Group relocations, are also available
PC-relative, 19, 21, 33 bits addresses
Operator    | Relocation name | Operation | Inst | Immediate | Check
------------+-----------------+-----------+------+-----------+----------
[implicit]  | LD_PREL_LO19    | S + A - P | ldr  | X[20:2]   | |X|≤2^20
------------+-----------------+-----------+------+-----------+----------
[implicit]  | LD_PREL_LO21    | S + A - P | adr  | X[20:0]   | |X|≤2^20
------------+-----------------+-----------+------+-----------+----------
[implicit]  | LD_PREL_LO21    | S + A - P | adr  | X[20:0]   | |X|≤2^20
------------+-----------------+-----------+------+-----------+----------
:pg_hi21:   | ADR_PREL_PG     | Page(S+A) | adrp | X[31:12]  | |X|≤2^32
            | _HI21           | - Page(P) |      |           |
------------+-----------------+-----------+------+-----------+----------
:pg_hi21_nc:| ADR_PREL_PG     | Page(S+A) | adrp | X[31:12]  |
            | _HI21_NC        | - Page(P) |      |           |
------------+-----------------+-----------+------+-----------+----------
:lo12:      | ADD_ABS_LO12_NC | S + A     | add  | X[11:0]   |
------------+-----------------+-----------+------+-----------+----------
:lo12:      | LDST8_ABS_LO12  | S + A     | ld   | X[11:0]   |
            | _NC             |           | st   |           |
------------+-----------------+-----------+------+-----------+----------
:lo12:      | LDST16_ABS_LO12 | S + A     | ld   | X[11:1]   |
            | _NC             |           | st   |           |
------------+-----------------+-----------+------+-----------+----------
:lo12:      | LDST32_ABS_LO12 | S + A     | ld   | X[11:2]   |
            | _NC             |           | st   |           |
------------+-----------------+-----------+------+-----------+----------
:lo12:      | LDST64_ABS_LO12 | S + A     | prfm | X[11:3]   |
            | _NC             |           |      |           |
------------+-----------------+-----------+------+-----------+----------
:lo12:      | LDST128_ABS     | S + A     | ?    | X[11:4]   |
            | _LO12_NC        |           |      |           |

The :lo12: change meaning depending on the size of the data the instruction is handling (e.g. ldrb uses LDST8_ABS_LO12_NC, ldrh uses LDST16_ABS_LO12_NC).
A GOT relative version of these relocations also exists, the assembler will pickup the right one.
Control flow relocations
Operator    | Relocation name | Operation | Inst | Immediate | Check
------------+-----------------+-----------+------+-----------+----------
[implicit]  | TSTBR14         | S + A - P | tbz  | X[15:2]   | |X|≤2^15
            |                 |           | tbnz |           |
------------+-----------------+-----------+------+-----------+----------
[implicit]  | CONDBR19        | S + A - P | b.*  | X[20:2]   | |X|≤2^20
------------+-----------------+-----------+------+-----------+----------
[implicit]  | JUMP26          | S + A - P | b    | X[27:2]   | |X|≤2^27
------------+-----------------+-----------+------+-----------+----------
[implicit]  | CALL26          | S + A - P | bl   | X[27:2]   | |X|≤2^27
------------+-----------------+-----------+------+-----------+----------

Epilogue
I couldn't find an official documentation.
The tables above have been reconstructed from the GAS test case and the ARM document explaining the type of relocations available for AArch64 compliant ELFs.
The tables doesn't show all the relocations present in the ARM document, as most of them are complementary versions, picked up by the assembler automatically.
A section with examples would be great, but I don't have an ARM GAS.
In the future I may extend this answer to include examples of assembly listings and relocations dumps.


text:
Q: Identify and create a list of all the misspelled words in new column I would like to apply SpellChecker function to identify all misspelled words in each sentence, then create a list of those misspelled words in a new dataframe column.
For example, Input:

ColumnA

I tried many times to iddentify misspelled words

I trried many timees to identtify misspelled words

I tried maany timees to identify missspelled words

Desired Output:

ColumnA
ColumnB

I tried many times to iddentify misspelled words
[{iddentify}, {misspelled}]

I trried many timees to identtify misspelled words
[{trried}, {timees}, {identtify}]

I tried maany timees to identify missspelled words
[{maany}, {timees}, {missspelled}]

I have tried these code, but the result shows something like this (character-based checking instead of word-based checking):
(https://i.stack.imgur.com/vNKqH.png)
!pip install pyspellchecker
from spellchecker import SpellChecker
spell = SpellChecker()
df['ColumnB'] = [list(map((spell.unknown), word)) for word in df['ColumnA']]
df['ColumnB']

Requirement already satisfied: pyspellchecker in /opt/conda/lib/python3.9/site-packages (0.7.1)
0    [{c}, {h}, {}, {}, {f}, { }, {m}, {}, {d}, {},...
1    [{c}, {d}, {c}, { }, {}, {p}, {d}, {}, {t}, { ...
2    [{w}, {h}, {}, {n}, { }, {w}, {}, {l}, {l}, { ...
Name: ColumnB, Length: 3, dtype: object

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hibernate Search - StandardAnalyzer with empty stopwords via persistence.xml I've a question regarding the configuration of Hibernate Search via persistence.xml . The standard analyzer used for indexing and searching is the StandardAnalyzer. This analyzer has a list of english stopwords per default. I know that via constructor this stopword-list can be replaced with an own list (or EMPTY_SET). Unfortunately I didn't find such an option in the official documentation. The only thing I found is that it's possible to set a different analyzer via the hibernate.search.analyzer property. My question: is there an existing property to deactivate the english stopwords while using the StandardAnalyzer?

A: You could define your own subclass of StandardAnalyzer, pass the parameters you want to the super constructor, and set the hibernate.search.analyzer property to the fully qualified classname of your subclass. EDIT: As @AnarchoEnte replied, StandardAnalyzer is a final class, so you actually cannot do that.
But in my opinion, you'd be better off defining your own analyzer doing exactly what the standard analyzer does, but without stopwords:
@AnalyzerDef(
    name = "myDefault",
    tokenizer = @TokenizerDef(
        factory = org.apache.lucene.analysis.standard.StandardTokenizerFactory.class
    ),
    filters = {
        @TokenFilterDef(
            factory = org.apache.lucene.analysis.standard.StandardFilterFactory.class
        ),
        @TokenFilterDef(
            factory = org.apache.lucene.analysis.core.LowerCaseFilterFactory.class
        )
    }
)
public class MyEntity { // The annotation must be on an indexed entity, which one doesn't matter.
...
}

Then set it as default analyzer:
hibernate.search.analyzer = myDefault

This way, if you ever need to change something to the analyzer (add some filters, change the tokenizer, ...) you will only have to change that definition.


text:
Q: Planar eucliean bipartite matching with squared distances This is probably a really stupid question, but suppose I have two sets of points in the plane $X$ and $Y$ each with cardinality $|X| = |Y| = n$.  For any bipartite matching $M$ between $X$ and $Y$, let $c_1(M)$ denote the total "cost" of the matching $M$, in which we say that the cost between a pair $(x_i,y_j)$ is simply the Euclidean distance between $x_i$ and $y_j$.  Similarly let $c_2(M)$ denote the total cost of the matching $M$ where the cost between a pair $(x_i,y_j)$ is the square of the distance between $x_i$ and $y_j$.  Let $M_1$ and $M_2$ denote the optimal matchings with respect to cost functions $c_1$ and $c_2$ respectively.  My question is:  what are the point sets $X$ and $Y$ that maximize the ratio $c_1(M_2)/c_1(M_1)$?

A: The quotient can get as close as we please to $\sqrt{n}$.
Start by putting a red and a blue point distance $\sqrt{n}$ apart (let me use colors instead of "point in $X$"). Then put $n-1$ pairs of coinciding points (or extremely close if you don't want them to coincide), one red and one blue, as "stepping stones" between them, a unit distance apart, but along a large circular path.
With true distances, a pair of coinciding points of opposite color should always be matched to each other, so $c_1(M_1)=\sqrt{n}$. But with squared distances, the cost of that matching is $n$, so it will be just as good to use the stepping stones and pay for $n$ edges of cost 1 (and strictly better with a slight perturbation of the points).
Provided the stepping stones are arranged so that under squared distances no shortcut will pay, we get $c_1(M_2) = n$.
Clearly $\sqrt{n}$ is the best we can do. If we take the distance $c_1(M_2)$ and chop it into $n$ pieces, then the sum of the squares of the pieces is minimized when they are equal, therefore $$\frac{c_1(M_2)^2}n\leq c_2(M_2) \leq c_2(M_1)\leq c_1(M_1)^2.$$


text:
Q: Could not initialize class org.jetbrains.kotlin.gradle.internal.KotlinSourceSetProviderImplKt by running gradle run via cmd I have a question about gradle:
I Have the following code in Kotlin (just started to learn it):
@file:JvmName("KtlTest")

fun main(args: Array<String>)
{
    println("Hello Kotlin !")
}

and the following build.gradle:
plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.2.51'
}

group 'KGroupId'
version '1.0-SNAPSHOT'
ext.kotlin_version = '{{ site.data.releases.latest.version }}'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    testImplementation 'io.rest-assured:rest-assured:4.3.1'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

task runExample(type: JavaExec) {
    main = 'KtlTest'
    classpath = sourceSets.main.runtimeClasspath
}

If I run this via IntelliJIDEA by clicking green triangle near task - it runs ok.
But, if I run it via other -> runExample in Gradle tab in IntelliJIDEA I got this error:

Also, I got this error if I try to run it via CMD:

Could someone help me figure out what the problem is?


text:
Q: Is every minimal hypersurface in $S^n$ algebraic? Let $S^n$ be the round n-sphere. Wu-yi Hsiang asked in his paper "Remarks on closed minimal submanifolds in the standard riemannian m-sphere" (1967) the follow question

Is every minimal hypersurface (i.e. codimensional one) in $S^n$ algebraic (i.e. given by intersecting the zero set in $R^{n+1}$ of some homogenous polynomial in n+1 variables with $S^n$) ?

e.g. the Lawson surface in $S^3$ is given by the imaginary part of $(x_1+ix_2)^m(x_3+ix_4)^l$.
What is the current status of this problem?

A: The answer to this question is 'no' for most minimal surfaces of revolution in the $3$-sphere.
Consider surfaces in $S^3 = \{\,(z,w)\in\mathbb{C}^2\,|\,|z|^2+|w|^2=1\,\}$ that are invariant under the circle action
$$
\mathrm{e}^{i\theta}\cdot(z,w) = \bigl(\mathrm{e}^{ip\theta}\,z,\,\mathrm{e}^{iq\theta}\,w\,\bigr)
$$
where $p\ge q\ge 0$ are relatively prime integers.  The ring of polynomials invariant under this circle action is generated by $z\bar z$ and $w\bar w$ (of degree $2$) and the real and imaginary parts of $\zeta = {\bar z}^q\,w^p$ (of degree $p{+}q$).   These are subject to a single relation, $\zeta\bar\zeta = (z\bar z)^q(w\bar w)^p$ of degree $2(p{+}q)$.  Setting $u = z\bar z-w\bar w$, the mapping $(u,\zeta):S^3\to \mathbb{R}\times\mathbb{C}$ embeds the space of orbits in $S^3$ (where $z\bar z+ w\bar w = 1$) as the algebraic (orbifold) variety $(1{+}u)^q(1{-}u)^p-2^{p+q}\,\zeta\bar\zeta=0$.
A smooth surface in $S^3$ that is invariant under this action and that avoids the circles $z=0$ and $w=0$ can be parametrized in the form
$$
\bigl(z(\theta,s),w(\theta,s)\bigr) = \left(
\mathrm{e}^{i(p\theta-q^*\phi(s))}
\left(\tfrac12(1+u(s)\right)^{1/2},
\,
\mathrm{e}^{i(q\theta+p^*\phi(s))}
\left(\tfrac12(1-u(s)\right)^{1/2}
 \right)
$$
for some functions $\phi(s)$, defined modulo $2\pi$, and $u(s)$,  satisfying $|u(s)|<1$.  In this formula, $q^* = q/(p^2{+}q^2)$ and $p^*=p/(p^2{+}q^2)$.
Calculation shows that such a surface is minimal if and only if the curve $\bigl(u(s),\phi(s)\bigr)$ is, up to reparametrization, a geodesic for the metric
$$
g = \frac{\bigl((p^2{+}q^2)+(p^2{-}q^2)u\bigr)}{2(1-u^2)}\,\mathrm{d}u^2 + (1-u^2)\,\mathrm{d}\phi^2.
$$
Moreover, the parametrized surface will be an algebraic surface if and only if $u(s)$ and $v(s) = \tan\phi(s)$ are algebraically related, since, on such a surface, we will have
$$
\zeta(s) = \mathrm{e}^{i\phi(s)}
\left(\tfrac12(1{+}u(s)\right)^{q/2}
\left(\tfrac12(1{-}u(s)\right)^{p/2}
= \frac{1{+}i\,v(s)}{\sqrt{1{+}v(s)^2}}
\left(\tfrac12(1{+}u(s)\right)^{q/2}
\left(\tfrac12(1{-}u(s)\right)^{p/2}
$$
When $p\ge q>0$, the metric $g$ is a smooth metric on an orbifold of rotation (the 'poles' of the rotation are the orbifold points, of orders $p$ and $q$ respectively), with Gauss curvature
$$
K = \frac{2p^2+2q^2+(p^2{-}q^2)\,u}{(\,p^2+q^2+(p^2{-}q^2)\,u\,)^2} > 0.
$$
(In the special case $(p,q)=(1,0)$, the singularity at the 'pole' $u=-1$ is not an orbifold point, but the metric is, of course, still smooth on the disk $u>-1$.)
Making use of the Clairaut first integral for metrics of revolution, one finds that a geodesic that does not have $\phi$ constant (and hence, does not pass through the orbifold 'poles') and does not have $u$ constant must satisfy a relation of the form
$$
\frac{m}{1-u^2}\sqrt{\frac{2\bigl((p^2{+}q^2)+(p^2{-}q^2)u\bigr)}{\bigl(1-u^2-4m^2\bigr)}}\,\mathrm{d}u -\frac{\mathrm{d}v}{1+v^2}\, = 0\tag1
$$
for some constant $m$ with $0<|m|<\tfrac12$.
Now, it is not hard to show, using Liouville's Theorem, that the first term in $(1)$ is not the differential of any elementary function of $u$ when $p^2{-}q^2>0$.  (Obviously, it is the differential of an elementary function when $p^2{-}q^2 = 0$, but, otherwise, it is the differential of a nontrivial linear combination of incomplete elliptic integrals of the third kind in Legendre's terminology.)  Hence, $u$ and $v = \tan\phi$ cannot be algebraically related, since expressing $v$, even locally, as an algebraic function of $u$ would express the first term in $(1)$ as the differential of $\tan^{-1}(v)$, which would be an elementary function of $u$.  (For those unfamiliar with Liouville's Theorem and the theory of integration in terms of elementary functions, these notes by Brian Conrad give a very useful and clear introduction.)
Meanwhile, the set of values of $m$ satisfying $0< |m| < \tfrac12$ for which the geodesic described by the above relation closes smoothly is dense in the interval $(-\tfrac12,\tfrac12)$, since the integral of the first term in $(1)$ over the interval $u^2<1{-}4m^2$ is not constant in $m$, as it is an odd function of $m$ that is not equal to zero when $m$ is not zero.
Hence there exist such $m$ that yield a closed geodesic on the orbifold of rotation, which lifts to a closed minimal surface in $S^3$ that is not algebraic.
Remark 1:  There may be similar arguments that can be made for $S^n$ ($n>3$) using an appropriate symmetry reduction via a group action of cohomogeneity $2$, but not all of the induced metrics on the orbit spaces have a continuous symmetry, and hence the Clairaut integral does not always exist, which was essential in the above argument (so that an appeal could be made to Liouville's Theorem).
Remark 2: There is an interesting example associated to this question:  If, instead of the standard metric on $S^3$ of constant sectional curvature $+1$, one considers the 'squashed' (but still smooth and positive definite) metric
$$
G = \mathrm{d}z\,\mathrm{d}\bar z + \mathrm{d}w\,\mathrm{d}\bar w - (\mathrm{d}f)^2
$$
where $f = \tfrac14\sqrt{1+8z\bar z}$ (a smooth function on $S^3$) and sets $(p,q)=(3,1)$, then the metric on the (orbifold) orbit space whose geodesics describe minimal surfaces in this metric that are invariant under the circle action turns out to be the metric on the Tannery pear orbifold (up to a constant multiple).  In particular, not only are all the geodesics closed in Tannery's pear, but they are all, in addition, algebraic.  Hence, the corresponding minimal tori of revolution in this metric are algebraic as well (using the standard algebraic structure on $S^3$).


text:
Q: Flask-Admin GeoAlchemy2 example doesn't show a map I'm trying to run this example about how to use Flask-Admin displaying maps: https://github.com/flask-admin/flask-admin/tree/master/examples/geo_alchemy.
In README.rst, there's this instruction:

*You will notice that the maps are not rendered. To see them, you will have to register for a free account at Mapbox and set the MAPBOX_MAP_ID and MAPBOX_ACCESS_TOKEN config variables accordingly.

I already have a valid MAPBOX_ACCESS_TOKEN, and I went to MapBox to look for a MAPBOX_MAP_ID. There I read that MAP_ID was deprecated, and now I'll have to obtain a tileset ID, and it's described as a label composed by <my_mapbox_user_name>.the_tileset_ID itself.
So I located the code as they described in the instructions (in my case, mapbox-streets-v8) and fulfilled the config.py parameters:
MAPBOX_MAP_ID = '<my_mapbox_user_name>.mapbox-streets-v8'
MAPBOX_ACCESS_TOKEN = 'pk.eyJ1...'

However, I couldn't see any map displayed or any error message.
How can I fix it?

A: I think there is a small bug in file Lib\site-packages\flask_admin\static\admin\js\form.js. The original URL generated to get a tile is:
https://api.mapbox.com/styles/v1/mapbox/<MAPBOX_MAP_ID parameter>/tiles/12/2258/2457?access_token=<MAPBOX_ACCESS_TOKEN parameter>

However, the correct one is:
https://api.mapbox.com/styles/v1/<MAPBOX_MAP_ID parameter>/tiles/12/2258/2457?access_token=<MAPBOX_ACCESS_TOKEN parameter>

That is, I had to remove the mapbox word from the URL.
To do that I made some changes in form.js file:
      //var mapboxUrl = 'https://api.mapbox.com/styles/v1/mapbox/'+window.MAPBOX_MAP_ID+'/tiles/{z}/{x}/{y}?access_token='+window.MAPBOX_ACCESS_TOKEN
      var mapboxUrl = 'https://api.mapbox.com/styles/v1/'+window.MAPBOX_MAP_ID+'/tiles/{z}/{x}/{y}?access_token='+window.MAPBOX_ACCESS_TOKEN

Then, it's working now:


text:
Q: Mainframe access for test automation through Java code Is there any way, we can connect mainframe through java code and can see the screen content in console. Also we can send the option as input and go further in mainframe screens. I need this basically for test automation purpose.

A: I haven't used the Robot framework but I believe it will do what you want.  Its not Java but uses Python; should fit the bill based on you question.
https://github.com/Altran-PT-GDC/Robot-Framework-Mainframe-3270-Library

A: Rational Functional Tester with its "Extension for Terminal-based Applications" will do this quite well. See here for more information:
https://www.ibm.com/support/knowledgecenter/SSJMXE_10.0.1/com.ibm.test.terminal.docs/topics/cxmlrft0001.html
You can use its Java APIs (called the Host Access Class Library, or HACL for short) if you want to do anything particularly fancy, but "out of the box" it's a full test automation suite for terminal-based user interfaces. (Terminal-based UIs are available in a variety of systems, including but not only mainframes. Apple's macOS offers a terminal-based UI, for example. Mainframes provide a variety of UIs, including, but not only, classic terminal-based UIs. RFT's Extension for Terminal-based Applications is able to test practically every terminal-based UI across all systems that offer them.)


text:
Q: Error on migration to non-deprecated ldap functions I'm changing deprecated ldap functions to non-deprecated functions. But I am having problems with ldap_sasl_bind_s. It returns error code 49, which means invalid credentials. But I'm sure that the credentials are valid. Otherwise I added
TLS_REQCERT never

TLSVerifyClient never

to /etc/openldap/ldap.conf. Still I get the error.
ldap_simple_bind_s(q->ld, binddn, creds.bv_val);  //works well

ldap_sasl_bind_s(q->ld, binddn, LDAP_SASL_SIMPLE , &creds, NULL, NULL, NULL); //returns ldap error code 49 but continues working

The main problem is that : When i m using ldap_sasl_bind_s,  it doesnt bind all attrbiutes, that i got in my ldap architecture. Also when i m searching an existing attribute, it returns NOSUCH error.
Any help would be appreciated.

A: Basic C programming covering the uber-basics, although something tells me you read this stuff already: (And I cannot tell from your question if your application is external or you are moving deprecated functions from the openldap? sources)
Have you read this document which indicates to me that ldap_simple_bind and ldap_sasl_bind_s will work the same if char *LDAP_SASL_SIMPLE = 0;


text:
Q: Dart compare two strings return false Im new to dart and have a problem during building my Flutter application.
I have a firestore database as a backend and im getting data from there.
When i want to compare part of the data called status with the text 'CREATED', using == comparator, dart will return false.
Can someone explain why and how to check it properly?
rideObject is a Map

Update:
Here is the function that has the condition in it:
Widget _getPage() {
 if (rideObject == null) {
      return OrderRidePage(
          address: address,
          ridesReference: reference,
          setRideReference: this._setRideReference);
    } else {
      print(rideObject['status']);
      if (rideObject['status'] == "CREATED") {
        return LoadingPage(
            removeRideReference: this._removeRideReference,
            rideReference: rideReference);
      } else {
        return RidePage(
            address: address,
            ridesReference: reference,
            setRideReference: _setRideReference);
      }
    }
  }

The print statement returns to output:

I/flutter (15469): CREATED

Here you can see the structure of the rideObject

Funnily enough, the rideObject["status"] is String type as shown in here in console:
rideObject["status"] is String
true
"CREATED" is String
true
rideObject["status"]
"CREATED"
rideObject["status"] == "CREATED"
false

A: The String you got from your server is probably encoded and contains special character which you can't see, try to compare the hex values of both of the strings, and then replace all the special characters from the String returned by the server.
Using this, you can see the actual non visible difference between the two strings:
var text1 = utf8.encode(hardcodedText).toString();
var text2 = utf8.encode(textFromServer).toString();

A: If both are really strings, you can use "compareTo" which will return 0 if both are equal.
if(str1.compareTo(str2)==0){
}

It is explained here:
https://www.tutorialspoint.com/dart_programming/dart_programming_string_compareto_method.htm

A: I don't have a particular solution to this, but I updated to latest Flutter version that came up today, moved the "CREATED" string into constant and resolved an unrelated warning for another part of the application, and it suddenly started to work.

A: The answer for this problem is in the documentation of flutter:
https://api.flutter.dev/flutter/dart-core/String/compareTo.html
you can do:
(var.compareTo('WORD') == 0)

are equivalent
.compareTo()

Returns a negative value if is ordered before, a positive value if is ordered after, or zero if and are equivalent.thisother

A: Building off @yonez's answer, the encoding may be different after a string has been passed through a server.
Instead of: String.fromCharCodes(data)
Try using: utf8.decode(data)


text:
Q: I am trying to export data from different tables. I have pulled same headers from the tables I am trying to export data from different tables. I have pulled same headers from the tables.
select locationid, qty from a,
select locationid, qty from b,
select locationid, qty from c
Ideally i would like a query to see my data as
 locationid qtyA qtyB qtyc
Could someone help me with SQL Query?

A: Can you try the following queries?
First in ANSI-89:
SELECT
a.locationid as locationIdA, a.qty as qtryA,
b.locationid as locationIdB, b.qty as qtryB,
c.locationid as locationIdC, c.qty as qtryC
FROM
a, b, c

In case you need to filter by locationId (joined):
SELECT
a.locationid as locationIdA, a.qty as qtryA,
b.locationid as locationIdB, b.qty as qtryB,
c.locationid as locationIdC, c.qty as qtryC
FROM
a, b, c
WHERE
a.locationid=b.locationid
AND
b.locationid=c.locationid

Also you could try with ANSI-92:
SELECT
a.locationid as locationIdA, a.qty as qtryA,
b.locationid as locationIdB, b.qty as qtryB,
c.locationid as locationIdC, c.qty as qtryC
FROM
a
INNER JOIN b
ON
a.locationid=b.locationid
INNER JOIN c
ON
a.locationid=c.locationid


text:
Q: Springboot 2. hikaricp and Microsoft SQL Server We have services written in Springboot 2 and we are using SQL Server as backend database and intermittently we are receiving below error
Hikaricp is 3.4.1 [compile]
Microsoft SQL Server 2014
Springboot 2.2.1
Failed to validate connection ConnectionID:XXXX(The connection is closed.). Possibly consider using a shorter maxLifetime value.
We have minimumIdle and Maximum pool size same as suggested by Hikari.
maximum-pool-size: 25
connection-timeout: 5000
idle-timeout: 0
max-lifetime: 300000
allow-pool-suspension: true
register-mbeans: true
leak-detection-threshold: 60000

Please suggest if we need to make MinimumIdle as 0 for Microsoft SQL Server ?
Will it cause any performance impacts ?


text:
Q: Why won't Exchange 6.5 let me change to native mode? I am running Exchange Server 6.5 on Windows Server 2003.
I am building a new server running Server 2008 R2 and Exchange Server 2007.  The Exchange setup says that it can't proceed until the old Exchange server is running in "native" mode.
I run Exchange System Manager as directed, but when I reach the property sheet that tells me I am running "Mixed Mode (can support pre-Exchange 2000 servers)", the button that says "Change Mode" is grayed out.
I am logged in as the domain administrator.
My only guess for this is that Exchange thinks I still have an older server.  I used to have an older server many years ago, but I expunged it quite completely, I thought.
So why is this button grayed out?
Thanks

A: First problem is that Exchange 2007 isn't supported on Windows 2008 R2, yet.

A: From here:
Method 1: Manually delete the Site Replication Service from Exchange System Manager
You may be able to resolve this issue if you delete the Site Replication Service (SRS). For additional information about how to manually delete the Site Replication Service from Exchange System Manager, click the following article number to view the article in the Microsoft Knowledge Base:
329606  (http://support.microsoft.com/kb/329606/ ) Cannot use Exchange System Manager to delete SRS from remote computer
Back to the top
Method 2: Use the LDP tool (Ldp.exe) to edit attributes
If you cannot remove the SRS, use the LDP tool to remove the following attributes:
* msExchLegacyAccount
* msExchLegacyDomain
* msExchEncryptedPassword

Additionally, use the LDP tool to edit the msExchAdminGroupMode attribute by removing its value in the Edit Attribute box.
To edit these attributes, follow these steps.
Warning If you use the ADSI Edit snap-in, the LDP utility, or any other LDAP version 3 client, and you incorrectly modify the attributes of Active Directory objects, you can cause serious problems. These problems may require you to reinstall Microsoft Windows 2000 Server, Microsoft Windows Server 2003, Microsoft Exchange 2000 Server, Microsoft Exchange Server 2003, or both Windows and Exchange. Microsoft cannot guarantee that problems that occur if you incorrectly modify Active Directory object attributes can be solved. Modify these attributes at your own risk.

*

*Start the LDP tool.

*Click Connection, click Connect, and then click OK.

*Click Connection, click Bind, type the administrator's password in the Password box, and then click OK.

*Expand the CN=Configuration, DC=Domain, DC=com container.

*Expand CN=Services, and then expand CN=Microsoft Exchange.

*Expand CN=Organization, and then expand CN=Administrative Groups.

*Right-click the administrative group that you want in the left pane, and then click Modify.

*Make sure that the following text appears in the title bar of the Modify window:
  CN=Administrative Group,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=Domain,DC=com

*Type msExchLegacyAccount in the Attribute box, click Remove, and then click Enter.

*Click Run to remove the attribute.

*Repeat steps 8 through 10 to delete the following attributes:

*

*msExchLegacyDomain

*msExchEncryptedPassword

*Make sure that the following text appears in the title bar of the Modify window:
CN=Administrative Group,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=Domain,DC=com

*In the Attribute box, type msExchAdminGroupMode, and then click Replace.

*Type 0 in the Value box, and then click Enter.

*Click Run to reset the administrative group.

*Quit the LDP tool.

Back to the top
Method 3: Remove the SRS from Active Directory
To remove the SRS from Active Directory, follow these steps:

*

*Start the ADSI Edit tool.

*Expand Configuration Container, and then expand CN=Configuration, DC=Domain, DC=com.

*Expand CN=Services, and then expand CN=Microsoft Exchange.

*Expand CN=Organization, and then expand CN=Administrative Groups.

*Expand CN=Servers, and then expand CN=Server.

*Right-click CN=Microsoft DSA, and then click Delete.

Back to the top
Method 4: Edit the msExchMixedMode attribute
To change the value of the msExchMixedMode attribute to False, follow these steps:

*

*Start the ADSI Edit tool.

*Expand Configuration Container, and then expand CN=Configuration, DC=Domain, DC=com.

*Expand CN=Services, and then expand CN=Microsoft Exchange.

*Right-click CN=Organization, and then click Properties.

*On the Attributes tab in the Select which properties to view box, click Both.

*In the Select a property to view box, click msExchMixedMode.

*Click Clear.

*In the Edit Attribute box, type False.

*Click Set, and then click OK.

*Quit the ADSI Edit tool.


text:
Q: How to add action into the drop-down menu in django I've got a model like below:
class UserProfile(models.Model):
    username = models.CharField(max_length=16)
    phone_number = PhoneNumberField(verbose_name='Mobile Number')
    register_date = models.DateTimeField('Registration Date', auto_now=True)
    Email_addr = models.EmailField()

The admin.py is like this:
class UserProfileAdmin(admin.ModelAdmin):
    list_filter = ['username', 'phone_number', 'register_date', 'Email_addr']
    search_fields = ['username']
    list_display = ['username', 'phone_number', 'Email_addr']
    actions = ['some_actions']

As you know, in the dropdown menu there is one built-in action called Delete action.
How could I add another action to this dropdown menu like edit and how to write the action for this embedded action?
Thanks in advance


text:
Q: Convert Columns into rows DataFrame I have the following DataFrame:

Name
A
B
C
D
E

BTU
2
3
0
9
7

BTP
1
2
7
9
0

And I want this:

Name
letter
Value

BTU
A
2

BTU
B
3

BTU
C
0

BTU
D
9

BTU
E
7

BTP
A
1

BTP
B
2

BTP
C
7

BTP
D
9

BTP
E
0

How can I do it?

A: You can do this with melt:
pd.melt(df, id_vars=['Name'], value_vars=['A', 'B', 'C', 'D', 'E'], var_name='letter', value_name='Value').sort_values(by='Name', ascending=False)

Result:

Name
letter
Value

0
BTU
A
2

2
BTU
B
3

4
BTU
C
0

6
BTU
D
9

8
BTU
E
7

1
BTP
A
1

3
BTP
B
2

5
BTP
C
7

7
BTP
D
9

9
BTP
E
0


text:
Q: Calculating zonal statistics as table for all attributes (columns) in raster using ArcGIS Desktop I have a raster that has multiple columns in the attribute table that I can symbolize. I would like to calculate zonal statistics as a table for each of the columns in the raster attribute table individually.
How do I do this?
Here is an example of the raster attribute table.

OID
Value
Count
slodegradd
aws025wta

0
538236
7729
0.5
0.3

1
538237
21
0.4
0.2

2
538239
82
0.5
0.3

A: I was able to accomplish this by using the 'Lookup' and then 'Zonal Statistics as Table'.


text:
Q: SQL (Postgres): ON vs WHERE for better performance I have a person and a task table. The task table is much bigger and contains millions of rows.
With the following (fast) SQL statement I get a list of tasks for a given person:
select p.name, t.name
from person p
join task t on t.person_id = p.id
where p.id = 1234

Unfortunately, I need to work with the following (equivalent but slow) SQL statement:
select p.name, t.name
from person p
join task t on 1 = 1
where t.id in (
  select t.id
  from task t
  where t.person_id = p.id )
and p.id = 1234

Why does the second statement take about 20 seconds, while the first only runs for less than a second. Can I use an index or something to speed up the second statement as well? I cannot change the SQL statement.

A: select p.name, t.name
from person p
join task t on t.person_id = p.id
where p.id = 1234

*

*This is INNER JOIN

*It uses proper join conditions and p.id = 1234 further reduces the cost of the query

..
select p.name, t.name
from person p
join task t on 1 = 1
where t.id in (
  select t.id
  from task t
  where t.person_id = p.id )
and p.id = 1234

*

*This is CROSS JOIN which will generate m*n records

*Here, p.id = 1234 is used but still number of records will be (number of records satisfying p.id = 1234) * (Number of records in Tasks table)

*IN sub-query is corelated query which takes much time as query will be executed once for each record.

*Each expression/statements used in this query is costly. Hence, It is taking time.


text:
Q: SQL Server date Format user dependent? I have a query with hard coded dates, in this format
startdate >= '2012-11-03' AND enddate <= '2012-11-30 23:59'

My database date format is 'mdy', however I'm sure it will accept yyyy-mm-dd as its the universal date structure.
When I try run this query in SSMS on my target DB connected with a specific database user (userX) I get an error about the date formats

Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

However, when I run the exact query connected as the SA user, the query executes..
Why is this? I have given userX full dbo permissions (sysadmin etc) and still get the error?

A: If you need to specify datetimes using strings, you should use a safe, language-independent format.
In SQL Server, that's the ISO-8601 format (slightly adapted), and it supports basically two safe formats for DATETIME that always work - regardless of your language, regional and dateformat settings:
YYYYMMDD              (e.g. 20121231  for 31st of December 2012)  if you need date only

YYYY-MM-DDTHH:mm:ss   (e.g. 2012-12-31T21:05:00 for 31st of December 2012, 9:05pm)

Note:

*

*the first date-only format has no dashes or delimiters!

*the second format has dashes for the date (can be omitted, too), and there's a fixed T as delimiter between the date and the time portion of the string
Update: as per your last comment (on the different default languages for the two users) - try this:
-- this is how your `SA` interprets the string as datetime....
SET LANGUAGE english
SELECT CAST('2012-11-30 23:59' AS DATETIME)

Works just fine...
-- this is how your British user interprets teh string as datetime
SET LANGUAGE british
SELECT CAST('2012-11-30 23:59' AS DATETIME)

Msg 242, Level 16, State 3, Line 7
  The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

This tries to interpret the string as 11th of the 30th month of 2012 and obviously, that fails....

A: consider using

startdate >= '2012-11-03' AND enddate < '2012-12-01'

instead


text:
Q: CrossPlatform Cuepoint Event for HTML5 Video Edittted to ad clarity
I am looking to create an HTML5 Video playback that triggers events at specific regularly timed cue-points. For example, I'd like an event to fire every second during video playback that checks the contents of a textbox (i.e. at second1 textbox contained; at second2 textbox contained). The 'tricky' part is that I need it to work across all major platforms/browsers, and that includes IPhones and IPads.
IPhones particularly seem to be a problem in that no matter the player, the setting, the hack I've tried - when a video starts playing, the browser goes to the background and the video is played in a full-screen container (Quicktime?). When the video stops playing and control is back with the browser, I see that the cuepoint events fired, but that's of no use if the textbox is unreachable during video playback!
I am very familiar with FlowPlayer and have already done a bunch of work to ensure it works for playback across most relevant platforms; the cuepoint feature of its API seems to be exactly what we need BUT there's a warning/restriction specific to it:

Be aware that cuepoints are subject to device restrictions regarding the HTML5 video API. On devices which do not support inline video
  because they delegate playback to a system component (e.g. QuickTime
  on iPhone) the effect of cuepoints is next to none in real world
  setups

Has anyone worked with Flowplayer cuepoints OR alternate tech on iPhones/iPads? Obviously, if I can maintain one code base that would be preferrable to having multiple platform-specific versions.

A: Here is a simple controller for the video element which tracks the timeupdate event fired by the video element to trigger callback functions at the specified timecodes.
It allows you to attach multiple callbacks for the same timecode.
The timeupdate event is fired at different rates on different devices, because of this there is a limitation in that cuepoints can only be attached at integer values so at 5 seconds not 5.5, you can potentially remove this but then there is a risk that the cuepoints will not be triggered
/**
 * Function which allows you to register cuepoints to trigger callbacks
 * at specific timecodes
 * @param {HTMLElement} video_el The video element you want to track
 */
var VideoController = function(video_el){
    /**
     * The video element this controller is for
     * @type {HTMLElement}
     */
    this.element = video_el; //

    /**
     * Object containing all the cuepoints
     * @type {Object}
     */
    this.cuepoints = {};

    /**
     * The last processed_timecode so we dont fire events more than once
     * @type {Number}
     */
    this.processed_timecode = undefined;

    /**
     * Allows you to trigger a callback at a specific timecode
     * @param {Number}   timecode The timecode you want to trigger your callback
     * @param {Function} callback Your callback function
     */
    this.addCuepoint = function(timecode, callback){
        //
        timecode = Math.floor(timecode);

        //
        if(this.cuepoints[timecode] === undefined){
            this.cuepoints[timecode] = [];
        }

        this.cuepoints[timecode].push(callback);

        return this;
    }

    /**
     * Internal method to track the videos current timecode and to trigger
     * the cuepoints when neccesary
     * @param  {[type]} e A timeupdate event from the video
     */
    this.timeupdate = function(e){

        var timecode = Math.floor(e.target.currentTime);

        // check to see if there is a callback registered for this timecode
        if(this.cuepoints.hasOwnProperty(timecode) && this.cuepoints[timecode] !== undefined && this.processed_timecode !== timecode){

            //if there is it loops through the array of callbacks and triggers them
            for(var i = 0,l=this.cuepoints[timecode].length;i<l;i++){
                this.cuepoints[timecode][i]();
            }

        }

        //updates the processed_timecode so we do not fire these callbacks again
        this.processed_timecode = timecode;

    }.bind(this);

    // add addEventListener to the video element to track the video timecode
    this.element.addEventListener('timeupdate', this.timeupdate);

    return this;
}

var video = document.getElementById('myVideoElement');
var video_controller = new VideoController(video);

video_controller.addCuepoint(2,function(){
    console.log('do something at 2 seconds');
});
video_controller.addCuepoint(2,function(){
    console.log('do something else at 2 seconds');
});

A: I've adapted @Irfan 's answer above to use requestAnimationFrame instead of relying on the timeupdate event.
This will allow for a more granular triggering of events on a half second etc, just adjust the .tofixed(1) as appropriate.
This will not likely help you with the iPhones web video restrictions, but for other use cases it should be helpful to anyone else who needs precise triggering or events based on video time.
// Request Animation Frame Shim
// Source: https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            function( callback ){
                window.setTimeout(callback, 1000 / 60);
            };
})();

var VideoController = function(video_el){
    this.element = video_el;
    this.cuepoints = {};
    this.processed_timecode = undefined;
    var self = this;
    this.addCuepoint = function(timecode, callback){
        var timecode = timecode.toFixed(1);
        if(this.cuepoints[timecode] === undefined){
            this.cuepoints[timecode] = [];
        }
        this.cuepoints[timecode].push(callback);
        return this;
    }
    this.rafUpdate = function(timestamp){
        var timecode = video_el.currentTime.toFixed(1);
        if(!video_el.duration){
            requestAnimFrame(self.rafUpdate);
        }else if( timecode < video_el.duration ){
            requestAnimFrame(self.rafUpdate);
        }
        if( self.cuepoints.hasOwnProperty(timecode) && self.cuepoints[timecode] !== undefined && self.processed_timecode !== timecode ){
            for(var i = 0,l=self.cuepoints[timecode].length;i<l;i++){
                self.cuepoints[timecode][i]();
            }
        }
        self.processed_timecode = timecode;
    }
    requestAnimFrame( this.rafUpdate ); // keeps better time than video.timeupdate
    return this;
}

var video = document.getElementById('myvideo');
globalVars['video'] = video;
var video_controller = new VideoController(globalVars['video']);
video_controller.addCuepoint(10.2,function(){
    endframe.play();
});


text:
Q: Why is this KMP code showing a runtime error? Is returning a vector from the function is creating any problem? or is it just some basic syntax problem?
It is  just the sample code from CLRS. The computePrefix function computes values for proper prefix of the given pattern and matches the values in main function.
Getting a SIGSEGV error to be more precise. Your kind advice will really be helpful.
Thank you.
#include <bits/stdc++.h>

using namespace std;

int main()
{
    string text, pattern;
    vector<int> computePrefixFunction(string p);
    cin >> text;
    cin >> pattern;
    int n = text.length();
    int m = pattern.length();
    vector<int> pi = computePrefixFunction(pattern);
    int q = -1;
    for(int i = 0; i < n; ++i)
    {
        while(q > -1 && pattern[q+1] != text[i])
            q = pi[q];
        if(pattern[q+1] == text[i])
            q = q + 1;
        if(q == (m-1))
        {
            cout << "Pattern occurs from position: " << q - m + 1 << '\n';
            q = pi[q];
        }
    }
    return 0;
}

vector<int> computePrefixFunction(string p)
{
    int m = p.length();
    vector<int> pi;
    pi[0] = -1;
    int k = -1;
    for(int q = 0; q < m; ++q)
    {
        while(k > -1 && p[k+1] != p[q])
            k = pi[k];
        if(p[k+1] == p[q])
            k = k + 1;
        pi[q] = k;
    }
    return pi;
}

A: In order to use a vector, do push_back to add elements to it. If you just initialize it without a size like you do on the second line of computePrefixFunction, trying to access pi[0] or pi[q] will give you a runtime error. Instead, do pi.push_back(value).


text:
Q: Visudo rule not working for service restart I want to be able to restart a service in Ubuntu without being root.

$ whoami

ubuntu

Then I did:

sudo visudo

and I added a line:
ubuntu ALL = NOPASSWD: /usr/sbin/service javaspringapi restart

And saved the file. Resulting sudoers file:

sudo cat /etc/sudoers

#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

ubuntu ALL = NOPASSWD: /usr/sbin/service javaspringapi restart

Now when I try to run the command:

/usr/sbin/service javaspringapi restart

I still get:
 ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
 Authentication is required to restart 'javaspringapi.service'.
 Authenticating as: Ubuntu (ubuntu)
 Password:

A: The sudoers file is referenced only if you run sudo (hence the name).
So you should be able to restart the service with
sudo /usr/sbin/service javaspringapi restart
without being prompted for password as this is what you have configured.


text:
Q: Actuarial theory of interest question with effective discount I have spent several hours trying to solve this problem. $A$ and $B$ both open up new bank accounts at time $0$. The principle for $A$ (the amount deposited at $t=0$) is $100$. The principle of $B$ is $50$ (the amount deposited at $t=0$). Each account earns an annual discount rate of $d$. The amount of interest earned in $A$ during the 11th period is equal to $X$. The amount of interest earned in $B$ during the 17th period is equal to $X$. Calculate X.
Given that we are dealing with effective discount rate, for $A$ and $B$ we have $a(t)^{-1} = (1-d)^t$ clearly the amount of interest earned is $(1-d)^t$ for both $A$ and $B$. This means that $(1-d)^{11}=(1-d)^{17}$
Is this the correct set up? if not why? Given that the principles are $100, 50$ we have:
$\frac{100}{(1-d)^{11}}=\frac{50}{(1-d)^{17}}$ that is if we are setting the amount functions equal to each other during the $17$ and $11$ period. I thought this would translate to $50(1-d)^{11} = 100(1-d)^{17}$ then substituting $X$ for $(1-d)^{17}$ and $(1-d)^{11}$ we have something that makes no sense $50X=100X$ which gives $X=0$ after solving. If I don't substitute for $X$ I have $50(1-d)^{11}=100(1-d)^{17} \to 50=100(1-d)^6$ which translates to $\frac{1}{2}=(1-d)^{6}$ which gives a decimal less than one. The answer is $38.88$ I have no idea where I am going wrong. What am I missing? Am I even any where close on my thought processes?

A: The amount of interest earned in A during the 11th period is equal to $100\cdot (q^{11}-q^{10})$, where $q=1+i$ and $i$ is the interest. Equivalently for $B$. Thus the equation is
$$100\cdot (q^{11}-q^{10})=50\cdot (q^{17}-q^{16})$$
Dividing the equation by $50\cdot q^{10}$.
$$2\cdot (q-1)=(q^{7}-q^{6})$$
The (approximate) solution is $q=1.12246$
Thus $X=50\cdot (1.12246^{17}-1.12246^{16})=38.87749...\approx 38.88$


text:
Q: Google Maps API Sea Routes i searched enough and didn't find any way to remove the sea routes from a port to another, what featureType should i use on map options?

A: This seems to remove ferry lines; are those your concern?
[
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [
      { "visibility": "off" }
    ]
  }
]

It also removes other "transit lines" on the ground. which may be undesirable.


text:
Q: SVG stroke inside fill I'm making svg animation and i have to end up with stroke inside fill or as just one line without that messy transformation. I'm using stroke-dasharray and stroke-dashoffset to animate and also change fill from rgba(0, 0, 0, 0) to color
My question is:
Can I force stroke to appear inside of shape?


text:
Q: Best Way to copy data from Kernel Driver to user space driver I am having a kernel driver which is currently reading data from a sensor.
Now I have to  write a user space application which will call kernel's sensor_read() API and send data to cloud.
How can I expose kernel's sensor_read() call to user space and read this data from user space? Data is about 10 bytes.

A:
How can I expose kernel's sensor_read() call to user space and read this data from user space?

Most likely you should use IIO kernel framework, as it's specifically designed for writing sensor drivers. IIO exposes necessary files for your driver (in /sys/bus/iio/ and /dev/iio*). You can read() those files, or poll() them (to handle interrupts).
Official documentation is available here. You can also use some existing drivers as a reference, look here: drivers/iio/ .
Before IIO framework was introduced, it was common to provide sysfs files for drivers manually. So if you use old enough kernel, that should be the way to write the driver: handle your bus (like I2C) and sysfs files manually. But still, the best way is to use new kernel and IIO.

I am working on a Gyro + accel sensor. Linux driver will be sending events of type EV_MSC for both of them

It's not unusual for chip to have more than one sensor on it. In that case you should create two different drivers: one for accelerometer, and one for gyro. This way you will have two different files, one file per sensor.
For example, look how it's done for LSM330DLC chip (accelerometer + gyro):

*

*accel driver: drivers/iio/accel/st_accel_core.c

*gyro driver: drivers/iio/gyro/st_gyro_core.c
Both drivers are calling iio_device_register() function from driver's probe function, which creates corresponding files (which you can read/poll). Refer to documentation for further details.

As per my understanding I will open both the input devices from user space and add then to list of FD's which we want to poll. So when there is a new event how I can determine whether this event is from Gyro or aceel?

If you are curious about how to handle two /dev/input/event* files in user space, you basically have two choices:

*

*using blocking I/O: you can read/poll them in different threads

*using non-blocking I/O: you can open those files as O_NONBLOCK and just read() them in the same one thread; if new data is not available yet -- it will return -1 and errno will be set to EAGAIN; you can do those reads in infinite loop, for instance

This answer contains example of how to handle input file in C. And here you can read about blocking/non-blocking I/O.

A: You can use IOCTL (ioctl/read) calls to access the kernel functions from User space.
Refer below link for sample:
http://www.tldp.org/LDP/lkmpg/2.4/html/x856.html

A: There are many ways to access sensors data from kernel space to userspace

*

*Check for relevant driver of the sensor you used. Check whether it supports/provides sysfs support.

*you can read the data from /sys/class/ interfaces. You need to ensure that the relevant parameters exported to sysfs.
For eg: Temperature sensors should have exported temperature values(equivalent factors) in sysfs entry.
Examples(Below examples are fictions only)
cat /sys/class/hwmon/tempsensor/value
cat /sys/class/hwmon/tempsensor/min_value
cat /sys/class/hwmon/tempsensor/max_value

*In some drivers, you can read them through ioctl / read / write api's to read/write sensor data.


text:
Q: как в php передать параметр на странице index.php функцией header Требуется передать get-параметр на страницу индекс.php, но попытка сделать это таким образом: header('Location: index.php?success') - приводит к провалу. Совсем такой же резульат получается когда: header('Location: ?success'), а вот вариант: header('Location: success') заставляет браузер думать что мы хотим обратиться к несуществующей странице и я его понимаю. Причём в таком варианте: header('Location: test.php?success') всё работает исправно, при наличии конечно файла test.php в текущей папке. Как же всё таки передать этот параметр на страницу?
PS.: Тесты производились с использованием OpenServer, но подозреваю что на реальном хостинге я бы столкнулся с подобным результатом.

A: Слишком сложно вы с куками намудрили. Всё можно сделать проще:
if (!isset($_GET['success'])) {
    header('Location: ?success');
}
else {
    echo 'Success redirect!';
}

A: Разрешение данного вопроса я вижу через куки:
    if (empty($_COOKIE['success'])) {
      header('Location: ?success');
      if(isset($_GET['success'])) {
        setcookie('success', 'Operation has executed successfully');
      }
    } else {
      echo $_COOKIE['success'];
    };

Конечно такое использование весьма малопрактично, но оно работает и решает поставленную задачу


text:
Q: Jstree, get_checked, pass value to div onselect event i'm using an MVC c# asp.net 4.0 project with Jstree, but i have a small problem i have a jstree that's populated witha a JSON array.
My problem is I need to catch the value of the checkboxes in jstree when checked to a div in my view.

A: OK, i finally got this working this is the solution i hope it Help's someone :)
first you must bind:
    .bind('check_node.jstree', function (e, data) {
        $("#listSelectedActives").html(BuildList());
    })
   .bind('uncheck_node.jstree', function (e, data) {
       $("#listSelectedActives").html(BuildList());

then the use this function:
function BuildList() {
    var checked = $("#demoTree").jstree("get_checked", null, true);
    var output = "";

    $(checked).each(function (i, node) {
        var id = $(node).attr("ID");
        var text = $(node).attr("NodeText");

        output += "
ID: " + id + " TEXT: " + text + "
";
    })

    return output;
}

If this is too confusing please let'me know :)


text:
Q: SKCropNode precision problems I am developing a game in which I require several images to be overlaid in order to allow the player to choose the colour of their plane. I do this using the following code:
SKCropNode *cropper = [SKCropNode node];

SKSpriteNode *mask = [SKSpriteNode spriteNodeWithImageNamed:planeImageName];

SKTexture *texture = [SKTexture textureWithImageNamed:@"Camo"];

SKSpriteNode *paint = [SKSpriteNode spriteNodeWithTexture:texture];

SKSpriteNode *outline = [SKSpriteNode spriteNodeWithImageNamed:planeOutlineImageName];
outline.size = CGSizeMake(mask.size.width, mask.size.height);

LRHeroPlane *hero = [LRHeroPlane spriteNodeWithColor:[UIColor clearColor] size:CGSizeMake(5, 5)];

[hero addChild:cropper];
[cropper addChild:paint];
[cropper setMaskNode:mask];
[hero addChild:outline];

Where planeOutlineImageName and planeImageName are strings which can be used to find the images in my asset catalogue, and hero is the root node. When I add this to my scene, however, the camouflage paint goes beyond the borders of the outline, leaving the full plane looking messy and unprofessional. Below are the images used: (The actual images are .pdf but I converted them to .png to include them in this post)

Does anybody know why this is happening? Any help is much appreciated.


text:
Q: Next and Prev buttons not working with multiple calendars I have rendered multiple calendars on a single page and I need to use the next / prev buttons (as well as date select) in order to see different date ranges. I have connected external next / prev buttons, however, they only effect the last calendar on the page.
My JS to make the calendar elements:
document.addEventListener('DOMContentLoaded', function() {
    for (let index = 1; index <= array_length; index++) {
        calendar_str = 'calendar_' + String(index);
        eval('var ' + calendar_str + ' = document.getElementById(\'' + calendar_str + '\');');
        var calendar = new FullCalendar.Calendar(eval('calendar_' + String(index)), {

        ... code here to setup calendar ...

          });
          calendar.render();
          calendar.setOption('contentHeight', 200);

          document.getElementById('prev-btn-ext').addEventListener('click', function() {
            calendar.prev(); // call method
          });

          document.getElementById('next-btn-ext').addEventListener('click', function() {
            calendar.next(); // call method
          });

    }
});

My problem is that when the page is rendered, I can see all of the calendars and I can drag and drop events between them, however, when I click the next and prev buttons only the very last calendar changes. I need all of the calendars to change synchronously based off of the single next / prev button.
As you can see, my calendar instances are named 'calendar_1', 'calendar_2', etc. but the EventListener for the next and previous buttons only looks at the "calendar" variable. I am wondering if my problem has to do with that, maybe I need to specify an argument for calendar.next() or calendar.prev() for each calendar instance somehow?

A: This is a scope issue.
var calendar = redefines the calendar variable each time your loop runs. And since you've defined it with var, its scope is global to the whole function body, and extends inside all the callbacks assigned to the click events within the function. This means even the callbacks defined in previous iterations of the loop will use the most recent definition of calendar when they execute.
Whereas if you write let calendar = instead, this will limit the scope of the variable to the immediate enclosing block (the loop in this case), and mean the callbacks use the version defined within that iteration of the loop when they run, and your code will work as intended. This is one of the reasons let was added to JavaScript.
Demo: https://codepen.io/ADyson82/pen/OJMbjQz
This is a useful reference article: What's the difference between using "let" and "var"?

But overall, instead of using eval (which can be a security issue, as well as creating hard-to-read code) to generate unique variable names, it would be a lot cleaner just to store all your calendar references in an array. So here's an alternative approach:
document.addEventListener("DOMContentLoaded", function () {
  let calendars = []; //calendars array
  //auto-detect the number of calendars on the page
  var calendarElements = document.querySelectorAll(".cal");

  calendarElements.forEach(function (cal) {
    let calendar = new FullCalendar.Calendar(cal, { plugins: ["dayGrid"] });
    calendar.render();
    calendar.setOption("contentHeight", 200);
    calendars.push(calendar); //add to array of calendars
  });

  document
    .getElementById("prev-btn-ext")
    .addEventListener("click", function () {
      calendars.forEach(function (cal) {
        cal.prev();
      });
    });

  document
    .getElementById("next-btn-ext")
    .addEventListener("click", function () {
      calendars.forEach(function (cal) {
        cal.next();
      });
    });
});

The HTML would just need a small change to add the "cal" class to the calendar elements, e.g.:
<button type="button" id="prev-btn-ext">Prev</button>
<button type="button" id="next-btn-ext">Next</button>

Demo: https://codepen.io/ADyson82/pen/zYrodyG


text:
Q: Check if file exists in cache before removing it with Liip Imagine Bundle ( and Symfony3 ) Seems very basic: I want to check if a file exists in Liip Imagine Bundle cache before removing it. An example: after a photo update all the cache has been deleted, only some of the thumbnails have been regenerated (say 175px ones but not 250px ones for example) and I want to delete the corresponding photo.
I'm using a listener to do that in Symfony, as I've seen others do. Here's how it looks:
<?php
namespace AppBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use AppBundle\Entity\Photo;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Description of CachePhotoListener
 *
 * @author Norman
 */
class CachePhotoListener
{
    protected $cacheManager;
    protected $request;

public function __construct($cacheManager, RequestStack $request_stack)
{
    $this->cacheManager = $cacheManager;
    $this->request = $request_stack->getCurrentRequest();
}

public function postUpdate(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    if ($entity instanceof Photo) {
        $this->cacheManager->remove($entity->userPath());
    }
}

// Case : remove photo
public function preRemove(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    $filters = array('thumb_prospect_250', 'thumb_prospect_175');

    foreach($filters as $filter){
        if ($entity instanceof Photo) {
            $expectedCachePath = $this->cacheManager->getBrowserPath($entity->getPath(), $filter);

            if (file_exists($expectedCachePath)) {
                $this->cacheManager->resolve($this->request, $entity->getPath(), $filter);
                $this->cacheManager->remove($entity->getPath());
            }
        }
    }
}

The problem : file_exists returns always "false" even when the thumbnail exists. Here's a sample of the $expectedCachePath variable :
'http://dev.playermanager/media/cache/thumb_prospect_250/uploads/photos/11/4d176797ca5c7dd753b23ca17b77630eeff0ba8d.jpg' (length=118)

boolean false

'http://dev.playermanager/media/cache/thumb_prospect_175/uploads/photos/11/4d176797ca5c7dd753b23ca17b77630eeff0ba8d.jpg' (length=118)

boolean false

What am I doing wrong ? (I also tried to check the files with "is_readable" and obtaining the same results)

A: Ok, I managed to solve my problem. I modified two things.
First I checked the presence of the photo in Liip cache with the isStored method. Second, there was a mistake in my cacheManager->resolve parameters, the $this->request parameter shouldn't have been there.
Which gives me the following preRemove function in the listener:
public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        $filters = array('thumb_prospect_250', 'thumb_prospect_175');

        foreach($filters as $filter){
            if ($entity instanceof Photo) {
                $cacheExists = $this->cacheManager->isStored($entity->getPath(), $filter);

                if ($cacheExists) {
                    $this->cacheManager->resolve($entity->getPath(), $filter);
                    $this->cacheManager->remove($entity->getPath());
                }
            }
        }
    }

A: I think calling $this->cacheManager->getBrowserPath returns URL while you want directory path.
What do you store in $entity->getPath()? Maybe you can check whether the file exists in "%kernel.cache_dir%" directory yourself.


text:
Q: Differentiability of matrix-vector product map Let $E$ denote the set of endomorphisms (linear operators) on $\mathbb{R}^n$, and define $G : \mathbb{R^n} \times E \rightarrow \mathbb{R}^n$ by
$$ G(x,X) = Xx. $$
Question:
Is $G$ differentiable? If yes, what is its derivative?
I could not go very far in my attempt. For any $(y,Y), (h,H) \in \mathbb{R^n} \times E$ we have
$$ G((y,Y)+(h,H)) - G(y,Y) = Yh + Hy + Hh. $$
The next step would be to guess a linear map $L_{(y,Y)}$ such that
$$ \frac{\lVert G((y,Y)+(h,H)) - G(y,Y) - L_{(y,Y)}(h,H) \rVert}{\lVert (h,H) \rVert} \rightarrow 0$$
as $(h,H) \rightarrow 0$. However I am unable to come up with such a map.

A: Product rule. If $B$ is a continuous bilinear function then $B$ is differentiable and $$B'(x,y)\cdot (h,k) = B(x, k) + B(h, y).$$
Proof. Simply expand $B(x+h,y+k)=B(x,y)+B(x,k)+B(h,y)+B(h,k).$ Then, $\|B(h,k)\|\leq\|B\|\|h\|\|k\|=o(\|(h,k)\|).$ Q.E.D.
Apply simply this rule to $B(x,X)=Xx.$

A: HINT: suppose that $\langle\cdot |\cdot \rangle:\Bbb R^n\times\Bbb R^n\to\Bbb R$ is a bilinear product and $f,g:\Bbb R^m\to\Bbb R^n$ are Fréchet differentiable functions, then its easy to check from the definition of Fréchet derivative that
$$\partial[\langle f(x)|g(y)\rangle](h,v)=\langle\partial f(x)h|g(y)\rangle+\langle f(x)|\partial g(x)v\rangle\tag1$$
for $x,y,h,v\in\Bbb R^m$. Then note that the action of a matrix on a vector can be written as a sum of bilinear products, that is
$$Xv=([X]_1\cdot v,[X_2]\cdot v,\ldots,[X]_n \cdot v)\tag2$$
where the dot $\cdot$ stands for the dot product in $\Bbb R^n$ and $[X]_k$ is $k$-th file of the matrix $X$. Then using $(1)$ is easy to find $\partial[Xv](Y,h)$ for any $h,v\in\Bbb R^n$ and any $X,Y\in E$.


text:
Q: Swift - Mapping invisible button on UIImage which zoom In/Out Can some one suggest the best way to do this..
In the Below Image

*

*Add invisible buttons over the image for each section of the map.

*The image should be in a scrollview to zoom in and out the image.

*Zooming in/out should not change the button mapping area

*Should support for all iPhone models.

What I did..
Added a UIImageView inside a UIScrollView(for zoom in/out) and on viewDidAppear() manually added invisible button for the UIImage like this.
self.image.frame = CGRect(x: xValue , y:yValue, width: 60, height: 60)

Is there any better solution for finding the UIImage coordinates?

A: Very late to the party, but this should work:
in ViewDidLoad add this:
    scrollView.minimumZoomScale = 0.5
    scrollView.maximumZoomScale = 6.0
    scrollView.contentSize = self.imageView.frame.size
    scrollView.delegate = self

After ViewDidLoad add this:
// MARK: - Update the minimum zoom scale each time the controller updates its subviews
override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    updateMinZoomScaleForSize(view.bounds.size)
}

Then create a file private function to calculate the zoom scale for scrollView
fileprivate func updateMinZoomScaleForSize(_ size: CGSize) {
    let widthScale = size.width / imageView.bounds.width
    let heightScale = size.height / imageView.bounds.height
    let minScale = min(widthScale, heightScale)

    imageScrollView.minimumZoomScale = minScale
    imageScrollView.zoomScale = minScale
}

A: Are you using nine imageViews? No. it's not correct it seems.
Try like this :

*

*Take a collection view and give necessary constraints like top, bottom, left and right.

*Add image view to collection view cell. Add corner radius properties(it seems ur image views need this).

*For zoom in and zoom out actions, add pinch gesture to collection view.

*Add tap gesture for image view, instead of buttons.


text:
Q: Git doesn't automatically resolve conflicts This is a git-newbie question, however, I have almost 7 years of experience with clearcase, where what I am trying to achieve with git in this particular case is just plain simple. Anyway, I forked binutils on github and created a branch from the binutils-2_23_2 tag. I made some changes and it works. But I decided to ... and here's probably some difficulty with specifying what I decided to do (in term of clearcase/git vocabulary). In clearcase that would be:

*

*I have a branch with changes taken from binutils-2_23_2, there a
parent somewhere in the branch tree,

*somewhere else in the branch
tree I create another branch, this time going from the
binutils-2_24-branchpoing tag,

*then I 'merge' (cleartool merge -nc
-g -to file file@@/version-specification) and clearcase finds the common ancestor, resolves all automatic conflicts and delegates all
non-automatic conflicts resolution to e.g. three-way merge using
kdiff3,

I am not quite sure how to do something similar in git. There seem to be two potential candidates - that is "merge" and "rebase", but which is right? My idea would be to checkout the new 2_24 development branch branch and then "merge" changes from the 2_23_2 development branch, but when I do that git shows plethora unresolved conflicts of which none are related to my changes. I would expect git to handle this by itsels, and present me with only those which relate to my work on the older development branch.

A: The Git equivalent of the ClearCase merge would be git merge.
git rebase would be to replay one branch on top of the other.

The OP Wojciech Migda adds in the comments:

for the moment I have reverted to generating and applying patches - with this (plus some manual patch edit) it worked

That can work if the common ancestor is too old between the two branches.
As Ajedi32 comments:

Try running git merge-base branch1 branch2 to find the common ancestor of your branch and the branch you're merging.
  Then run git diff <result of last command> HEAD to review the changes made on your branch.


text:
Q: Use of a MySQL Query in Microsoft Access Dears,
Needless to say, I have been loosing my mind to make a query which works perfectly fine in MySQL work into Microsoft Access. I get some exceptions.
This is a comparison query which is supposed to indeed compare electrical consumptions from the same month, both in the current year and the previous one, grouped by building.
As I said, it works perfectly fine in MySQL, but not in MS Access.
Original Query:
SELECT
tblElectricReadings.Building,
SUM(CASE WHEN tblElectricReadings.ReadingDate >= DATE_SUB(NOW(), INTERVAL 1 YEAR) THEN (tblElectricReadings.EndMeter - tblElectricReadings.StartMeter) ELSE NULL END) AS 'Cons1',
SUM(CASE WHEN tblElectricReadings.ReadingDate BETWEEN DATE_SUB(NOW(), INTERVAL 2 YEAR) AND DATE_SUB(NOW(), INTERVAL 1 YEAR) THEN (tblElectricReadings.EndMeter - tblElectricReadings.StartMeter) ELSE NULL END) AS 'Cons2',
CONCAT(MONTHNAME(tblElectricReadings.ReadingDate)) AS MonthRecorded
FROM tblElectricReadings
WHERE   tblElectricReadings.ReadingDate >= DATE_SUB(NOW(), INTERVAL 2 YEAR)
GROUP BY tblElectricReadings.Building,
CONCAT(MONTHNAME(tblElectricReadings.ReadingDate))
ORDER BY tblElectricReadings.ReadingDate, tblElectricReadings.Building

I realize MS Access SQL is a bit different, so I tried some variations after lurking the internet. This is as close as I could get, but it still won't work:
SELECT
tblElectricReadings.[Building],
SUM(IIF(tblElectricReadings.[Reading Date] >= DATEADD("y",-1,NOW()), (tblElectricReadings.[End Meter] - tblElectricReadings.[Start Meter]),0)) AS 'Cons1',
SUM(IIF(tblElectricReadings.[Reading Date] BETWEEN DATEADD("y",-2,NOW()) AND DATEADD("y",-1,NOW()), (tblElectricReadings.[End Meter] - tblElectricReadings.[Start Meter]),0)) AS 'Cons2',
MONTHNAME(tblElectricReadings.[Reading Date]) AS MonthRecorded
FROM tblElectricReadings
WHERE tblElectricReadings.[Reading Date] >= DATEADD("y",-2,NOW())
GROUP BY tblElectricReadings.[Building], MONTHNAME(tblElectricReadings.[Reading Date])
ORDER BY tblElectricReadings.[Reading Date], tblElectricReadings.[Building]

With the above, I now get the following error: "Your query does not include the specified expression 'tblElectricReadings.[Reading Date]' as part of an aggregate function.
Has anyone got any clues what I am doing wrong? Any help will of course be greatly appreciated :) Apologies if I am asking something easy, but I am still learning a lot here :(
Thanks for any eventual help you can provide.
EDIT 3: I managed! This is what worked for me - Thanks all for the help provided, appreciated.
SELECT
tblElectricReadings.[Building],
MONTHNAME(MONTH(tblElectricReadings.[Reading Date])) AS MonthRecorded,
SUM(IIF(tblElectricReadings.[Reading Date] >= DATEADD("yyyy",-1,NOW()), (tblElectricReadings.[End Meter] - tblElectricReadings.[Start Meter]),0)) AS [Current Year Consumption],
SUM(IIF(tblElectricReadings.[Reading Date] BETWEEN DATEADD("yyyy",-2,NOW()) AND DATEADD("yyyy",-1,NOW()), (tblElectricReadings.[End Meter] - tblElectricReadings.[Start Meter]),0)) AS [Previous Year Consumption]
FROM tblElectricReadings
WHERE tblElectricReadings.[Reading Date] >= DATEADD("yyyy",-2,NOW())
GROUP BY tblElectricReadings.[Building], MONTH(tblElectricReadings.[Reading Date])
ORDER BY MONTH(tblElectricReadings.[Reading Date]), tblElectricReadings.[Building];

A: Not sure it's the only issue but
SUM(IIF(tblElectricReadings.ReadingDate >= DATEADD("y",-1,NOW()), (tblElectricReadings.EndMeter - tblElectricReadings.StartMeter),"")

is obviously wrong: you can't SUM Strings, even empty ones. Try instead:
SUM(IIF(tblElectricReadings.ReadingDate >= DATEADD("y",-1,NOW()), (tblElectricReadings.EndMeter - tblElectricReadings.StartMeter),0)

And do the same for the other occurences.
EDIT:
I also think that your ORDER BY clause doesn't make sense since it tries to order on something that is not present as such in the output data set. It should be:
ORDER BY MONTHNAME(tblElectricReadings.ReadingDate), tblElectricReadings.Building


text:
Q: Bash version 3.2 doesn't read in lines/compare lines to a regular expression I wrote a script in bash at home to solve a problem and "brought it with me" to work (More or less I just found it useful enough to put on my work laptop). It is a bash script and essentially, the only difference between my home version and the work version is where the files are located.
The bash script has this in it:
if [ ! -e $finalfile ]; then
    echo >> $finalfile
else
    echo > $finalfile
fi

while IFS='' read -r line || [[ -n "$line" ]]; do
    if [[ "$line" =~ [A-Z]{1,}\( ]]; then
        varName=$(echo "$line" |cut -d "(" -f1 | tr -d "[:punct:]" | tr -d "[:blank:]")
        findComments
    fi
done < "$getVarNames"

When I run this script at home, it reads in every line and prints correctly to final file (which is done in a different function). All the program does is read in each line from a file with the variable names, strip all the extraneous punctuation and blanks, and then checks a different file for comments with that variable name in it in the function findComments. The comments follow a specific form and depending on the form, the program will place some text into the finalfile. So I use read and regular expressions a LOT throughout this script.
The work version of the script does not run. When I use the -x option when I run it, this is what I get:

+ IFS=
+ read -r line
=~ [A-Z]{1,}( ]])=c(581,583)
+ IFS=
+ read -r line
=~ [A-Z]{1,}( ]])=c(584,585)
+ IFS=
+ read -r line
=~ [A-Z]{1,}( ]]2)=c(586,587)
+ IFS=
+ read -r line
=~ [A-Z]{1,}( ]]1)=c(588)

I'm not sure why. But it is reading in the line, because the garbage printed after my regular expression in the output are pieces of the lines it's supposed to be reading in. I checked the version of bash and work is running 3.2.25 while I'm running 4.2.25 at home (I think? I know I updated in 2011 or so and I think that's 4.2 or 4.3? But I know I'm at Bash 4.0, also I'm not home atm so I can't check... All I know is for sure I don't have bash v3). I'm also not 100% sure that we're going to update bash anytime soon at work. If things go like they do for most software, then we might not update until a program we run has an incompatibility with bash 3.2. So... like never.
I know bash 3.0 added some regular expression matching and in bash 3.2 there's a change to the regular expression operator =~ so that you don't need to put " " around the regular expression, I read that somewhere but here's link that I'm looking at right now. What I'm not seeing is any information on read changing in bash v3. There were some changes in v4 but I haven't found any changes that affect how I'm using read.
The long and short of this is that I don't know why this code doesn't work in version 3.2 of bash. I've been looking for an answer wherever I can find information but I legitimately can't figure out what is the problem with my code. I'm pretty sure it's read because I think my regular expression is OK, but is it possibly the regular expression? How can I fix my code so it works on a system with 3.2 on it?
Also on another note, I don't know if there's anywhere that has like... release notes or a changelog or something that I can look at for bash. It would be helpful if I could look at exactly what 3.2 was fixing or like, exactly what was added in my current (home) version of bash.


text:
Q: How to show/ hide windowActionBar programatically in Android? I am applying one style to two activities. MainActivity.java has toolbar setup instead of action bar, therefore, I have following line in theme style to hide action bar:
<item name="windowActionBar">false</item>

And in the another activity I have action bar enabled:
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);

But this returns NOException error.
I tried following but didn't help either:
actionBar.show();

Style:
<style name="BrownTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/brown</item>
    <item name="colorPrimaryDark">@color/dark_brown</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="buttonStyle">@color/brown</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Elaboration:
I am using style for two activities. The first activity has it's own toolbar instead of default action bar and the second activity has action bar. If I remove from style then I cannot run the first activity and if I put, then I cannot run the second activity. I want to enable it programatically in second activity.
Is there any possibility to change the style item attributes programatically? or any override method to bypass what I have in style item attributes?

A: I fixed this using custom toolbar for both activities.
The style.xml now has the following theme:
<style name="BrownTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/brown</item>
    <item name="colorPrimaryDark">@color/dark_brown</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="buttonStyle">@color/brown</item>
</style>

And in the second activity (or all other activities):
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And the toolbar layout (app_bar_main.xml):
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

And the activity layout:
<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

A: getSupportActionBar().hide(); to hide
and getSupportActionBar().show(); to show.


text:
Q: Not able to connect to openldap server in ldaps mode - CentOS I have configured my openldap server in ldaps mode. But after configuring I am not able to connect it on 636 port where as I am able to connect on 389 port
[root@testldap certs]# ldapsearch -x -LLL -h testldap.india.airwave.com -p 636 -D  cn=Manager,dc=india,dc=airwave,dc=com -w  whopee   -b "ou=Users,dc=india,dc=airwave,dc=com"
ldap_result: Can't contact LDAP server (-1)
[root@testldap certs]# ldapsearch -x -LLL -h testldap.india.airwave.com -p 389 -D  cn=Manager,dc=india,dc=airwave,dc=com -w  whopee   -b "ou=Users,dc=india,dc=airwave,dc=com"
dn: ou=users,dc=india,dc=airwave,dc=com
objectClass: organizationalUnit
ou: users

dn: cn=Sandeep Lade,ou=users,dc=india,dc=airwave,dc=com
cn: Sandeep Lade
sn: Lade
objectClass: inetOrgPerson
userPassword:: d2hvcGVl
uid: vlade

dn: cn=Engineering,ou=users,dc=india,dc=airwave,dc=com
cn: Engineering
objectClass: groupOfNames
member: cn=Sandeep Lade,ou=users,dc=india,dc=airwave,dc=com

Both 389 and 636 are listening
[root@testldap certs]# netstat -an | grep 389
tcp        0      0 0.0.0.0:389                 0.0.0.0:*                   LISTEN
tcp        0      0 :::389                      :::*                        LISTEN
unix  2      [ ]         DGRAM                    19389
[root@testldap certs]# netstat -an | grep 636
tcp        0      0 0.0.0.0:636                 0.0.0.0:*                   LISTEN
tcp        0      0 :::636                      :::*                        LISTEN
unix  3      [ ]         STREAM     CONNECTED     13636
[root@testldap certs]#

Able to connect to 636 port using openssl connect
[root@localhost sandeeplade]# openssl s_client -connect 10.22.156.157:636 -showcerts -CAfile cacert.pem
CONNECTED(00000003)
write:errno=104
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 307 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    Start Time: 1516769274
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---
[root@localhost sandeeplade]#

ldap.conf file
[root@testldap certs]# cat /etc/openldap/ldap.conf
#
# LDAP Defaults
#

# See ldap.conf(5) for details
# This file should be world readable but not world writable.

#BASE   dc=example,dc=com
#URI    ldap://ldap.example.com ldap://ldap-master.example.com:666

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

PORT 636
#TLS_CACERTDIR  /etc/openldap/certs
TLS_CACERTDIR /etc/openldap/certs
TLS_REQCERT allow

ssl start_tls
tls_checkpeer yes
tls_cacertfile /etc/openldap/certs/cacert.pem

[root@testldap certs]#

slapd.conf file

[root@testldap certs]# cat /etc/openldap/slapd.conf
TLSCACertificateFile    /etc/openldap/certs/cacert.pem
TLSCertificateFile      /etc/openldap/certs/server.crt
TLSCertificateKeyFile   /etc/openldap/certs/server.key

# Use the following if client authentication is required
#TLSVerifyClient        demand
# ... or not desired at all
TLSVerifyClient never

[root@testldap certs]#

certificates are available in /etc/openldap/certs and they are generated using openssl
[root@testldap certs]# cd /etc/openldap/certs/
[root@testldap certs]# ls -lrt
total 96
-r--------. 1 root root    45 Jan 23 21:59 password
-rw-r--r--. 1 root root 16384 Jan 23 21:59 secmod.db
-rw-r--r--. 1 root root 65536 Jan 23 21:59 cert8.db
-rw-r--r--. 1 root root 16384 Jan 23 21:59 key3.db
-rw-------. 1 ldap ldap  1743 Jan 23 23:57 server.key.pass
-rw-r--r--. 1 root root  1094 Jan 23 23:59 server.csr
-rw-r--r--. 1 root root  4718 Jan 24 00:02 server.crt
-rw-r--r--. 1 root root  1675 Jan 24 00:38 server.key
-rw-r--r--. 1 root root  4537 Jan 24 05:18 cacert.pem
[root@testldap certs]#

ldaps enabled in /etc/sysconfig/ldap
[root@testldap certs]# cat /etc/sysconfig/ldap
# Options of slapd (see man slapd)
#SLAPD_OPTIONS=

# At least one of SLAPD_LDAP, SLAPD_LDAPI and SLAPD_LDAPS must be set to 'yes'!
#
# Run slapd with -h "... ldap:/// ..."
#   yes/no, default: yes
SLAPD_LDAP=yes

# Run slapd with -h "... ldapi:/// ..."
#   yes/no, default: yes
SLAPD_LDAPI=yes

# Run slapd with -h "... ldaps:/// ..."
#   yes/no, default: no
SLAPD_LDAPS=yes

# Run slapd with -h "... $SLAPD_URLS ..."
# This option could be used instead of previous three ones, but:
# - it doesn't overwrite settings of $SLAPD_LDAP, $SLAPD_LDAPS and $SLAPD_LDAPI options
# - it isn't overwritten by settings of $SLAPD_LDAP, $SLAPD_LDAPS and $SLAPD_LDAPI options
# example: SLAPD_URLS="ldapi:///var/lib/ldap_root/ldapi ldapi:/// ldaps:///"
# default: empty
#SLAPD_URLS=""

# Maximum allowed time to wait for slapd shutdown on 'service ldap stop' (in seconds)
#SLAPD_SHUTDOWN_TIMEOUT=3

# Parameters to ulimit, use to change system limits for slapd
#SLAPD_ULIMIT_SETTINGS=""
[root@testldap certs]#

I am struggling to get the openldap worked from past two days. Any help is highly appreciated

A: Your ldpasearch parameters are wrong for an SSL query.  See here: https://stackoverflow.com/questions/9468137/ldapsearch-over-ssl-tls-doesnt-work
You need to use the "-H" iso -h and -p.

A: I will suggest to add the server CA root to /etc/openldap/ldap.conf :
TLS_CACERT /etc/ssl/certs/ca-bundle.crt
TLS_REQCERT allow

Also try to run slapd with -d 256 to debug connections And execute ldapsearch with -d 9  for debugging also.
I'm sure there is an issue with the generated certificates.

A: You should delete existing cert cache dirs with pattern like this, if exists:
/tmp/openldap-tlsmc-certs--*

More info: https://fedoraproject.org/wiki/OpenLDAP-and-MozNSS-Compatibility-Layer


text:
Q: How to check for duplicate value in Excel vba? Data validations in Excel are not working when user copy-pastes the data.
I want an error message to be thrown when the user pastes duplicate data in a column.
I'm using the following code(another alternative) but this is not what I want. I want this to be checked when the user inserts the data and if there is any issue then throw an error message.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
  Dim rngCell As Range Dim lngLstRow As Long lngLstRow = Sheet1.UsedRange.Rows.Count
  For Each rngCell In Sheet1.Range("A1:A" & lngLstRow)
    If CountIf(Range("A:A"),A1) > 2 Then
      MsgBox "Please enter unique value " & rngCell.Address
        rngCell.Select
    End If
  Next
End Sub

A: By using the Change event, we can trap duplicate entries without data validation:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim RangeOfInterest As Range, Intersection As Range, cell As Range

    Set RangeOfInterest = Range("A:A")
    Set Intersection = Intersect(RangeOfInterest, Target)
    If Intersection Is Nothing Then Exit Sub

    With Application
        For Each cell In Intersection
            If .WorksheetFunction.CountIf(RangeOfInterest, cell.Value) > 1 Then
                .EnableEvents = False
                    .Undo
                .EnableEvents = True
                MsgBox "duplicates not allowed"
            Exit Sub
            End If
        Next cell
    End With
End Sub

NOTE:

*

*the code can handle both typed entries into column A as well as copy/pastes into the column

*the code can handle multi-cell copy/pastes into the column