text:
Q: Util to extract bits from byte array into a new byte[] I'm trying to build a utility class to make bitwise manipulation and conversions more readable. Currently I'm stuck at building a method to extract bits from a byte array and form a new byte[] from them. Needless to say I'm not very fluent in bitwise operations.
I believe it could probably be achieved using BitSet, but there would be too many conversions and the implementation would be Java-speciffic. It would be nice to have a clear algorithm that could be easily ported to other languages later on.
So far I've got that far:
    public static byte[] toBytes(int offset /*full bytes*/, int bitsOffset /*bytes + bits*/, int bitsCount, byte... bytes) {
        int bytesCount = bitsCount / 8;
        int paddingBits = bitsCount % 8;
        int partialBits = 8 - paddingBits;

        if (paddingBits > 0) {
            bytesCount++;
        }

        byte[] data = new byte[bytesCount];

        return data;
    }

I've commented the above out and replaced it temporary with
    public static byte[] toBytes(int offset, int bitsOffset, int bitsCount, byte... bytes) {
        int firstBitIndex = (offset * 8) + bitsOffset;
        return new BigInteger(new BigInteger(1, bytes).toString(2).substring(firstBitIndex, firstBitIndex + bitsCount), 2).toByteArray();
    }

However I'd still like to have a proper implementation with as little overhead as possible and not speciffic to Java (no java-speciffic tools used, like BitSet)
This is a hint what I'd expect it to do
   /**
     * [0000 0110   1111 0010] = toBytes(1, 4, 12, [xxxx xxxx   xxxx 0110   1111 0010   xxxx xxxx])
     * [0000 0110   1111 0010] = toBytes(1, 5, 12, [xxxx xxxx   xxxx x011   0111 1001   0xxx xxxx])
     * [0000 0110   1111 0010] = toBytes(1, 6, 12, [xxxx xxxx   xxxx xx01   1011 1100   10xx xxxx])
     */

And here are some unittests
public class ByteUtilTest {

    @Test
    public void toBytes_sameByte() {
        byte[] result = ByteUtil.toBytes(1, 4, 3,
                toByte("11111111"),
                toByte("11110111"),
                toByte("11111111"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("00000011")), toBinaryString(result));
    }

    @Test
    public void toBytes_sameByte_full() {
        byte[] result = ByteUtil.toBytes(1, 0, 8,
                toByte("11111111"),
                toByte("01110101"),
                toByte("11111111"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("01110101")), toBinaryString(result));
    }

    @Test
    public void toBytes_sameByte_noneWithoutOffset() {
        byte[] result = ByteUtil.toBytes(1, 0, 0,
                toByte("11111111"),
                toByte("01110101"),
                toByte("11111111"),
                toByte("11111111"));

        assertEquals(0, result.length);
    }

    @Test
    public void toBytes_sameByte_noneWithOffset() {
        byte[] result = ByteUtil.toBytes(1, 3, 0,
                toByte("11111111"),
                toByte("01110101"),
                toByte("11111111"),
                toByte("11111111"));

        assertEquals(0, result.length);
    }

    @Test
    public void toBytes_twoBytes_resultWithTwoBytes() {
        byte[] result = ByteUtil.toBytes(1, 2, 11,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011111"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("00000110"), toByte("10110011")), toBinaryString(result));
    }

    @Test
    public void toBytes_twoBytes_resultWithOneByte() {
        byte[] result = ByteUtil.toBytes(1, 2, 7,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011111"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("01101011")), toBinaryString(result));
    }

    @Test
    public void toBytes_twoBytes_firstFull() {
        byte[] result = ByteUtil.toBytes(1, 0, 11,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011111"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("00000011"), toByte("10101100")), toBinaryString(result));
    }

    @Test
    public void toBytes_twoBytes_lastFull() {
        byte[] result = ByteUtil.toBytes(1, 5, 11,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011101"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("00000101"), toByte("10011101")), toBinaryString(result));
    }

    @Test
    public void toBytes_twoBytes_bothFull() {
        byte[] result = ByteUtil.toBytes(1, 0, 16,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011101"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("01110101"), toByte("10011101")), toBinaryString(result));
    }

    @Test
    public void toBytes_threeBytes() {
        byte[] result = ByteUtil.toBytes(1, 2, 19,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011101"),
                toByte("10111111"));

        assertEquals(
                toBinaryString(
                        toByte("00000110"),
                        toByte("10110011"),
                        toByte("10110111")),
                toBinaryString(result));
    }

    @Test
    public void toBytes_threeBytes_firstFull() {
        byte[] result = ByteUtil.toBytes(1, 0, 19,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011101"),
                toByte("10111111"));

        assertEquals(
                toBinaryString(
                        toByte("00000011"),
                        toByte("10101100"),
                        toByte("11101101")),
                toBinaryString(result));
    }

    @Test
    public void toBytes_threeBytes_lastFull() {
        byte[] result = ByteUtil.toBytes(1, 2, 22,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011101"),
                toByte("10111111"));

        assertEquals(
                toBinaryString(
                        toByte("00110101"),
                        toByte("10011101"),
                        toByte("10111111")),
                toBinaryString(result));
    }

    @Test
    public void toBytes_threeBytes_allFull() {
        byte[] result = ByteUtil.toBytes(1, 0, 24,
                toByte("11111111"),
                toByte("01110101"),
                toByte("10011101"),
                toByte("10111111"));

        assertEquals(
                toBinaryString(
                        toByte("01110101"),
                        toByte("10011101"),
                        toByte("10111111")),
                toBinaryString(result));
    }

    @Test
    public void toBytes_bitsOffset_4() {
        byte[] result = ByteUtil.toBytes(1, 4, 12,
                toByte("11111111"),
                toByte("11110110"),
                toByte("11110010"),
                toByte("11111111"));

        assertEquals(toBinaryString(toByte("00000110"), toByte("11110010")), toBinaryString(result));
    }

    @Test
    public void toBytes_bitsOffset_5() {
        byte[] result = ByteUtil.toBytes(1, 5, 12,
                toByte("11111111"),
                toByte("11111011"),
                toByte("01111001"),
                toByte("01111111"));

        assertEquals(toBinaryString(toByte("00000110"), toByte("11110010")), toBinaryString(result));
    }

    @Test
    public void toBytes_bitsOffset_6() {
        byte[] result = ByteUtil.toBytes(1, 6, 12,
                toByte("11111111"),
                toByte("11111101"),
                toByte("10111100"),
                toByte("10111111"));

        assertEquals(toBinaryString(toByte("00000110"), toByte("11110010")), toBinaryString(result));
    }

    private String toBinaryString(byte... data) {
        StringBuilder binaryStr = new StringBuilder();
        String value = Integer.toBinaryString(data[0]);
        if (value.length() > 8) value = value.substring(value.length() - 8);
        else if (value.length() < 8) value = String.format("%8s", value).replace(" ", "0");
        binaryStr.append(value);
        for (int i = 1; i < data.length; i++) {
            value = Integer.toBinaryString(data[i]);
            if (value.length() > 8) value = value.substring(value.length() - 8);
            else if (value.length() < 8) value = String.format("%8s", value).replace(" ", "0");
            binaryStr.append(" ").append(value);
        }

        return binaryStr.toString();
    }

    private String toString(byte[] data) {
        return Arrays.toString(data);
    }

    private byte toByte(String binary) {
        return (byte) Integer.parseInt(binary, 2);
    }
}

A:
So far I've got [...] byte[] data = new byte[bytesCount];

Unfortunately this approach will only work if your bit offset is a multiple of 8. In all other cases you have to divide every byte you intend to copy. The following drawing illustrates how to divide each byte and where to put the divided parts.
MSB = most significant bit
LSB = least significant bit

Implementing the algorithm illustrated above is a bit tricky because of a lot of corner cases. The following implementation passes all your tests and all of my tests. I used many variables to give all the calculations meaningful names in the hope that it will be easier to follow. You can shorten the implementation by eliminating some of these variables and calculate some values in-place.
I took the liberty to rename your function toBytes to bitSubstring. The former name toBytes seemed a bit off for a method that already takes bytes as an input.
public static byte[] bitSubstring(int byteOffset, int bitOffset,
                                  int lengthInBits, byte... source) {
    return bitSubstring(8 * byteOffset + bitOffset, lengthInBits, source);
}

public static byte[] bitSubstring(int startBit, int lengthInBits,
                                  byte... source) {
    assert startBit >= 0 && startBit < 8 * source.length;
    assert lengthInBits >= 0 && startBit + lengthInBits <= 8 * source.length;

    int lengthInBytes = (int) Math.ceil(lengthInBits / 8.0);
    byte[] target = new byte[lengthInBytes];
    int startByte = startBit / 8;
    int endBitExclusive = startBit + lengthInBits;
    int endByteExclusive = (int) Math.ceil(endBitExclusive / 8.0);
    int sourceBytesToRead = endByteExclusive - startByte;
    int lowerPartSize = 8 * endByteExclusive - endBitExclusive;
    int shiftLowerUp = (8 - lowerPartSize);
    int shiftUpperDown = lowerPartSize;
    int lastSrc = 0;
    if (sourceBytesToRead > lengthInBytes) {
        lastSrc = source[startByte] & 0xFF;
        startByte++;
    }
    for (int targetByte = 0; targetByte < target.length; ++targetByte) {
        int curSrc = source[startByte + targetByte] & 0xFF;
        target[targetByte] |= (lastSrc << shiftLowerUp)
                            | (curSrc >>> shiftUpperDown);
        lastSrc = curSrc;
    }
    int overhang = 8 * lengthInBytes - lengthInBits;
    if (overhang > 0) {
        target[0] &= 0xFF >>> overhang;
    }
    return target;
}

Above algorithm should be fairly fast. However, if you are only interested in implementation size and readability an approach where you copy bit by bit is better.
public static byte[] bitSubstringSlow(int startBitSource, int lengthInBits,
                                      byte... source) {
    byte[] target = new byte[(int) Math.ceil(lengthInBits / 8.0)];
    int startBitTarget = (8 - lengthInBits % 8) % 8;
    for (int i = 0; i < lengthInBits; ++i) {
        setBit(target, startBitTarget + i, getBit(source, startBitSource + i));
    }
    return target;
}

public static int getBit(byte[] source, int bitIdx) {
    return (source[bitIdx / 8] >>> (7 - bitIdx % 8)) & 1;
}

public static void setBit(byte[] target, int bitIdx, int bitValue) {
    int block = bitIdx / 8;
    int shift = 7 - bitIdx % 8;
    target[block] &= ~(1 << shift);
    target[block] |= bitValue << shift;
}

… or less re-usable but even shorter:
public static byte[] bitSubstringSlow2(int startBitSource, int lengthInBits,
                                       byte... source) {
    byte[] target = new byte[(int) Math.ceil(lengthInBits / 8.0)];
    int startBitTarget = (8 - lengthInBits % 8) % 8;
    for (int i = 0; i < lengthInBits; ++i) {
        int srcIdx = startBitSource + i;
        int tgtIdx = startBitTarget + i;
        target[tgtIdx / 8] |= ((source[srcIdx / 8] >>> (7 - srcIdx % 8)) & 1)
                              << (7 - tgtIdx % 8);
    }
    return target;
}


text:
Q: Run disk error check on NTFS file? I have a feeling that my system hard drive is dying. Benchmark kind of enforces it. Here is the benchmark of my system hard drive during low system activity:

And here is the benchmark of backup drive:

Furthermore, there are some files which I just can't touch because I get CRC errors and the hard drive activity spikes to 100% with operating speeds less than 1 MB/s while working with such files.
I haven't yet tried swapping SATA cable as I have read this might cause the problems. Anyway, I would like to run some tests on specific clustsers where those files I am interested in are stored.
I don't want to do the full chkdsk because it takes a very long time.
I would like to either find the utility which executes the disk check directly on the clusters where the file belongs or a couple utilities where one tells me the cluster locations and another can check just those locations.
How do I check and possibly fix disk errors where the files I am interested in are stored?
Edit: S.M.A.R.T. info:

A: Install CrystalDiskInfo and run it, and post the S.M.A.R.T. info in your question.
What you want to look at in particular are the reallocated sector count and the pending sector reallocations.
When you say you get CRC errors, what application is telling you this?
Neither the harddrive nor the filesystem (NTFS) tracks the CRCs of files.
You can't fix disk errors. Disk errors are bad sectors on the disk. The drive will automatically remap them, but at some point you just have to copy all the data off and put it onto a new drive.

A: You are right. Read errors and reallocated sectors are symptoms of dying disk.
You have very high read error rate, it has a lot of reallocated sector count etc.
Maybe thats just some sectors, maybe it is partial damage and disk firmware can deal with that by reallocating sectors, but that disk is not reliable anymore.
Backup your all important data and replace disk ASAP if you can.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Minimise the functional $\int_D \| \operatorname{grad}u(M)\|^2\,\mathrm dM$ I have the following problem:

Let $k \in \mathbb{N}^*$ and $D$ be the closed disk of radius $1$ in $\mathbb{C}$ and $g\colon \mathbb{U} \to \mathbb{R}:z \mapsto \sin(k\mathrm{Arg}(z))$. Now let $E$ be the set of functions from $D$ to $\mathbb{R}$ which are continuous on $D$, $C^1$ on $\overset{\circ}{D}$ and whose partial derivatives can be continuously extend to $D$ and whose restrictions at $\mathbb{U}$ is $g$. Find the minimum of the functional:
  $$u \in E \mapsto\int_D \| \operatorname{grad}u(M)\|^2 \,\mathrm{d}M.$$

I would like to have some thoughts on it, the problem is that I do not know at all how to abord it and where to look at.
I know that most of the time in order to find the maximum of a function we need to find the critical point of this function in order to see if these points are relatives minimum and then ajust. But here it is not clear to me how I should find the critical points or if I should apply an other technique.
Thank you.

A: $\def\∆{\mathord{∆}}\def\d{\mathrm{d}}\def\vec{\boldsymbol}$Using polar coordinates, $g(θ) = \sin(kθ) \in C([0, 2π])$, thus the solution to the equation$$
\begin{cases}
-\∆u = 0, \quad x \in D^\circ\\
u|_{∂D} = g
\end{cases}
$$
satisfies $u \in C(D) \cap C^∞(D^\circ)$ and\begin{align*}
u(r, θ) &= \frac{1}{2π} \int_{-π}^π \frac{1 - r^2}{1 + r^2 - 2r \cos(α - θ)}g(α) \,\d α\\
&= \frac{1}{2π} \int_{-π}^π \frac{1 - r^2}{1 + r^2 - 2r \cos(α - θ)} \sin(kα) \,\d α.
\end{align*}
Next, it will be proved that this $u \in \mathscr{E}$ minimizes $\displaystyle J(v) = \int_D |∇u|^2 \,\d x$ in $\mathscr{E}$. For any fixed $v \in \mathscr{E}$, denote $φ = v - u$. Note that $u + tφ \in \mathscr{E}$ for any $t \in \mathbb{R}$. Define $j(t) = J(u + tφ)$ for $t \in \mathbb{R}$, then$$
j'(t) = \int\limits_D \frac{\d}{\d t} \bigl(∇(u + tφ) · ∇(u + tφ)\bigr) \,\d x = 2 \int\limits_D ∇(u + tφ) · ∇φ \,\d x,\\
j''(t) = 2 \int\limits_D \frac{\d}{\d t} \bigl( ∇(u + tφ) · ∇φ \bigr) \,\d x = \int\limits_D |∇φ|^2 \,\d x \geqslant 0.
$$
Note that $u|_{∂D} = v|_{∂D} = g$ implies $φ|_{∂D} = 0$, and $\∆ u = 0$ on $D^\circ$, thus\begin{align*}
\frac{1}{2} j'(0) &= \int\limits_D ∇u · ∇φ \,\d x = \int\limits_{∂D} φ∇u · \vec{n} \,\d s - \int\limits_D φ\∆ u \,\d x = 0,
\end{align*}
which implies $J(v) = j(1) \geqslant j(0) = J(u)$. Therefore, $u$ minimizes $J$. Finally,\begin{align*}
J(u) &= \int\limits_D |∇u|^2 \,\d x = \int\limits_{∂D} u∇u · \vec{n} \,\d s - \int\limits_D u\∆ u \,\d x\\
&= \int\limits_{∂D} g\frac{∂u}{∂\vec{n}} \,\d s = \int\limits_{∂D} \left. g\frac{∂u}{∂r} \right|_{r = 1} \,\d s = \int_{-π}^π \sin(kα) · \frac{∂u}{∂r}(1, α) \,\d α.
\end{align*}

Now for this particular $g(θ) = \sin(kθ)$, after solving for $u$ for small $k$, the solution for general $k$ can be guessed as $u(r, θ) = r^k \sin(kθ)$. To verify this, note that in polar coordinates,$$
\∆ = \frac{∂}{∂r^2} + \frac{1}{r} \frac{∂}{∂r} + \frac{1}{r^2} \frac{∂^2}{∂ θ^2},
$$
thus\begin{align*}
\∆ u(r, θ) &= \frac{∂}{∂r^2}(r^k \sin(kθ))  + \frac{1}{r} \frac{∂}{∂r}(r^k \sin(kθ)) + \frac{1}{r^2} \frac{∂^2}{∂ θ^2}(r^k \sin(kθ))\\
&= k(k - 1) r^{k - 2} \sin(kθ) + \frac{1}{r} · k r^{k - 1} \sin(kθ) - \frac{1}{r^2} · r^k k^2\sin(kθ) = 0.
\end{align*}
Therefore,$$
J(u) = \int_{-π}^π \sin(kα) · \frac{∂u}{∂r}(1, α) \,\d α = \int_{-π}^π \sin(kα) · k\sin(kα) \,\d α = kπ.
$$


text:
Q: sqlite query with like opearator is not working in xcode I wrote the code for sqlite statement as follows:
if(sqlite3_open([[self filepath] UTF8String], &db) == SQLITE_OK)
{
    retrievestatement = nil;

    if(retrievestatement == nil) {

        const char *sql = "Select * from OrdersHeaderTable where orderPlaceDate like '%?'";

        if(sqlite3_prepare_v2(db, sql, -1, &retrievestatement, NULL) != SQLITE_OK)
            NSAssert1(0, @"Error while creating detail view statement. '%s'", sqlite3_errmsg(db));

    }
    sqlite3_bind_text(retrievestatement, 1, [year UTF8String], -1, SQLITE_TRANSIENT);

    while(sqlite3_step(retrievestatement) == SQLITE_ROW)
    {

        NSLog(@"value is %@",[NSString stringWithUTF8String:(const char*)sqlite3_column_text(retrievestatement, 0)]);

    }

    sqlite3_finalize(retrievestatement);
}

But it is not getting data.Please suggest me.

A: Please check this line . I think this is the problem.
    const char *sql = "Select * from OrdersHeaderTable where orderPlaceDate like '%?'";

Change the above line to
    const char *sql = "Select * from OrdersHeaderTable where orderPlaceDate like '%hyd'";

i.e change the ? mark to your search string .

A: It should work this way:
const char *sql = "Select * from OrdersHeaderTable where orderPlaceDate like ?001";
......
sqlite3_bind_text(retrieveStatement, 1, [[NSString stringWithFormat:@"%@%%", year] UTF8String], -1, SQLITE_TRANSIENT);

I'm reporting here only the relevant part of code, add the prepare statement etc.

A: The parameter marker ? does not work inside strings.
You have to combine the string '%' and the value of your year parameter; this can be done either in your code (see Michele's answer), or in SQL like this:
sql = "Select * from OrdersHeaderTable where orderPlaceDate like '%' || ?";


text:
Q: Make fgets skip special character My question is about parsing a text file using fgets. Basically there are commands that I need to parse. Once I hit a ";", anything afterwards are comments and can be skipped:
;;
;; Very basic test - no ifs or comparisons
;;

defun main
5 3 2 * + printnum endl     ;; Should output (3 * 2) + 5 = 11
3 4 5 rot * + printnum endl ;; Should output (3 * 5) + 4 = 19
return

After processing:
defun main
5 3 2 * + printnum endl
3 4 5 rot * + printnum endl
return

In my code, I have a while loop to get each line from the text file:
while (fgets(str, 1000, IN)!= NULL)
        {
            len = strlen(str);
            str[len-1] = '\0'; //removes newline character
            printf("%s\n", str);
            hello = strtok(str,";");
            printf("%s\n", hello);

        }

I'm unsure as to how to make it where, when strtok sees a semicolon, it will automatically cut out anything that comes after, up until the end of the line. My attempt returns the following output:
 Very basic test - no ifs or comparisons

defun main
5 3 2 * + printnum endl
3 4 5 rot * + printnum endl
retur

It cuts off the last character from return but doesn't remove the comment after the second line of semicolons. This is pretty standard behavior no matter the contents of the text file I'm parsing. What am I missing here? Thank you.

A: The problem comes from strtok. As man strtok says:

The strtok() function breaks a string into a sequence of zero or more
         nonempty tokens.

[...]

From the above description, it follows that a sequence of two or more
         contiguous delimiter bytes in the parsed string is considered to be a
         single delimiter, and that delimiter bytes at the start or end of the
         string are ignored.

(Emphasis mine.)
Whenever your line starts with one or more ; characters, strtok will simply ignore them.
To solve this, you should instead search for the first occurrence of ; in the string, and if found, replace it by '\0' (the NUL terminator).
Variant 1 (using strchr / if):
char *p = strchr(str, ';');
if (p) {
    *p = '\0';
}
printf("%s\n", str);

Variant 2 (strcspn, cheeky):
str[strcspn(str, ";")] = '\0';
printf("%s\n", str);


text:
Q: How to load yaml string placeholders for python? I have a configuration file as config.yaml, that look like this

misc.application_title: "ATT"

data_dir: "${APP_DIR}/aux_data"

I have a function in app.py where it loads the config from yaml file. My question is how to load ${APP_DIR} as placeholder in the string.
I have to load string placeholders while loading yaml file itself.
Any leads will be appreciated .


text:
Q: columns from django.db.models.query.QuerySet With a raw query the columns for the SQL that will be executed can be accessed like this.
    query_set = Model.objects.raw('select * from table')
    query_set.columns

There is no columns attribute for django.db.models.query.QuerySet.
I'm not using raw ... I was debugging a normal query set using Q filters ... it was returning way too many records ... so I wrote code to see what the results would be with normal SQL. I'd like the see the columns and the actual SQL being called on a query set so I can diagnose what the issue is without guessing.
How do you get the columns or the SQL that will be executed from a django.db.models.query.QuerySet instance?

A: Ok, so based on your comment, if you want to see what django has created in terms of SQL there's an attribute you can use on the Queryset.
Once you've written your query, qs = MyModel.objects.all(), you can then inspect that by doing qs.query, which if you print that out will show you the SQL query itself.
You'll have to inspect this query to see what columns are being included.
The query object is a class called Query which I can't find mention of in the django docs, but it's source is here; https://github.com/django/django/blob/master/django/db/models/sql/query.py#L136


text:
Q: Compute the dimension of a sum of subspaces Let $V$ be the vector space of $2 \times 2$ matrices over $\mathbb F$. Let $W_1$ be the set of matrices of the form
$\begin{bmatrix}
x &−x \\
y & z
\end{bmatrix}$
and let $W_2$ be the set of matrices of the form
$\begin{bmatrix}
a &b \\
−a & c
\end{bmatrix}$. What is the dimension of $W_1+W_2$?
I found that the basis of $W_1$ and the basis of $W_2$ have size $3$, so $\dim W_1=\dim W_2=3$. I also found that the basis of $W_1 \cap W_2$ has size $2$, so $\dim(W_1 \cap W_2)=2$.
From this informatinon, how can I find the dimension of $W_1+W_2$ (without using the formula for the dimension of a sum)?
All I know so far is that $W_1+W_2$ is the smallest subspace that contains $W_1$ and $W_2$, and is contained in $V$. Since $\dim W_1=\dim W_2=3$ and $\dim V=4$, we must have $\dim(W_1+W_2)$ to be $3$ or $4$.
How do I know which one is it?
Source: Linear Algebra by Hoffman and Kunze - Exercise 7 of Section 2.3

A: The dimension is $4$, that is, $W_1+W_2$ consists of all the $2\times 2$ matrices. You can check directly that every matrix can be written as a sum of a matrix from $W_1$ and a matrix from $W_2$, for instance:
$$\begin{bmatrix}
x &y \\
z & t
\end{bmatrix}=\begin{bmatrix}
x &-x \\
z & t
\end{bmatrix}+ \begin{bmatrix}
0 & x+y \\
0 & 0
\end{bmatrix}$$

A: Alternatively, still without using the inclusion-exclusion dimension formula, note that $$W_1 = W_1 + \{0\} \subseteq W_1 + W_2.$$
If $\dim(W_1 + W_2) = 3 = \dim(W_1)$, then $W_1$ is a subspace of $W_1 + W_2$, but with the same dimension. This implies that $W_1 = W_1 + W_2$. A similar argument also shows that $W_2 = W_1 + W_2$. So, under this assumption, we have
$$W_1 = W_2.$$
This is very easy to disprove!


text:
Q: Auto increment numbers in div id javascript can somebody please help me?
How to add auto increment number in div ID using javascript?
I have four divs and I'd like to have them automatically numbered (box1, box2, box3, box4) in the ID by javascript.
Here's my code

A: set id property
var list = document.getElementsByClassName("something");
for (var i = 0; i < list.length; i++) {
    list[i].id = "box" + (i + 1);
}

A: There is an error in your code: <= should be only < if you are starting from 0!
One possible solution is to use the node.setAttribute("attributeName", "attributeValue") method in order to set / change the attribute (in this case the id) of an element:

A

B

C

D

The output is:

If it is alright to use JS libraries (for example jQuery), then the transformation could be written even more succinctly:
$(".something").each(function(index) {
    $(this).attr("id", this.id + index);
});

This code leads to the same output as above.
The commented jQuery code:
// find all elements with the class "something"
$(".something")
// call for each one of them
    .each(
// the function with parameter = current index
    function(index) {
// take the current element
    $(this)
// and set the attribute id to the new value
    .attr("id", this.id + index);
});


text:
Q: Building a Google Docs Clone with Supabase Realtime I'm looking to build an app similar to Google Docs in that it is collaborative and updates should reflect in realtime when another user makes changes to a document (row).
Right now, I have a useEffect that listens to changes of the document state and debounces the changes so that changes will only persist after 1 second, preventing unnecessary requests.
I'm wondering the best way to send instructions on how to change the json document to the database rather than sending a whole new copy of the data.
Also i'm not sure how google docs works but I've heard it communicates directly from client to client?
Is there an optimal way to create a google docs clone with Supabase?


text:
Q: How to send POST request? I found this script online:
import httplib, urllib
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
print response.status, response.reason
302 Found
data = response.read()
data
'Redirecting to http://bugs.python.org/issue12524'
conn.close()

But I don't understand how to use it with PHP or what everything inside the params variable is or how to use it. Can I please have a little help with trying to get this to work?

A: Your data dictionary conteines names of form input fields, you just keep on right their values to find results.
form view
Header configures browser to retrieve type of data you declare.
With requests library it's easy to send POST:
import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

More about Request object: https://requests.readthedocs.io/en/master/api/

A: If you really want to handle with HTTP using Python, I highly recommend Requests: HTTP for Humans. The POST quickstart adapted to your question is:
>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': '12524', 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>
Issue 12524: change httplib docs POST example - Python tracker

</title>
<link rel="shortcut i...
>>>

A: You can't achieve POST requests using urllib (only for GET), instead try using requests module, e.g.:
Example 1.0:
import requests

base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)

payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)

print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP

Example 1.2:
>>> import requests

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

Example 1.3:
>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))

A: If you don't want to use a module you have to install like requests, and your use case is very basic, then you can use urllib2
urllib2.urlopen(url, body)

See the documentation for urllib2 here: https://docs.python.org/2/library/urllib2.html.

A: Use requests library to GET, POST, PUT or DELETE by hitting a REST API endpoint. Pass the rest api endpoint url in url, payload(dict) in data and header/metadata in headers
import requests, json

url = "bugs.python.org"

payload = {"number": 12524,
           "type": "issue",
           "action": "show"}

header = {"Content-type": "application/x-www-form-urlencoded",
          "Accept": "text/plain"}

response_decoded_json = requests.post(url, data=payload, headers=header)
response_json = response_decoded_json.json()

print(response_json)

A: You can use the request library to make a post request.
If you have a JSON string in the payload you can use json.dumps(payload) which is the expected form of payload.

    import requests, json
    url = "http://bugs.python.org/test"
    payload={
        "data1":1234,'data2':'test'
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    print(response.text , response.status_code)

A: This is a solution without any external pip dependencies, but works only in Python 3+ (Python 2 won't work):
from urllib.parse import urlencode
from urllib.request import Request, urlopen

url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'}     # Set POST fields here

request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)

Sample output:
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "foo": "bar"
  },
  "headers": {
    "Accept-Encoding": "identity",
    "Content-Length": "7",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "Python-urllib/3.3"
  },
  "json": null,
  "origin": "127.0.0.1",
  "url": "https://httpbin.org/post"
}


text:
Q: Number of errors that can be detected with a single-bit even parity code word system? How many errors can a transmission system which uses code words with 7 data bits and a single parity bit (Checking for Even parity) detect at the receiving end.
While I am aware of the fact that any odd number of errors can be detected with this kind of a system, what exactly would be the answer? Or is the answer just one?
Ps. I'm not sure if this is the right Stack site to post this question. Do let me know if it isn't.

A: I'm not sure exactly what you're asking.  If you fail a parity check, you are assured that there is at least one bit of the 8 in error (it may be the parity bit).  There may be 3, but you have no way of distinguishing the two results.  Further, if you have an even number of errors, they will result in no detected error at all.
No matter what, you have no indication which bit is in error, so parity is useless for any error correction.
Parity is generally used in systems which are reliable enough that the probability of having more than one error in N bits (N=8 in this example) is considered negligible.

A: A single parity bit within an 8-bit field allows 50 % of field bit errors to be detected. Of its 256 possible values, 128 (50 %) of them have valid parity and 128 have invalid parity.
Parity on your 7-bit value does not let you specifically detect errors in the actual value, only that the overall field's bit pattern is invalid.

A: We can see the parity bit as a simple checksum. No checksum system, included the parity, can assure the received datum is correct. These system can however reduce the possibility of taking bad data as good, which is totally different.
Let's start talking about a one byte checksum. For every datum (a packet) you receive, you have 256 possible values for the checksum, and of those 256, only one is correct. So, 255 among 256 possible errors are detected. That's no bad.
If now we go to the parity bit, we have only two possible values for the checksum: 0 and 1. So we can detect 1 error among 2.
The bottom line is this, I think: we can not speak about "how many errors can we detect?", instead we can speak about "how much we improve the error detection?". Using no parity bit, there is no error detection; using a single bit of checksum (a parity) we [can potentially] detect 50% of the errors. Depending on which side we look at the question, either we doubled the quality (because we halved the probability of undetected errors), or we have made an infinite step ahead.
Last thought: the parity bit protects every single byte transmitted on a serial line. Often a meaningful message is made of several bytes; if we invalidate the whole message as soon as any single byte fails the parity, then every byte in the message doubles the quality of the error detection.


text:
Q: How to output label with icon in line? Text of the label jumps on a next line when I use setIcon(). How to output it in one line?
Label info = new Label("Reports are generated every day at 5 pm", ContentMode.HTML);
info.setIcon( new ThemeResource("img/icons/information.png") ) ;
info.setSizeUndefined();
JobsLayout.addComponent( info );
JobsLayout.setComponentAlignment(info, Alignment.MIDDLE_RIGHT);

A: You can use icon inside label text:
Label date = new Label(FontAwesome.CALENDAR.getHtml() + " " + new Date());
date.setContentMode(ContentMode.HTML);

Source: Vaadin Wiki.
Result:

A: You should try this:
info.addStyleName("line");

with this CSS:
.v-caption-line {
    display: inline !important;
}

A: I had the same problem and used the following "solution" at the end. The advantage is if you use multiple labels on below each other they have the same space between icon and text.
Vaadin Code
Button label = new Button("Your label text here.");
label.setIcon(FontAwesome.USER);
label.addStyleName(ValoTheme.BUTTON_BORDERLESS + " labelButton");

CSS Code
.labelButton:after, .labelButton:active {
    content: none;
    border: none;
    color: #000000;
}

.labelButton {
    cursor: default;
}

A: It might be the label as well, you can try some inline CSS since you have specified your content type to HTML anyway, it should be something like this:
Label info = new Label("Reports are generated every day at 5 pm", ContentMode.HTML);
If that didn't work, try doing the same thing with the div associated with the label - or - you can inject your icon with the inline CSS within the span.


text:
Q: How to prevent an element from adding a class dynamically in asp menu? I have spent hours to solve this problem,but i didn't succeed. I am developing asp menu for the first time. Everything is fine,but when I hover the Menu item .highlighted css class gets added dynamically to the corresponding element.
Here is my code:
<asp:Menu ID="Menu1" runat="server" StaticDisplayLevels="1" StaticSubMenuIndent="10" Orientation="horizontal" RenderingMode="List" CssClass="MenuClass">
 <Items>
       <asp:MenuItem Text="Dashboard" Target="" Value="Dashboard">
             <asp:MenuItem Text="Tasks" Value="Tasks"></asp:MenuItem>
              <asp:MenuItem Text="Call Backs" Value="Call Backs"></asp:MenuItem>
       </asp:MenuItem>

       <asp:MenuItem Text="Application" Value="Application">
              <asp:MenuItem Text="New" Value="New"></asp:MenuItem>
              <asp:MenuItem Text="View" Value="View"></asp:MenuItem>
       </asp:MenuItem>
 </Items>
</asp:Menu>

This asp:menu in the webpage it is rendered as UL(unordered list) and LI(lists).
For the above code the html format rendered in the webpage is as follows:

          Dashboard

              corresponding lists:  TASKS and CALLBACKS

        Viceversa the ul and li for the Application MENUITEM are rendered as html

In this what I need is, When I hover the menu Dashboard the sub menuitems Tasks and Call Backs will be shown, because the style for the UL with the class level2 dynamic changes to display:block.
At the same time, a class named as highlighted is added dymanically to the  tag and the class name becomes class="popout level1 static highlighted" and  also automatically by the asp:menu functionality.
When the mouse leaves the Dashboard menu the added highlighted class gets removed dynamically and automatically.
I didn't know how the highlighted class gets added into the  tag.
My problem is to stop adding the highlighted class dynamically into the  tag, because I need to keep the style for the corresponding ul tag in the level2 as display:block.
When highlighted class is added, the style for the ul with the class name*level2 dynamic*
changes into display:block. But when the mouse leaves from the menu, it becomes as display:none.
In my project I have to keep the selected menu and its submenu as display:block until the another menu is clicked.
I have used JQUERY to make the submenus to be display:block for the selected menu.
I need to know how to stop or prevent adding the highlighted class to the a tag.
I think we can achieve it through jquery.
 $(document).ready(function () {

    if ($(".popout").hasClass("selected")) {
         $("a.popout.level1.selected.static").next("ul").css("display", "block");
    }

    if ($(".popout").hasClass("highlighted")) {
         $("a.popout.level1.selected.static.highlighted").next("ul").css("display","block");
    }

     $("a.popout.level1.selected.static.hihglighted").mouseout(function () {
                $("a.popout.level1.selected.static.highlighted").next("ul").css("display", "block");
                $("a.popout.level1.selected.static").next("ul").css("display","block");
                if ($("a.popout.level1.selected.static.highlighted").next("ul").css("display", "none")) {
                    $(".test").css("display", "block");
                }
            });
});

Here when the mouse leaves the menu, the highlighted class removed dynamically the css for the ul gets automatically as display:none, even as I had set it to be display:block it fails to be block. It displays none. So the addition of highlighted class is the worry on this case.
SO I have to stop the addition of the highlighted class to the anchor tag, so that the style will not be changed.
The adding of highlighted class didn't make any worries, but if it removes, the ul style becomes as display:none. I don't know why...?
Please help me on these issues..
Thanks in advance...:)

A: I have done this simple animation with that code :
        $("ul.level1 li a").mouseenter(function () {
            var ulhight = $(this).next("ul").height();
            $(this).next("ul").css({  "height": "0px", "overflow": "hidden" });
            $(this).next("ul").animate({ height: ulhight }, 300)
        })


text:
Q: Moving certain data to a new data set I am trying to move specific words from one data set to another in R. I have used the below code:
treatmentWords <- select(filter(m4, m4$word == 'CHLOROQUINE'),c(index,word))

But this returns an empty data set. The complete data set is currently in m4 with and index and word column. Basically I want the data set that looks like this
m4
Index   Word
1       CHLOROQUINE
2       SHOT
3       CHLOROQUINE
4       SHOT

to use a filter or select command to now have the below in treatmentWords:
treatmentWords
Index   Word
1       CHLOROQUINE
3       CHLOROQUINE

Any help is welcome!

A: My preferred method is:
m4[m4$Word == "CHLOROQUINE",]
  Index        Word
1     1 CHLOROQUINE
3     3 CHLOROQUINE

Another popular method from Base R is subset. It takes less typing usually:
subset(m4, Word == "CHLOROQUINE")
  Index        Word
1     1 CHLOROQUINE
3     3 CHLOROQUINE

But I see you are also using filter, which usually comes from dplyr. So you could do this:
library(dplyr)
m4 %>%
  filter(Word == "CHLOROQUINE")
  Index        Word
1     1 CHLOROQUINE
2     3 CHLOROQUINE

If you want to assign the results to treatmentWords:
treatmentWords <- m4[m4$Word == "CHLOROQUINE",]


text:
Q: Visual Studio 2017 Indent Guide Coloring In Visual Studio 2015, I had coloring for the indent guides like this.
I can't seem to find this feature in Visual Studio 2017.  Is there an extension that does this?
There's an option in the Fonts and Colors to change the color for all Guidelines.  But what I want is the same in 2015 where it's automatically color coded (blue, green, teal, purple, etc.) depending on the type/level of the braces.

A: Native in VS2017. It's called "Structure Guide Lines"

A: There is no such feature built into VS2015. It is added by extensions.
Eg. the "Structure Visualiser" from Productivity Power Tools.
However for 2017 there is a (lesser) feature built in, so the Productivity PowerTools 2017 does not include this feature. (It is now also a set of separate extentions rather than a monolithic tool.)
This is explained in a blog post see section What's Missing?

A: There is also an excellent extension for Visual Studio 2015 called Indent Guides that is working really well.
It is not compatible with VS2017 by default, but you can get around that by modifying the extension manifest file within the vsix file:
1) Download IndentGuide v14.vsix for VS2015
2) Use 7-zip (or other archive utility) to open the .vsix file (which is actually a .zip)
3) Edit the extension.vsixmanifest file within the .vsix file
4) Make a copy of the whole VisualStudio Version="14.0" section
5) Change that new copy to VisualStudio Version="15.0"
6) Save the manifest, save the vsix.
7) Double-click the .vsix file to install it.  Ignore the compatibility warning.

A: This really should be a comment, but as I do not have enough reputation to make it, an "answer" it is.
A uservoice was added to solicit feedback on missing features of the current Structure Visualizer added to VS2017. If you have an interest in seeing these features restored, please vote.
Improve the Structure Visualizer in Visual Studio 2017

A: I think this is just what you want.This is that extension called "Indent Guides".
The number behind the '#' on behalf of the different level of the Indent Guides.
I know my answer looks terrible. Please forgive me. As a new one here, i really try my best.

A: In the German Version of VS2017 Enterprise the setting your looking for is called "Strukturführungslinien" in Options / Environment / Fonts and Colors. I would translate it with "structurelines".


text:
Q: Mocha - hooks in separate files I am trying to put methods beforeEach and afterEach to a separate files because I will use them a lot.
I can not find a way to do this & will work. Can you help me out?
This is my working code:
describe('something', function () {
  beforeEach(function () {
    console.log('beforeEach');
  });

  afterEach(function () {
    console.log('afterEach');
  });

  it(...);
});


text:
Q: Increase MySQL max_connection on Lightsail (not RDS) database I have a database created in Lightsail (not RDS, just Lightsail>Databases>Create database). I am trying to increase its max_connections number from 150 to 500 by connecting to it remotely, but I am getting the following error:
Access denied; you need (at least one of) the SUPER or SYSTEM_VARIABLES_ADMIN privilege(s) for this operation

Is there a way for me to achieve this on Lightsail?
Database instance info:
High availability MySQL database (8.0.11)
2 GB RAM
1 vCPU
80 GB SSD

A: It sound like you are attempting to set the parameter through SQL?
For lightsail databases, you need to follow these instructions and use AWS CLI: https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-updating-database-parameters
(if I'm wrong, please let us know what command you are running to generate the error you are seeing above)

A: AWS RDS and lighsail wil automatically inject your proper amount of max_connections based on your memory installed.  With 2 gigs, you get around 66*2=132
It will just overwhelm even RDS if you make too many connections, as they require more RAM for each one.
"parameterName": "max_connections",
"parameterValue": "{DBInstanceClassMemory/12582880}"

mysql> show variables like "max_connections";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 66    |
+-----------------+-------+

# pip3 install awscli --upgrade --user
# .local/bin/aws lightsail get-relational-database-parameters --relational-database-name <your given name>
# .local/bin/aws lightsail update-relational-database-parameters --relational-database-name <your given name> --parameters "parameterName=explicit_defaults_for_timestamp,parameterValue=0,applyMethod=pending-reboot"

which is required for MySQL 5.7
OR for your situation
# .local/bin/aws lightsail update-relational-database-parameters --relational-database-name <your given name> --parameters "parameterName=max_connections,parameterValue=500,applyMethod=pending-reboot"

If your region is us-west-2a, then remove the "a" from the .aws/config
[default]
region = us-west-2
output = json


text:
Q: strange character at the top right of the page I found a kind of x symbol at the top right of the page: https://www.tothetoptogether.it/iscriviti/
How can I solve?

A: Welcome on Stack Overflow! I encourage you to write as many details as you can in your questions, so that other users can help you in the best possible way. As for the question, I think it's just a typo. Inspecting the source code of the page, I find x seems to be a "lost" character:

If you have access to the source code of the page, deleting it will solve your problem.


text:
Q: Conservation of Energy in Double Slit Experiment How is energy conserved In Young's Double Slit Experiment ?
In destructive interference , energy is lost .
So what happens to that lost energy ?
Does it escape as heat ?

A: I think your confusion is assuming that the energy of two waves add, when in reality there is an interference term.
The short, physics-y answer is that it is not that any energy has disappeared, rather the interference has caused some of the energy that 'would have been there' to show up in a different place. The energy got shifted but not destroyed.
This can be backed up with some math. Let's say we have an electromagenetic wave
\begin{equation}
\vec{E}_1(\vec{x},t)=\vec{\mathcal{E}}_1 \cos(\vec{k}\cdot\vec{x} - \omega t)
\end{equation}
where $\vec{\mathcal{E}}_1$ is a constant. Note $B=\frac{1}{c}\vec{k} \times \vec{E}$. I will suppose that I can neglect the magnetic field term in the energy below, to simplify things.
The energy is
\begin{equation}
U_1 = \frac{1}{2}\vec{E}^2 = \vec{E}_1^2 \cos^2(\vec{k}\cdot \vec{x} - \omega t)
\end{equation}
Now let's add a second wave
\begin{equation}
\vec{E}_2(\vec{x},t)=\vec{\mathcal{E}}_2 \cos(\vec{k}\cdot\vec{x} - \omega t+\phi)
\end{equation}
For simplicity let's suppose that the wavenumber and frequency is the same, the only difference is the phase $\phi$.
Now, you might have thought that the energy is $U=U_1+U_2$. However this is not true! The energy is really
\begin{equation}
U=\frac{1}{2}\left(\mathcal{E}_1^2 \cos^2(\vec{k}\cdot\vec{x}-\omega t) + \mathcal{E}_2^2 \cos^2\left(\vec{k}\cdot\vec{x}-\omega t + \phi\right)+2\mathcal{E}_1\mathcal{E}_2 \cos(\vec{k}\cdot \vec{x}-\omega t)\cos(\vec{k}\cdot\vec{x}-\omega t + \phi)\right)
\end{equation}
The last term above is the counterintuitive term that 'shifts the energy around.'
Finally, to be pedantic I should point out that above I am really talking about the energy density. The true, total energy is the integral of the energy density, and is not sensitive to these kinds of interference effects. In particular, (at least in electromagnetism), the total energy of the two waves is the same as the sum of the energy of each individual wave (the interference term will integrate to zero). Thus interference will shift the energy density around, but will leave the total energy unchanged.


text:
Q: R: populating and/or duplicating rows based upon other columns My question is based upon this question.
I have a data as below. I want to fill cells by first looking down and then by looking up as long as the bom is same. In case of bom=A, I want to fill up rows as shown. But in case of bom=B, as the type_p column is different, I want to duplicate rows and feel the blanks
bom=c(rep("A",4),rep("B",3))
Part=c("","lambda","beta","","tim","tom","")
type_p=c("","sub","sub","","sub","pan","")
ww=c(1,2,3,4,1,2,3)
df=data.frame(bom,Part,type_p,ww)

> df
  bom   Part type_p ww
1   A                1
2   A lambda    sub  2
3   A   beta    sub  3
4   A                4
5   B    tim    sub  1
6   B    tom    pan  2
7   B                3

The final data that I want is as below
    bom Part    type_p  ww
1   A   lambda  sub      1
2   A   lambda  sub      2
3   A   beta    sub      3
4   A   beta    sub      4
5   B   tim     sub      1
6   B   tim     sub      2
7   B   tim     sub      3
5   B   tom     pan      1
6   B   tom     pan      2
7   B   tom     pan      3

________________________________________Update 1
The logic that I want is as below. Please remember that my data is very huge and I have thousands of values in each column.
bom and ww columns are always populated/filled in incoming data

*

*Check if an entry in column bom has more than 1 value in the column type_p

*If there is only 1 value then fill blanks in type_p and ww columns by first looking down and then looking up. In this case bom=A has only one value in type_p (sub)

*If an entry in column bom has more than 1 unique value in type_p column then create additional sets of the same rows of that bom such that total sets will  be equal to distinct values in type_p column for that bom. In this case bom=B has two values in type_p (sub and pan)

*Fill blanks in type_p and ww columns by first looking down and then looking up (look at the source row to fill up values)

===========================================================Update 2
After step 3, the data frame would look like below
> df
   bom   Part type_p ww
1    A lambda    sub  1
2    A lambda    sub  2
3    A   beta    sub  3
4    A   beta    sub  4
5    B    tim    sub  1
6    B                2
7    B                3
8    B                1
9    B    tom    pan  2
10   B                3

A: With tidyr and dplyr, you could manage to do something near what you aim
library(tidyr)
library(dplyr)
# replacing empty string with NA
df <- df %>% mutate_each(funs(sub("^$", NA, .)), Part, type_p)
# filling missing values
df <- df %>% fill(Part, type_p,.direction = "down") %>% fill(Part, type_p,.direction = "up")

df
#>   bom   Part type_p ww
#> 1   A lambda    sub  1
#> 2   A lambda    sub  2
#> 3   A   beta    sub  3
#> 4   A   beta    sub  4
#> 5   B    tim    sub  1
#> 6   B    tom    pan  2
#> 7   B    tom    pan  3

To obtain what you described (in question and comment), you could treat BOM A & B separately:
bind_rows(
  df %>% filter(bom == "A"),
  df %>% filter(bom == "B") %>%
    complete(nesting(bom, Part, type_p), ww)
)
#> Source: local data frame [10 x 4]
#>
#>       bom   Part type_p    ww
#>    (fctr)  (chr)  (chr) (dbl)
#> 1       A lambda    sub     1
#> 2       A lambda    sub     2
#> 3       A   beta    sub     3
#> 4       A   beta    sub     4
#> 5       B    tim    sub     1
#> 6       B    tim    sub     2
#> 7       B    tim    sub     3
#> 8       B    tom    pan     1
#> 9       B    tom    pan     2
#> 10      B    tom    pan     3


text:
Q: Linux send unicode character to active application Ok, so I'm trying to develop an app using C++ and Qt4 for Linux that will map certain key sequences to special Unicode characters. Also, I'm trying to make it bilingual, so the special Unicode character sent depends on the selected language. Example: AltGr+s will send ß or ș, depending whether German or Romanian is selected. On Windows, I have achieved this using AutoHotKey. However, I couldn't get IronAHK to work on Linux so I have written myself a nice Qt Application for it, using Qxt to register "global" shortcuts. I have tried this snippet:
void mainWnd::sendKeypress( unsigned int keycode )
{
    Display *display = QX11Info::display();
    Window curr_focus;
    int revert_to;

    XGetInputFocus( display, &curr_focus, &revert_to );

    XTestFakeKeyEvent( display, keycode, true,  0 );
    XTestFakeKeyEvent( display, keycode, false, 1 );

    XFlush( display );
}

copied from another application(where it works), but here it seems to do nothing. Also, there might be a problem with the fact that the characters I'm trying to send aren't found on a US 101 Keyboard, that I currently use on my laptop(and as the layout in the OS).
So my question is: how do I make the app send a Unicode character to whichever app has focus, inserting a special character(sort of like KCharMap)? Remember, these are special characters which are not found on a normal US Keyboard. Thanks in advance.


text:
Q: If I don't want the points, can I make my answers "community wiki"?
Possible Duplicate:
What is community wiki for?

I get too many votes for weaker or viral answers and too few for hard worked ones. Can I make community wiki those answers that I do not want votes (therefore points) for?

A: You could use CW in such cases, but bear in mind that it would make the answer editable also by users with a reputation of at least 100 (and not 2000 as the usual). This means that a user with a reputation of at least 100 points would be able to edit your answer without passing through a suggested edit that is then approved by another user.

A: Why not take the points and put them to good use by placing a bounty on a hard question?


text:
Q: C# - Finding my machine's local IP Address and not the VM's I have a VirtualBox VM installed on my machine and as such there is an ethernet adapter that appears for it. I'm enumerating through the list of my machine's IP address via the following:
       public string GetLocalIpAddress()
       {
            try
            {
                string strHostName = Dns.GetHostName();

                // Then using host name, get the IP address list..
                IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);

                foreach (IPAddress ip in ipEntry.AddressList)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        return string.Format("({0})", ip.ToString());
                    }
                }
            }
            catch(Exception e)
            {
                Global.ApplicationLog.AddApplicationLog(EnumAppEventTypes.SYSTEM_ERROR, e.ToString());
            }

            return "";
        }

My problem is that the virtual machine's ethernet adapter also catches on the condition:
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)

Is there a way of picking out my machine's local ip address and disregarding my virtual machine's?

A: Use WMI and check ConnectorPresent property for physical device.
public static string GetPhysicalIPAdress()
{
    foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (ConnectorPresent(ni))
        {
            if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
            {
                foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
                {
                    if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        return ip.Address.ToString();
                    }
                }
            }
        }
    }
    return string.Empty;
}

private static bool ConnectorPresent(NetworkInterface ni)
{
    ManagementScope scope = new ManagementScope(@"\\localhost\root\StandardCimv2");
    ObjectQuery query = new ObjectQuery(String.Format(
        @"SELECT * FROM MSFT_NetAdapter WHERE ConnectorPresent = True AND DeviceID = '{0}'", ni.Id));
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    ManagementObjectCollection result = searcher.Get();
    return result.Count > 0;
}

A: There is one option. VM IP don't have Default Gateway, so, exclude all IP's without Default Gateway.
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
    var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
    if (addr != null)
    {
        if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
        {
            Console.WriteLine(ni.Name);
            foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
            {
                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    Console.WriteLine(ip.Address.ToString());
                }
            }
        }
    }
}

A: You can disregard the Ethernet adapter by its name. As the VM Ethernet adapter is represented by a valid NIC driver, it is fully equivalent to the physical NIC of your machine from the OS's point of view.

A: I'm refining Andrej Arh's answer, as the IP Address reported by GatewayAddresses can also be "0.0.0.0" instead of just null:
    public static string GetPhysicalIPAdress()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
            if (addr != null && !addr.Address.ToString().Equals("0.0.0.0"))
            {
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            return ip.Address.ToString();
                        }
                    }
                }
            }
        }
        return String.Empty;
    }


text:
Q: Complicated counting in excel I have the following columns in Excel
    a    b    c
 1 SUM  1st  2nd
 2 0    2/2  2/4
 3 0    1/1  3/4

b2 is defined as "=CONCATENATE(TRUNC(2);"/";TEXT(('Other sheet'!B2);0))"
and similar to b3,c2,c3.
Column |SUM| should count sum from |1st| to |2nd| but only the first numbers before "/".
for example: b2+c3+... = 2+2+... = 4+... so a2=4+...
any ideas how to do that? :)

A: You can use the 'left' function
Use it like this
A2=left(B2;1)+left(C2;1)

A: Use the below formula with feature shift+ctrl+enter:
=SUM(TRUNC(MID(B2:C2,1,SEARCH("/",B2:C2,1)-1)))

A: Here's a simple way to do it
=SUMPRODUCT(INT(SUBSTITUTE(B2:C2,"/",".")))

Extend your range as far as you need by changing B2:C2 to B2:X2, for example.

I think this might work for your system.

=SUMA.ILOCZYNÓW(ZAOKR.DO.CAŁK(PODSTAW(B2:C2;"/";".")))


text:
Q: Row details panel Is it possible to have row details open on click? like below closed/open state:

A: Yes, you can. Check the documentation here on how you can do this, along with how to custom implement it here.


text:
Q: Oracle SQL - Grouping multiple medical claims into one event I'm trying to group multiple medical claims into one event, or inpatient stay.  To keep this simple, let's say I have a patient who goes to the hospital on 1/1/2017, is released on 1/5/2017, and is transferred to another hospital on that same day, and is released from that other hospital on 1/10/2017.
So I have two claims, one with an admit date of 1/1/2017 and discharge date of 1/5/2017, and the other claim has an admit date of 1/5/2017 and discharge date of 1/10/2017.  Because one starts right after the other, it is considered one inpatient stay.
In Oracle, I would like to combine that into one line, with an admit date of 1/1/2017, and a discharge date of 1/10/2017, based on the fact that the one claim has a discharge date of 1/5/2017, and the second claim has an admit date on that same date.
Any help on which direction to go into would be greatly appreciated.
UPDATE:  Please see the sample data below:
  CLAIM_ID   MEME_RECORD_NO  ADMIT_DATE      DISCHARGE_DATE
        1            127300   1/3/2017       1/11/2017
        2            127300  1/12/2017       1/20/2017
        3            180100   1/3/2017        1/6/2017
        4            180100   1/6/2017       1/20/2017
        5            265700   1/2/2017        1/5/2017
        6            265700   1/5/2017       1/17/2017
        7            300000   2/1/2017        2/5/2017
        8            300000   2/5/2017        2/9/2017
        9            300000   2/9/2017       2/12/2017

CLAIM_ID 1 and 2 are separate events, since the ADMIT_DATE for CLAIM_ID 2 is greater than the discharge date for CLAIM_ID 1 (even though they're the same patient), CLAIM_ID 3 and CLAIM_ID 4 combined is one event, since the discharge date for CLAIM_ID 3 is the same as the ADMIT_DATE for CLAIM_ID 4, and the scenario repeats itself for CLAIM_ID's 5 and 6.  For CLAIM_ID'S 7, 8 and 9, this is also one event, so all 3 would be combined.  In addition to actually grouping them, I would also like to number the rows with an EVENT_ID field
Assuming the above were a table, and I queried it, the output should be 5 events.  The final product should look like this:
EVENT_ID       MEME_RECORD_NO  ADMIT_DATE      DISCHARGE_DATE
    1                127300     1/3/2017       1/11/2017
    2                127300    1/12/2017       1/20/2017
    3                180100     1/3/2017       1/20/2017
    4                265700     1/2/2017       1/17/2017
    5                300000     2/1/2017       2/12/2017

I really appreciate any help on this.


text:
Q: React Native TextInput displays only part of text Using this simple code (see runnable snack)
import * as React from 'react';
import { Text, View, StyleSheet, TextInput } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
 return (
   <View style={styles.container}>
     <TextInput style={styles.paragraph} value={'ios-only! abc-def 242343535325342534523'} />
     <TextInput style={styles.paragraph} value={'ios-only! abc-def 242343535325342534523'} />
   </View>
 );
}

const styles = StyleSheet.create({
 container: {
   flex: 1,
   paddingTop: Constants.statusBarHeight,
   backgroundColor: '#ecf0f1',
   padding: 8,
 },
 paragraph: {
   margin: 24,
   fontSize: 18,
   textAlign: 'left',
   backgroundColor: 'green',
 },
});

I obtain this: You see that part of the text is not visible in the textinput, but becomes visible when I place cursor into the textinput.
Is there some way to display full text content in textinput (and cut it off when it goes offscreen)? Thanks!


text:
Q: is there is any stemmer available for indian language is there is any implementation of stemmers for indian languages like(hindi,telugu) are available ....

A: Hindi Analyzer, with stemmer, is available in Lucene. It is based on this algorithm(pdf).

A: hindi_stemmer is a Python implementation of the Hindi stemmer described in "A Lightweight Stemmer for Hindi" by Ananthakrishnan Ramanathan and Durgesh D Rao.

A: We created a java version of original code Python Hindi Stemmer
Although the way authors of original Hindi stemmer used variable L is not well understood but there is a complete code what would work
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
public class SimpleHindiStemmer {

/* This is not coming while pasting the code better copy from Python Code as given in suffixes[1]  */
private static String [] stem1 = new String [] { "ो", "े", "ू", "ु", "ी", "ि", "ा" };

/* This is not coming while pasting the code better copy from Python Code as given in suffixes[2]  */
private static String [] stem2 = new String [] { "कर", "ाओ", "िए", "ाई", "ाए", "ने", "नी", "ना", "ते", "ीं", "ती", "ता", "ाँ", "ां", "ों", "ें" };

private static String [] stem3 = new String [] { "ाकर", "ाइए", "ाईं", "ाया", "ेगी", "ेगा", "ोगी", "ोगे", "ाने", "ाना", "ाते", "ाती", "ाता", "तीं", "ाओं", "ाएं", "ुओं", "ुएं", "ुआं" };

private static String [] stem4 = new String [] { "ाएगी", "ाएगा", "ाओगी", "ाओगे", "एंगी", "ेंगी", "एंगे", "ेंगे", "ूंगी", "ूंगा", "ातीं", "नाओं", "नाएं", "ताओं", "ताएं", "ियाँ", "ियों", "ियां" };

private static String [] stem5 = new String [] { "ाएंगी", "ाएंगे", "ाऊंगी", "ाऊंगा", "ाइयाँ", "ाइयों", "ाइयां" };

private static ArrayList<String []> stemList = new ArrayList<String []>(5);

static int [] cut = new int [] { 0, 1, 1, 1, 2, 2 };

static {

    stemList.add(stem5);
    stemList.add(stem4);
    stemList.add(stem3);
    stemList.add(stem2);
    stemList.add(stem1);

}

public SimpleHindiStemmer(){

}

public static void main(String [] argv){

    SimpleHindiStemmer sm = new SimpleHindiStemmer();
    String word = "रास्ते";
    System.out.println(sm.stemprocess(word));
}

public String stemprocess(String word){

    int wlen = word.length();
    int wordlen = wlen*3;
    int icnt = 5;
    for (String [] stemwords : stemList){
        if(wordlen > (icnt + 1)){
            for(String sw: stemwords){
                if(StringUtils.endsWith(word, sw)){
                    return StringUtils.substring(word, 0, wlen - cut[icnt]);

                }
            }

        }

        icnt--;
    }

    return word;
}
}

As you see utf-8 chars in some cases are not well captured . Look at original python code and just copy suffixes values from there.

A: import java.util.Map;
import java.util.WeakHashMap;

/**
 * Hindi light stemmer- removes number, gender and case suffixes from nouns and adjectives
public class HindiStemmerLight{

/**
 * A cache of words and their stems
 */
static private Map<String, String> cache = new WeakHashMap<String, String>();

/**
 * A buffer of the current word being stemmed
 */
private StringBuilder sb = new StringBuilder();

/**
 * Default constructor
 */
public HindiStemmerLight() {
}

public String stem(String word) {
    String result = cache.get(word);

    if (result != null)
        return result;

    //
    sb.delete(0, sb.length());

    //
    sb.append(word);

    /* remove the case endings from nouns and adjectives */
    remove_suffix(sb);

    result = sb.toString();
    cache.put(word, result);

    return result;
}

private void remove_suffix(StringBuilder word) {
    int len = word.length() - 1;

    /* article */

    if (len > 4) {
        if (word.substring( len- 2, len+1).equals("िया")) {
            word.delete(len-2 , len + 1);
            return;
        }
        if (word.substring( len- 2, len+1).equals("ियो")) {
            word.delete(len-2 , len + 1);
            return;
        }

    } /* end if len >4 */
    if (len > 3) {
        if (word.substring(len-1, len+1).equals("ाए")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals(" ाओ")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals(" ुआ")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals(" ुओ")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring( len- 1, len+1).equals("ये")) {
            word.delete(len-1 , len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals(" ेन")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals(" ेण")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring( len- 1, len+1).equals(" ीय")) {
            word.delete(len-1 , len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals("टी")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals("ार")) {
            word.delete(len - 1, len + 1);
            return;
        }
        if (word.substring(len-1, len+1).equals("ाई")) {
            word.delete(len - 1, len + 1);
            return;
        }

    } /* end if len > 3 */
    if (len > 2) {
        if (word.substring(len, len+1).equals(" ा")) {
            word.delete(len , len + 1);
            return;
        }
        if (word.substring(len, len+1).equals(" े")) {
            word.delete(len , len + 1);
            return;
        }
        if (word.substring(len, len+1).equals(" ी")) {
            word.delete(len , len + 1);
            return;
        }
        if (word.substring(len, len+1).equals(" ो")) {
            word.delete(len , len + 1);
            return;
        }
        if (word.substring(len, len+1).equals("ि ")) {
            word.delete(len , len + 1);
            return;
        }
        if (word.substring(len, len+1).equals("अ")) {
            word.delete(len , len + 1);
            return;
        }

    } /* end if len > 2 */
    return;
}

}


text:
Q: How do I calculate the time complexity of a nested 'for' loop? Consider:
def fun(n):

    for i in range(1, n+1):
        for j in range(1, n, i):
            print (i, ",", j)

I'm having trouble with the nested for loop. Is it 2n^2 + 2n + 1?

A: The inner loop runs from 1 (inclusive) to n (exclusive) in hops of i. That thus means that it will make (n-1)//i steps.
The outer loop makes n runs where i ranges from 1 to n. We can slighlty overestimate the total number of steps by calculating the number of steps as a sum:
 n                    n
---                  ---
\     n-1            \    1
/     ---    = n-1 * /   ---
---    i             ---  i
i=1                  i=1

We can here use the Stirling approximation: we know that the integral if 1/i will be between the sum of 1/(i+1) and 1/i.
The integral of 1/i, so we approximate this as:
 n         n
---        /\
\    1     |    1
/   ---  ≈ |   --- dx  = log(n) - log(1)
---  i    \/    x
i=1        1
So that means that the total number of steps is, in terms of big oh O(n log n).

A: The complexity of your code is O(n log n). Inside the first for loop, the complexity is O(n/i) which in total we have:
O(n/1) + O(n/2) + ...+ O(n/i)+...+O(1)

Is equal to:
n O( 1 + 1/2 + ... + 1/n ) = n O(log(n)) = O(n log(n))


text:
Q: HTTPS GET API call using base64 encoding I am trying to make an HTTP GET API call to one of my server, which support HTTP basic authentication using an API key in base64 encoding. so basically I want to add my authorization header in base64 encoding to my request.
The one method of authorization I know is:
>>> import requests
>>> r = requests.get('https://test.com/test-API-Gateway/v0/deployments', auth=('user', 'password'), verify=False)).text

>>> print r
{"statusCode":401,"statusMsg":Unauthorized,"result":[]}

But my server does not return anything, since it does not take id and password for authentication, rather it needs the base64 encoding header. Can you please tell me how to achieve this?
Thanks in advance.

A: The Python Requests library does allow you to add custom headers. You should be able to create the appropriate header (with your base64 encoding) and pass it as a parameter, like so:
import requests
url = 'https://test.com/test-API-Gateway/v0/deployments'
myheaders = {'my-header-param': 'somedata'}
r = requests.get(url, headers=myheaders, verify=False)).text

The related documentation can be found here.


text:
Q: Referrer URL in case if the link was clicked from email I have a user registration process in which I send an email to the user for email verfication and to activate their account. Now when the activate link from the email is clicked, How do I get the referrer that tells me whether or not the user came to the page by clicking the link from the email?

A: Before you generate the email, you generate a unique token for that user. Then you'd append that token to the URL, and the page that does the verification checks the username and the verification token. If they match, then the user has verified their email.
For example, your email would contain a link to http://www.example.com/process.php?user=foo&validate_token=bar. Then your process.php page would check to make sure that the foo user's validation token is actually bar. If it is, then the user foo has had their email address validated.

A: You'll need to generate some type of id and store it in a database along with the user info. When the user click on the link, it will have the unique id appended to it like:
http://www.mygreatsite.com/verify?user=username&id=1234

You'll check the id against any existing id's in the db and if it's a match, allow them in

A: You can't trust referrers in any way. There are a lot of private browsing plugins and other things that will prevent the referrer from being passed in correctly.

A: The issue with an email link for registrations, regardless of the token, is that, if you access your db immediately upon activation of the link it is easy enough for some tedious person to create a Denial of Service issue. Simple solution I have designed: check ip address, relocate to different servers based on ip address (aka dump all, or most, of the trouble makers into one location to sort through) and then present  a form to click (or a recapture) to finalise registration before you go anywhere near your db. Not enough by itself but is a handy additional series of walls to add to your other security measures to prevent dns attacks from simulated 'registration' links. Also protects most of your legitimate people from being bothered during an attempted DNS attack.


text:
Q: SC.SceneView animated vertically? do you see any solution for this?
I would like to get the SC.SceneView transition from bottom to top and not from left to right or right to left.
The Doc isn't saying much here, but since the original transistion has to be somewhere, maybe i can prototype its method for that?
Thank you

A: Looking at the source, there are no options to animate horizontally.  You could create a subclass to do it (doesn't look complicated), using the existing source as a guide.
However, this doesn't appear to be using the Animation framework or adjust methods.  You could probably define your own that works better, using css3.  That method will work better (i.e. the animation should be smoother)


text:
Q: Import a C++ .lib and .h file into a C# project? I have just started a C# project and want to import a C++ .lib and it's corresponding header (.h) file.
I've read various posts that all mention .dll, rather than .lib, which is confusing me.
The image below shows the .lib and .h file I'm referring to, all I've done is drag them into the project.

Can anyone point me to a clearer explanation of how to go about doing this? I'm sure it can't be as hard as it seems.

A: It is 'as hard as it seems'. C++ and C# are ambivalent. The first has deterministic destruction, the second not. Now, you write C++/cli delaying the destruction to some finalizer called by the garbage collector working in it's own thread, introducing problems all over the place (thread safety, are C++ members (used in c++/cli) valid?, ...). Even worse the GC might suggest C++ objects being tiny (a pointer) and provoke a kind of memory leak (due to late deallocating tiny objects). Essentially you end up in writing a GC on top of the C++/cli GC to delete non C++/cli (!) objects in the main thread or another. All that is insane, ...

A: This is, unfortunately, a non-trivial problem.
The reason is primarily due to the fact that C++ is an unmanaged language.  C# is a managed language. Managed and unmanaged refers to how a language manages memory.

*

*C++ you must do your own memory management (allocating and freeing),

*C# .NET Framework does memory management with a garbage collector.

In your library code
You must make sure all of the places you call new, must call delete, and the same goes for malloc and free if you are using the C conventions.
You will have to create a bunch of wrapper classes around your function calls, and make sure you aren't leaking any memory in your C++ code.
The problem
Your main problem (to my knowledge) is you won't be able to call those functions straight in C# because you can't statically link unmanaged code into managed code.
You will have to write a .dll to wrap all your library functions in C++.  Once you do, you can use the C# interop functionality to call those functions from the dll.
[DllImport("your_functions.dll", CharSet = CharSet.Auto)]
public extern void your_function();

A: What you could do, is creating a C++/CLI wrapper and expose the functionality of the lib you want to use via your wrapper. The created wrapper dll you can easily reference in your C# project. This of course takes a little bit of work to create the managed/unmanaged wrapper, but will pay off in the long run.
To create a managed C++ project select under the C++ project templates CLR and Class Library. Here you can link to your lib, use the header file the way you are used to.
Next create a new class (ref class) and wrap your library in it. An example might look something like this:
LibHeader.h

int foo(...);

You write a wrapper class like this:
Header:
Wrapper.h

public ref class MyWrapper
{
    public:
        int fooWrapped();
};

Your Implementation:
Wrapper.cpp

#include Libheader.h

int MyWrapper::fooWrapped()
{
     return foo();
}

Namespaces and all the good stuff omitted for simplicity.
Now you can use MyWrapper in your C# code just as easy as any other managed class. Of course when the interface of the lib gets more complicated you have to think about it a bit more, but it might help to separate the lib-code from your application. Hope to have shed some light on it.


text:
Q: PFQueryTableViewController not showing custom cells I have a subclass of PFQueryTableViewController that I am trying to show in a container view (as a subview).  My problem is that I cannot get the custom cells to show in the tableview.  I have verified the following via debugging:

*

*The tableview is being added to the parent view

*The tableview is a PFQueryTableView Controller as it includes the default pull to refresh

*The PFQuery is returning the correct number of objects

*The CellForRowAtIndexPath method is being called and iterating through the correct number of times

*The correct data from Parse is being passed to the different labels in the cells

*The labels are connected via IBOulets in my subclass of UITableViewCell.  When I am trying to access the labels it is working correctly as it accesses the subclass and label

I have everything working here correctly except that the cell actually shows up!  What am I missing?
This is my cellForRowAtIndexPath code:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object{

     static NSString *CellIdentifier = @"RoundCell";

    RoundCell*   cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];

    if (cell == nil)
    {
        cell = [[RoundCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

     // get string values from Parse
     NSString * teeString =[object objectForKey:@"roundTee"];
     NSString* courseString = [object objectForKey:@"roundCourse"];
         NSString * courseString2 = [[courseString stringByAppendingString:@" - "]stringByAppendingString:teeString];
     NSString * dateString = [object objectForKey:@"roundDate"];
     NSString * scoreString = [object objectForKey:@"roundScore"];
    NSString * differentialString = [object objectForKey:@"roundDifferential"];

    cell.courseNameCell.text = courseString2;
    cell.dateCell.text = dateString;
    cell.scoreCell.text= scoreString;
    cell.differentialCell.text=differentialString;
     return cell;
 }

A: The correct method is to call the custom cell in cellForRowAtIndexPath.
Check two basic things:
1. on the storyboard and click on the cell in the Attributes inspector checks that the cell has the correct identifier

2. set the cellForRowAtIndexPath in this way:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object{

 CustomCell *cell = (CustomCell * )[self.tableView dequeueReusableCellWithIdentifier:@"YOUR CELL NAME" forIndexPath:indexPath];

So in your case try:
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object{

     CustomCell *cell = (CustomCell * )[self.tableView dequeueReusableCellWithIdentifier:@"YOUR CELL NAME" forIndexPath:indexPath];

     NSString * teeString =[object objectForKey:@"roundTee"];
     NSString* courseString = [object objectForKey:@"roundCourse"];
         NSString * courseString2 = [[courseString stringByAppendingString:@" - "]stringByAppendingString:teeString];
     NSString * dateString = [object objectForKey:@"roundDate"];
     NSString * scoreString = [object objectForKey:@"roundScore"];
    NSString * differentialString = [object objectForKey:@"roundDifferential"];

    cell.courseNameCell.text = courseString2;
    cell.dateCell.text = dateString;
    cell.scoreCell.text= scoreString;
    cell.differentialCell.text=differentialString;
     return cell;
 }

Do not forget to import the subclass of custom cell in your File.m
#import "YourCustomCell.h"

and set the cell in the identity inspector

A: If you designed your UITableView cell in a XIB (which it sounds like you did), then you can't use the alloc init paradigm to initialize your object. You have to use:
cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCellXibFile"
                                     owner:nil
                                   options:nil] objectAtIndex:0]

A: Swift Version (prior to 1.2):
import UIKit

class JPUsersTableViewController: PFQueryTableViewController {

override init!(style: UITableViewStyle, className: String!) {
    super.init(style: style, className: className)
    textKey = "username"
    pullToRefreshEnabled = true
    paginationEnabled = true
    objectsPerPage = 25
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()

    title = "Users"

    tableView.registerClass(PFTableViewCell.self, forCellReuseIdentifier: kTableViewCellIdentifier)
    tableView.separatorInset.right = tableView.separatorInset.left
    tableView.tableFooterView = UIView(frame: CGRectZero)
    view.backgroundColor = kbackgroundColor

    let returnIcon = UIBarButtonItem(image: kNavBarReturnIcon, style: .Plain, target: navigationController, action: "popViewControllerAnimated:")
    returnIcon.tintColor = kToolbarIconColor
    navigationItem.leftBarButtonItem = returnIcon

    tableView.reloadData()
    addPullToRefresh()
}

override func queryForTable() -> PFQuery! {
    let query = PFUser.query()
    query.whereKey("username", notEqualTo: PFUser.currentUser().username)
    query.orderByAscending("username")

    //if network cannot find any data, go to cached (local disk data)
    if (self.objects.count == 0){
        query.cachePolicy = kPFCachePolicyCacheThenNetwork
    }

    return query
}

// MARK: - Navigation

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> PFTableViewCell! {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as PFTableViewCell
    cell.textLabel?.text = object["username"] as? String

    if let profileImage = object["profileImage"] as? PFFile {
        cell.imageView.file = profileImage
    }
    else {
        cell.imageView.image = kProfileDefaultProfileImage
    }

    cell.textLabel?.font = UIFont(name: kStandardFontName, size: kStandardFontSize)
    cell.textLabel?.textColor = UIColor.whiteColor()
    cell.backgroundColor = kbackgroundColor

    return cell
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 50
}
}


text:
Q: Type inheritance in Dictionary Here's the situation:
There's a base class of type BaseObject ,from which all other classes are derived(i.e. Task : BaseObject).
There's also a base class collection of type BaseObjectCollection which inherits from Dictionary<ulong,BaseObject> and some other collections that inherit from it (i.e. TaskCollection:BaseObjectCollection).
When iterating over TaskCollection members they are shown as BaseObject type.
Is there any way to make the collection "change" its values' types so that it will possess the functionality of BaseobjectCollection and yet appear as Dictionary<ulong,Task> instead of Dictionary<ulong,BaseObject>

A: You should change your BaseObjectCollection type to be generic in the type of value it will use. For example:
public class BaseObjectCollection<T> : Dictionary<ulong, T>
    where T : BaseObject

Then you can use a BaseObjectCollection<Task> and still be completely type-safe.
(I would personally use composition in most cases rather than deriving a new type from Dictionary<,> but that's a different matter.)


text:
Q: Sum three tables I want to get 2 sums from 3 tables:
tbl_header
id   id_quotation   description
1    1              descr_1
2    2              descr_2

tbl_body
id   id_quotation   id_item  item_cost
1    1              1        400
2    1              2        300

tbl_money
id   id_quotation   amount
1    1              200
2    1              300
3    2              100

So I need 1 query to get the description from the tbl_head SUM(tbl_body.item_cost) WHERE tbl_body.id_quotation = 1 (in this case 400+300=700) and SUM(tbl_money.amount) WHERE id_quotation=1 (in this case 200+300=500). Id_quotation is the same field in all tables.
I did it with this query:
select    head.description,
          sum(body.item_cost) as sum_1,
          (select   sum(money.amount)
           from     tbl_money money
           where    money.idquotation=head.idquotation
           GROUP BY money.id_quotation) as sum_2
FROM      tbl_body as body,
          tbl_header as head
WHERE     head.id_quotation=body.id_quotation
GROUP BY  head.description

Now I'd like to eliminate the inner query select sum(money.amount) from ... and replace it with something like SUM(money.amount) but I always get the record 3 times so the sum is three times bigger. The query that doesn't work is:
SELECT        head.description,
              Sum(body.item_cost) AS sum_1,
              sum(money.amount) as sum_2
FROM          (tbl_header head
               INNER JOIN tbl_body body
               ON head.id_quotation=body.id_quotation)
  INNER JOIN  tbl_money money
  ON          head.id_quotation=money.id_quotation
WHERE         head.id_person=1
  AND         money.id_quotation=body.id_quotation
GROUP BY      head.description;

Thanks.

A: select min(header.description), SUM(body3.item_cost), SUM(money.amount)
from tbl_header header
    left outer join tbl_body body on header.id_quotation = body.id_quotation
    left outer join tbl_body body1 on body1.id< body.id
    left outer join tbl_body body2 on body2.id> body.id
    left outer join tbl_money money on money.id_quotation = header.id_quotation and body1.id is null
    left outer join tbl_body body3 on body3.id_quotation=header.id_quotation and body2.id is null
where header.id_quotation = 1
group by header.id_quotation

A: Your approach is fine, although I would put the subquery in the from clause and fix the join to use proper join syntax.  There is a trick to do what you want.  Although I don't recommend it, I will show you:
select    head.description,
          sum(body.item_cost)/count(distinct money.id) as sum_1,
          sum(money) / count(distinct money.id) as sum_2
FROM      tbl_body body join
          tbl_header head
          on head.id_quotation=body.id_quotation join
          tbl_money
          on money.idquotation = head.idquotation
GROUP BY  head.description

That is, divide out the counts of the duplicates.  I would only ever do this for the quickest and dirtiest queries.
The recommended way is to do the summary on the money table before the join:
select    head.description,
          sum(body.item_cost) as sum_1,
          sum(money) as sum_2
FROM      tbl_body body join
          tbl_header head
          on head.id_quotation=body.id_quotation join
          (select idquotation, SUM(money) as money
           from tbl_money
           group by idquotation
          ) money
          on money.idquotation = head.idquotation
GROUP BY  head.description


text:
Q: Evaluate the sum $n(n-1)(n-2)(n-3)$ Can someone be kind to help me to verify the sum $n(n-1)(n-2)(n-3)$, using generating functions?
My result is: $4{n+1\choose 2} + 4{n+2\choose 3} +{n+4 \choose 5} + 6{n+2\choose 3} + 6{n+1\choose 2} + 11{n+1 \choose 2} - 6{n+1 \choose 2}$

A: Assuming you mean to evaluate $\sum_{k=0}^n k(k-1)(k-2)(k-3)$, the falling factorial approach hinted above - i.e. using $\Delta(N^{\underline{m}}) = m N^{\underline{m-1}}$ seems nice to tackle this problem.
If you must use generating functions, note the ogf of $P(n)=n(n-1)(n-2)(n-3)$ is obtained by the operation $P(xD) \dfrac1{1-x}$, where $D$ stands for differentiation.
Then to sum, we need to divide further by $(1-x)$. From there you should be able to find the coefficient of $x^n$.


text:
Q: Не работает .attr <button class ="btn btn-default pull-right" id="save"  onclick="echoq();">Сохранить</button>

    <button  class="close" id="close" onclick="close();">×</button>
        Текст

Функции:
function echoq(){
  $( "#resultVK" ).removeAttr( "style" );
}
function close(){
  $( "#resultVK" ).attr("style","display:none");
}

Т.е. при нажатии сохранить - показать блок. При нажатии х - скрыть.
Но почему-то скрытие не работает.

A: Почему не работает?
Функция close не работает, поскольку у js есть нативный метод close и при его вызове вызывается не ваша функция, а нативная.
Решение лучше

$(document).on('click', '#save', function() {
  $('#resultVK').show();
});

$(document).on('click', '#close', function() {
  $('#resultVK').hide();
});

<button class ="btn btn-default pull-right" id="save">Сохранить</button>

    <button  class="close" id="close">×</button>
        Текст

A: зачем удалять style? меняйте только display:
$( "#resultVK" ).css("display","none");// hidden
$( "#resultVK" ).css("display","");// show

A: У window есть функция close. Переопределить её, надо полагать, нельзя. Поэтому стоит изменить имя функции. Например, на closeResult.
Использование inline-JS (onclick="") не приветствуется обществом уже немало лет. Возникшая проблема с именем функции - ещё один камень в огород inline_JS.
И, конечно, для работы со стилями лучше использовать .css().


text:
Q: Why are consumer grade RAID controlers MORE expensive than complete external array solutions and are they compatible? I'm looking at consumer grade ESATA DAS solutions for my home lab.
I use vmware workstation with mucho VMs currently all stored on the same 1TB 7200 RPM SATA disc- performance is pretty terrible as you can imagine.
But what perplexes me, looking on newegg, is how cheap complete ESATA RAID enclosures (for home users) are vs how expensive standalone RAID controllers (also for consumers) are. It makes me suspicious that the controllers bundled with these 4-8 bay enclosures are all garbage.
If I buy an external storage solution packaged with a SATA RAID card will I be able to upgrade the RAID card in the future? I know changing the card will mean rebuilding the array and restoring all the data of course. Apart from the slightly inconveniencing penchant of most higher end controllers not having external ESATA ports, which can easily be solved, are there any reasons why they wouldn't be compatible? As long as the card supports Port multiplier and SATA it should be able to access the disks right?
For a specific example I'd like to buy a complete solution like the "Sans Digital 4-Bay eSATA Tower Storage Enclosure", but then if necessary upgrade the RAID card to something like the "HighPoint RocketRAID 2720SGL".
I'm not asking for any specific buying suggestions I just want to be sure these two types of products will be compatible and I'm not misunderstanding something.


text:
Q: How to search a NSDictionary object from a NSMutableArray using a value of a key in dictionary I have an array which contains NSDictionaries.
[
  {
    "ObjectId": 20,
    "ObjectName": "Leave Request",
    "RequestItems": []
    "ClassName": "req-auth"
  },
  {
    "ObjectId": 22,
    "ObjectName": "Cancel Leave Request",
    "RequestItems": []
    "ClassName": "req-auth"
  }

I want to check in this array Leave Request and Cancel Leave Request objects are available. So I am going to search the object by ObjectName. But I don't understand how to search these objects by using a 1 value of those objects. Please help me.
Thanks

A: Try this
NSString *searchString = @"Cancel";
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return [evaluatedObject[@"ObjectName"] localizedCaseInsensitiveContainsString:searchString];
}];
    filteredContentList = [NSMutableArray arrayWithArray:[searchListValue filteredArrayUsingPredicate:predicate]];

A: You can try using NSPredicate. Something like this:
-(NSArray *)array:(NSArray *)array filteredWithString:(NSString *)string{

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.ObjectName CONTAINS[cd] %@",string];

    return [array filteredArrayUsingPredicate:predicate];
}

Just pass in the array to filter with the string you wish to filter it by and call it where you want to filter it.
A few things: Here cd is used to perform a case insensitive compare, if you want it be case sensitive just remove the cd from the string. ObjectName is the property you wish to filter by. You can change CONTAINS to LIKE if you want an exact comparison.

A: If you just want to fetch objectName from each dictionary in array, then do it like:
   for dict in arrayOfData{
        if let strObjectName : String = dict["ObjectName"] as? String{
        print(strObjectName)
        }
   }


text:
Q: issues w/ centering google map in bootstrap3 modal... keeps changing Hi and thanks for your help. I have a bootstrap 3 page that I put a google map into a modal. After MUCH tweaking and research, reading I was able to get the map to show, correctly in desktop and mobile formats (map fill the modal no grey, not break out of modal in responsive etc.) The last issue is that now I find the center marker does not center inside the frame after render all the time. That is to say SOMETIMES after a page reload the map will appear correctly, sometimes, mostly not. This is in Chrome, Firefox, Mozilla and Opera test browsers. Hours and hours spent on this help please.
Here's the code:
HTML

Map to Satori Spa

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

Satori Spa Massage - Encino Ca.

                <button type="button" class="close" data-dismiss="modal">Close</button>

JS at bottom of page

Live page is here @ satorispamassage.com
Thanks again and Any help appreciated.

A: The basic issue is that  you call the method setCenter of map , but the name of the variable is var_map.
Another issue: it may happen that someone opens the modal before the map has been created, test the variable before you access it:
  //start of modal google map
  $('#mapModal').on('shown.bs.modal', function () {

    //test if the map already has been created
    if(var_map){
      google.maps.event.trigger(var_map, "resize");
      var_map.setCenter(new google.maps.LatLng(34.158540, -118.493270));
    }
  });

(Also removed the call of initialize, there is no such function)