text:
Q: Writing predicates - is the quantifier necessary? I'm taking a course in mathematical logic, it has recently covered quantifiers and now I find myself somewhat confused whether or not the existential quantifier is necessary - consider this example:
Disclaimer: Assume that our universe is the set of natural numbers

$x$ is an even number

Now, I can't really tell the difference between these two notations:
$$(\exists m)(x=2m)$$
And this:
$$x=2m$$
Are they basically the same? If so, does it mean that we can always omit the existential quantifier?
Now, let's consider another example:

$x$ is prime

The same problem - I have two notations and can't choose which of them is the right one.
$$(\forall a)(a |x \Rightarrow ((a=1 \lor a=x) \land x\ne1))  $$
And
$$a|x \Rightarrow ((a =1 \lor a=x) \land x\ne 1) \\ [1]$$
And finally, the last predicate:

$x$ is composite

Is it enough to write $$ \neg [1]$$ or it is necessary to write $$(\exists a)(\neg [1])$$
Do these predicates actually mean the same thing?

A: No, we cannot omit the existential quantifier.
How we read the formula:

$x=2m$ ?

As: "every $x$ is even" ? Or as: "some $x$ is even" ? Or as: "every $x$ is the double of every $m$" ? Or as: "some $x$ is the double of every $m$" ?
The "usual" convention is that we can omit the universal quantifier.
If we apply it, we read:

$\exists m \ (x = 2m)$

as: $\forall x \exists m \ (x=2m)$, i.e. as: "every number is even".

Regarding the second part of the question, if we write, for $x \ne 1$: $\text{Prime}(x)$ as $\forall a (a|x \to \ldots)$, clearly:

$\text{Comp}(x) \text { iff } \lnot \text {Prime}(x) \text { iff } \lnot \forall a (a|x \to \ldots) \text { iff } \exists x \lnot (a|x \to \ldots)$.

A: Notice how '$x$ is even' makes explicit reference to $x$, but not to $m$. That should be an indication already that in your formula you want $x$ as a free variable (i.e do not quantify the $x$) but not $m$, so use:
$$\exists m \ x = 2m$$
Also note that depending on how you quantify the $x$, you get a different statement:
$$\forall x \exists m \ x =2m$$
means that all numbers are even, while
$\exists x \exists m \ x=2m$
means that some number is even. (note that in both interpretations there is no longer a reference to $x$, again signaling that the $x$ has been quantified)
Likewise, the meaning of
$$x =2m$$
(which, by itself, reads as '$x$ is twice $m$' ... so now you do have an explicit reference to $m$, reflecting the fact that $m$ is a free variable)
depends on how $m$ is being quantified:
$$\exists m \ x=2m$$
clearly means that $x$ is even, while
$$\forall m \ x =2m$$
clearly means something different!
So yes, you really want to existentially quantify that $m$.
Same story for '$x$ is composite': it makes no reference to any $a$, and so you do need to quantify that $a$ and have only $x$ as a free variable.  And also note that if you were to quantify the $a$ existentially, you don't get what you want.
Finally, for '$x$ is composite' it makes sense to just negate whatever you have for '$x$ is a prime' (and hence any quantificational issues will be taken care of automatically) ... if it weren't for the fact that $1$ is neither prime nor composite!   So what you really want there is '$x$ is not $1$ and $x$ is not prime'

A:
If so, does it mean that we can always omit the existential quantifier?

Not exactly, but there is a rigorous way of removing existential quantifiers.  It is called skolemization, and follows a 3-step process:

*

*Move all quantifiers outwards, giving you prenex normal form.  This is typically pretty straightforward but may require minor restructuring of the formula.

*Move existential quantifiers outside of universal quantifiers.  If your expression is of the form $\forall x \exists y \phi(x, y)$, it is claiming that for each x, there is a y.  You can rephrase that as there is a single function which maps x's to y's, which we write as $\exists f \forall x \phi(x, f(x))$.  In this context, we call $f$ a skolem function.

*Delete all existential quantifiers. The variables which were bound to those quantifiers become free.  These free variables may then be unified with any suitable terms which satisfy the predicate.

Because we unbind the variables in step 3, this changes the meaning of the statement (instead of merely claiming that there is an $f$ or $y$ satisfies the requirement, we are claiming that $f$ or $y$ has some independent meaning which satisfies the formula).  As a result, this is not a general-purpose technique, and must be used with care.  However, the altered statement is equisatisfiable with the original, which makes it suitable for automated theorem proving and other contexts where satisfiability is the object of our investigation.
Unfortunately, we cannot stop at step 2, if we want to remain within first-order logic.  Existential quantifiers over functions are only allowed in second-order logic; the formula shown in step 2 is ill-formed in first-order logic.  It is quite possible to perform this transformation without taking that detour through second-order logic (by dropping the existential quantifier at the same time as we introduce the skolem function), but that's a little harder to follow.
In practice, skolemization is often combined with a conversion to conjunctive normal form, because that is a prerequisite to applying resolution.


text:
Q: How to query solr field for a substring My use case:
I have a single-valued field called cqpath. This is a textfield and has a values that look something like the following:

*

*"/content/domain/en/path/to/some/page"

*"/content/domain/en/path/to/another/page"

*"/content/domain/en-us/path/to/some/page"

*"/content/domain/en-us/path/to/another/page"

I wanted to form a query that would return me 1. and 2. I'd been trying along the lines of writing:
cqpath: "/content/domain/en"
which has been discovered to be erroneous, since it retrieves items 3. and 4. as well. Could any of you think of a way to write a query that returns only 1. and 2. and not 3. and 4.?
This is a normal textfield field-type. Really do appreciate your help.

A: Starting from Solr 4.0 you can use a regex query. You can find some useful examples here.
In your case, you can get the results that you're looking for using something like:
cqpath:/.*content/domain/en.*/

A: It looks like you are trying to match partial paths here with boundaries on path elements (slashes). The usual generic solution is to tokenize during index to generate all alternative completions and not tokenize during query. So, the field type declaration is not symmetric. There are examples of that in Solr distribution. And you would look at using something like (index-time only) EdgeNGramFilterFactory instead of much more expensive regex matching.
For your specific case, you may want to look at testPathHierarchyTokenizer which does that for you automatically.
And if your content were more like full URLs than just path, you could also be interested by a custom update request processor chain that includes URLClassify URP. It is not very documented, but mentions generating url parts, which is what I think you would want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extracting RSS link with Nokogiri I am using Nokogiri to extract the RSS link from a webpage. However, since some websites have absolute paths and others relative on their HTML, I wanted to make it so that if the website has a relative path it will be made absolute.
Here is my code:
require 'nokogiri'
require 'simple-rss'
require 'open-uri'

ARGV.map! { |http| "http://#{http}"}
ARGV.each do |website|
doc = Nokogiri::HTML(open(website))
rss_path = doc.xpath("//link[@type=\"application/rss+xml\"]").map do |link|
    if link['href'] =~ /^http:\/\/[a-z]*\..*\//i
        puts link['href']
    else
        puts "#{website}#{link['href']}"
    end
end

So if I was on command line, I would type something like
ruby rss.rb 8gramgorilla.com rubyweekly.com

The code works fine for rubyweekly.com which has a relative path for its RSS but 8gramgorilla.com has an absolute path and so I would want it to just be output immediately, not have http://8gramgorilla.com/http://8gramgorilla.com/feed as the output. Basically, what's going on is that the IF statement is being ignored and it goes right away to the else statement.

A: The if statement isn't being ignored, it is evaluating to false. Your regexp is /^http:\/\/[a-z]*\..*\//i, so it is looking for http:// followed by any number of a-z (or a . since zero a-z will also match). But the website url is http://8gramgorilla.com, the first character is the digit 8, which isn't in the range a-z.
The most direct fix to this would be to change your regex to include digits, perhaps something like /^http:\/\/[\da-z]*\..*\//i (where \d has been added).
You might be able to simplify the regex more, perhaps simply checking to see if the url matches http:// at the start would be enough.
A more robust solution would be to properly parse the url in question, perhaps using the Addressable gem or the URI module in Ruby's standard lib.

A: There's no need for the if, just do:
require 'uri'
puts URI.join(website, link['href']).to_s

A: To detect the RSS feed for the New York Times http://www.nytimes.com:
<link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml">

I would use the following to extract the href value from application/rss+xml link tag:
require 'nokogiri'
require 'httparty'
url = 'http://www.nytimes.com'
resp = HTTParty.get(url)
doc = Nokogiri::HTML(resp.body)
feed = doc.css("link[type='application/rss+xml']").map{|link|link[:href]}.first

Which would return the RSS feed value for the site:
http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml

Note, if the site does not have application/rss+xml tag, the code will simply return nil.


text:
Q: GitHub probot : signature does not match event payload and secret I am aware of this question GitHub Probot : ERROR probot : signature does not match event payload and secret. In my case the problem is a bit weirder. So when I'm running my application on the localhost and it is receiving github hooks via proxy https://smee.io/ everything works fine. But (with exactly the same env variables) when I'm hosting my application on kubernetes I got following error GitHub probot : signature does not match event payload and secret and I know that according to linked question it has something to do with Webhook secret but I do not understand why the same variable is working on localhost and give errors on k8 (ofc is in base64). My app is done according to documentation https://probot.github.io/docs/development/#use-server. I suspect that it might be connect with x-hub-signature-256 but it shouldn't be a problem since when I check Webhook secret on k8 pod I can see that it is correct. Any ideas what can be cause of the problem?

A: It took me a while but the problem was in the base64 encoding of the secret. It contained new line character and because of it, the secret looked valid on the terminal. So to sum up this error was solely connected with secret correctness.


text:
Q: How to convert contact form 7 submission to post after submission? I have developed Contact Form 7 and I want to create a post directly after the user submits the form in WordPress. I am not able to do that.
Can anyone suggest any plugin or method?


text:
Q: Many-to-many relationship vs one-to-many relationships Recently I read an article about building a tag table for better seraching post by tags. The author suggested using one-to-many relationship with post table -> tag table with tag as text[] type. the performance were really good, especially pagination.
he showed how a many-to-many normalized post table - tag join table - tag table tag as text type - is way less performant.
At this point it made me question, if thats the case, then when do I have to make those normalized tables with many-to-many? as textbooks often tells us to normalize tables.
In my backend, besides tags, I'll employ a global category table, which will have a set 20 predefined category name that each post must make at least one relation to.
from his experimentations, it makes me want to build category table his way as well of one-to-many using text[] ... but I'm unsure it is wise to go what the logical model of many-to-many.
I'm a new learner of building databases with rdbms.
article:
http://www.databasesoup.com/2015/01/tag-all-things-part-3.html


text:
Q: multidimensional arrays in php? I have a problem with arrays in PHP. So, lets see: I have a table "Users" in database with such fields: "name, surname, age, rating". The number of users is nearly 100. I need to get all of them from database, post it to array, encode them with JSON end show. So I suppose, I need to do the follows:

*

*Get one row from DB.

*Add all data to some array fields like associative array.

*Push that array to some array container.

*Encode array container to JSON.

But when I try to encode, I get only last element in array container. I writted something like that:
$arrContainer = array();
$arr = array();
$i = 0;
while($row = getDataFromDB)
{
  arr[$i] = $i;
  arr["name"] = row["name"];
  arr["age"] = row["age"];

  array_push($arrContainer, $arr);
  $i++;
}

JSON.encode($arrContainer);

QUESTION: How can I make array of arrays with some data?

A: while($row = getDataFromDB)
{
   $arr[]=$row; // add $row as element of $arr array
}

Now you get multidimensional-array and can Json encode it
Besides, some database extensions can returns all data to multidimensional array automatically.
See PDOStatement::fetchAll manual

A: try this:
$arr = array();
$i = 0;
while($row = getDataFromDB){
  $arr[$i] = $row;
  $i++;
}
JSON.encode($arr);

A: You can create array as in @RiaD's answer
and then output json as ..
while($row = getDataFromDB) // @RiaD's code
{
   $arr[]=$row; // add $row as element of $arr array
}

//json output
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header('Content-type: application/json');
echo  json_encode($your_array);

A: The code you have posted is correct, however in the following lines you forgot to put $ before the $arr variable:
arr[$i] = $i;
arr["name"] = row["name"];
arr["age"] = row["age"];

Also the line arr[$i] = $i; should probably be something like $arr['rowNum'] = $i; having the key be the same as the value seems redundant.
And it should be said that using $arrContainer[]=$row; as @RiaD suggested is a quicker way to get an array of the row, array_push() is more intended to add multiple values to an array or if you want to treat it as a stack.

A: $allValuesArr = array();
$arr= array();
while($myRow = mysql_fetch_array($result))
{
    $arr["uid"] = $myRow["uid"];
    $arr["name"] = $myRow["name"];
    $arr["surname"] = $myRow["surname"];
    $arr["age"] = $myRow["age"];
    $arr["telephone"] = $myRow["telephone"];
    $arr["prof_id"] = $myRow["prof_id"];
    //$allValuesArr[] = $arr;
    array_push($allValuesArr, $arr);
}

$strJSON = json_encode($allValuesArr);
echo $strJSON;

response I get:
[{"uid":"1","name":"Sergii","surname":"Surname1","age":"26","telephone":"0976543135","prof_id":"1225423"},{"uid":"2","name":"Slava","surname":"Surname2","age":"24","telephone":"06353524","prof_id":"13584384"},{"uid":"3","name":"Desame","surname":"Surname3","age":"28","telephone":"0973153584","prof_id":"35843815"}]


text:
Q: Access (ADO) query between two hour ranges Using VB to query an access .mdb database via ADODB.
My date column holds both date and time, I would like to to build a query which will ignore the date, and refer only to the time in that column, in such a way, that will enable me to return records that have their time in between a range given by the user, ignoring the date.

I tried selecting between numbers, but I believe access I'm doing it wrong
...WHERE [Date_Time_Of_Birth] Between #04:00:00# and #06:00:00#

Just doesn't work as intended ... need a direction here.

A: Use the TimeValue Function to ignore the date portion of your Date_Time_Of_Birth values.
Also #04:00:00# and #06:00:00# are 4 and 6 AM. Since you want PM times, write the values as in one of these examples:
WHERE TimeValue([Date_Time_Of_Birth]) Between #16:00:00# and #18:00:00#

WHERE TimeValue([Date_Time_Of_Birth]) Between #4 PM# and #6 PM#


text:
Q: How to read the screen pixels? I want to read a rectangular area, or whole screen pixels. As if screenshot button was pressed.
How i do this?
Edit: Working code:
void CaptureScreen(char *filename)
{
    int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
    int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
    HWND hDesktopWnd = GetDesktopWindow();
    HDC hDesktopDC = GetDC(hDesktopWnd);
    HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
    HBITMAP hCaptureBitmap = CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight);
    SelectObject(hCaptureDC, hCaptureBitmap);

    BitBlt(hCaptureDC, 0, 0, nScreenWidth, nScreenHeight, hDesktopDC, 0,0, SRCCOPY|CAPTUREBLT);

    BITMAPINFO bmi = {0};
    bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
    bmi.bmiHeader.biWidth = nScreenWidth;
    bmi.bmiHeader.biHeight = nScreenHeight;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biCompression = BI_RGB;

    RGBQUAD *pPixels = new RGBQUAD[nScreenWidth * nScreenHeight];

    GetDIBits(
        hCaptureDC,
        hCaptureBitmap,
        0,
        nScreenHeight,
        pPixels,
        &bmi,
        DIB_RGB_COLORS
    );

    // write:
    int p;
    int x, y;
    FILE *fp = fopen(filename, "wb");
    for(y = 0; y < nScreenHeight; y++){
        for(x = 0; x < nScreenWidth; x++){
            p = (nScreenHeight-y-1)*nScreenWidth+x; // upside down
            unsigned char r = pPixels[p].rgbRed;
            unsigned char g = pPixels[p].rgbGreen;
            unsigned char b = pPixels[p].rgbBlue;
            fwrite(fp, &r, 1);
            fwrite(fp, &g, 1);
            fwrite(fp, &b, 1);
        }
    }
    fclose(fp);

    delete [] pPixels;

    ReleaseDC(hDesktopWnd, hDesktopDC);
    DeleteDC(hCaptureDC);
    DeleteObject(hCaptureBitmap);
}

A: Rereading your question, it sounds like we may have gotten off on a tangent with the screen capture.  If you just want to check some pixels on the screen, you can use GetPixel.
HDC hdcScreen = ::GetDC(NULL);
COLORREF pixel = ::GetPixel(hdcScreen, x, y);
ReleaseDC(NULL, hdcScreen);
if (pixel != CLR_INVALID) {
  int red = GetRValue(pixel);
  int green = GetGValue(pixel);
  int blue = GetBValue(pixel);
  ...
} else {
  // Error, x and y were outside the clipping region.
}

If you're going to read a lot of pixels, then you're better off with a screen capture and then using GetDIBits.  Calling GetPixel zillions of times will be slow.

A: You make a screenshot with BitBlt().  The size of the shot is set with the nWidth and nHeight arguments.  The upper left corner is set with the nXSrc and nYSrc arguments.

A: Starting with your code and omitting error checking ...
// Create a BITMAPINFO specifying the format you want the pixels in.
// To keep this simple, we'll use 32-bits per pixel (the high byte isn't
// used).
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = nScreenWidth;
bmi.bmiHeader.biHeight = nScreenHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;

// Allocate a buffer to receive the pixel data.
RGBQUAD *pPixels = new RGBQUAD[nScreenWidth * nScreenHeight];

// Call GetDIBits to copy the bits from the device dependent bitmap
// into the buffer allocated above, using the pixel format you
// chose in the BITMAPINFO.
::GetDIBits(hCaptureDC,
            hCaptureBitmap,
            0,  // starting scanline
            nScreenHeight,  // scanlines to copy
            pPixels,  // buffer for your copy of the pixels
            &bmi,  // format you want the data in
            DIB_RGB_COLORS);  // actual pixels, not palette references

// You can now access the raw pixel data in pPixels.  Note that they are
// stored from the bottom scanline to the top, so pPixels[0] is the lower
// left pixel, pPixels[1] is the next pixel to the right,
// pPixels[nScreenWidth] is the first pixel on the second row from the
// bottom, etc.

// Don't forget to free the pixel buffer.
delete [] pPixels;

A: You can use the code below to read the screen pixels:
HWND desktop = GetDesktopWindow();
HDC desktopHdc = GetDC(desktop);
COLORREF color = GetPixel(desktopHdc, x, y);

A: HBITMAP is not a pointer or an array, it is a handle that is managed by Windows and has meaning only to Windows. You must ask Windows to copy the pixels somewhere for use.
To get an individual pixel value, you can use GetPixel without even needing a bitmap. This will be slow if you need to access many pixels.
To copy a bitmap to memory you can access, use the GetDIBits function.


text:
Q: setting a generic alias results in doing nothing at all I want to create an alias, that can be defined on any command and concats | lolcat to it. So far I googled myself to
alias MyCommandName='f(){"$@" | lolcat; unset -f f};f'

but when I test it with dmesg I get no result.
# set dmesg
alias dmesg='f(){"$@" | lolcat; unset -f f};f'
#desired command: dmesg | lolcat
dmesg

In my understanding the alias defines a function f, that is called afterwards. To prevent recursion, the last statement is to unset the function.
EDIT:
I stopped at:
    alias MyCommandName='f(){eval "$@ | lolcat"; unset -f f};f'
    alias MyCommandName='f(){eval "$0 $@ | lolcat"; unset -f f};f'

which does not the trick, because i can't pass the $0 argument into my function. The $0 is always f inside of the function. a generic aliaslias like is NOT possible. :(
NOT A DUPLICATE of this, because I am using ZSH and argument passing is possible according to like 10 other answers like this and this :).

A: If I understand right, you want to do something that takes a command name, say dmesg, and make it into something pipes its output to lolcat.
This is still best done using functions:
dmesg () { command "$0" "$@" | lolcat; }

That's as "generic" as it comes. The command command skips functions and calls builtins or executables: What is use of command: `command`?. $0, as you realised, is the name of the function, in this being the name of the command as well. So command "$0" runs the command with the same name as the function.


text:
Q: Is spinor the sum of scalar, vector, bi-vector, pseudo-vector, and pseudo-scalar? Is spinor $\psi$ actually the sum of scalar, vector, bi-vector, ..., pseudo-scalar?
Before talking about spinors, we have to differentiate two kinds of spacetime, demonstrated with the example of spin connection 1-form $\omega$ in Einstein-Cartan gravity
$$
\omega = \frac{1}{4}\omega^{ab}_{\mu}\gamma_a\gamma_bdx^{\mu}.
$$
The spin connection 1-form $\omega$ is a

*

*Vector in spacetime manifold characterized by differential vector base $dx^{\mu}$.

*Bi-vector in internal (local, tangential, or spinor bundle) spacetime characterized by anti-symmetric $\gamma_a\gamma_b$, where $\gamma_a$ are Dirac vector basis.

(A bonus example: the torsion 2-form $T = \frac{1}{2}T^{a}_{\mu\nu}\gamma_a dx^{\mu}dx^{\nu}$ is a bi-vector and vector in the above two spaces, respectively)
Now back to our initial assertion: a spinor is a

*

*Scalar in spacetime manifold characterized by differential vector base $dx^{\mu}$. The spinor $\psi$ is a $0$-form.

*Sum of scalar, vectors, bi-vectors, ..., pseudo-scalar, in internal (spinor bundle) spacetime characterized by Dirac vector base $\gamma_a$: $\psi = \xi_s + \xi_v^{a}\gamma_a + \xi_{bv}^{ab}\gamma_a\gamma_b + ...$. The individual coefficients like $\xi_s$ and $\xi_v^a$ are just numbers (Grassmann odd though), not columns. In other words, a Dirac spinor (e.g., a neutrino and an electron putting together as an isospin doublet) spans the whole space of the 16 elements of the "Dirac algebra"! Not just some sub-space of it. It's partially evidenced via indirectly projecting a spinor to the measureable components such as scalar bi-linear $tr(\bar{\psi}\psi)$,  vector bi-linear (current) $tr(\bar{\psi}\gamma_a\psi)$, bi-vector bi-linear $tr(\bar{\psi}\gamma_a\gamma_b\psi)$, etc. Note that, here a Dirac spinor is not a 4*1 column anymore, rather, it lives in the same operator space (4*4 matrices, if you will, that is why we have to take traces tr(...) for Spinor bilinears above) spanned by the Dirac algebra. The conventional column spinor is just an idempotent projection (an individual left ideal like a neutrino or an electron)  of the matrix spinor. There are only 2 column spinors (electron/neutrino isospin doublet) instead of 4: the reduction from 4 to 2 has to do with the fact that 4*4 complex matrices are 2-fold cover of the real Dirac algebra. More precisely, the real Dirac algebra is isomorphic to 2*2 matrices of quaternions instead of complex numbers, hence there are only 2 columns. A beauty of this matrix spinor (isospin doublet) approach is that you can model internal Lorentz group transformation acting on one side of the spinor as $\exp(\epsilon^{ab}\gamma_a\gamma_b)\psi$ (a,b = 0, 1, 2, 3), and weak group transformation acting on the other side of the same spinor similarly as $\psi \exp(\epsilon'^{ab}\gamma_a\gamma_b)$ (a, b = 1, 2, 3). How about quarks and strong interactions? Hint: you have to go beyond Dirac algebra.

Note that there are two kinds (external  and internal) of Lorentz transformations:

*

*External Lorentz transformation (global rotation portion of local diffeomorphism) on differential forms (e.g. electromagnetic gauge field 1-form $A = A_{\mu}dx^{\mu}$) is performed in the spacetime manifold characterized by differential vector base $dx^{\mu}$.

*Internal Lorentz transformation $\exp(\epsilon_{ab}\gamma_a\gamma_b)$ on Dirac-algebra-valued objects is performed in the internal spacetime characterized by the whole Dirac algebra (spinor field $\psi$) or bi-vector/vector portion of it (spin connection 1-form $\omega$/tetrad 1-form $e$).

Most of times, we go back/forth (and get away with it) between the external and internal spaces (e.g. Kahler-Dirac fermion) without explicitly mentioning it, thanks to the soldering 1-form vielbein/frame/tetrad $e$, which is a vector in spacetime manifold characterized by differential vector base $dx^{\mu}$, as well as a vector in the internal/spinor bundle spanned by Dirac vector base $\gamma_{a}$.
In flat spacetime, the vielbein/frame/tetrad $e$ has the form:
$$
e = e^{a}_{\mu}\gamma_adx^{\mu} = \delta^{a}_{\mu}\gamma_adx^{\mu},
$$
which nicely bridges the two spaces, "soldering" $\gamma_a$ and $dx^{\mu}$ via delta function $\delta^{a}_{\mu}$ and producing Minkowskian metric
$$g_{\mu\nu} \sim tr(e^{a}_{\mu}\gamma_ae^{b}_{\nu}\gamma_b) = tr(\gamma_\mu \gamma_\nu) \sim \eta_{\mu\nu} .
$$
Note that
$$
<0|e^{a}_{\mu}|0>= \delta^{a}_{\mu}
$$
is a non-zero vacuum expectation value of the 1-form field $e$, which breaks both the external (diffeomorphism) and internal local Lorentz invariances. Without this God-given symmetry breaking effect, our spacetime will be metric-less and devoid of the notion of distance and time interval
$$g_{\mu\nu} = 0.$$
An (almost) metric-less spacetime would be perfect playground for wormholes and time/space travelers.

A: *

*There are no "two spacetimes". There is a single spacetime $M$, which is a four-dimensional Lorentzian manifold, and there's a bunch of bundles over it.

*The spin connection is formally a connection form on a $\mathrm{SO}(1,3)$-principal bundle over $M$ that can act on anything that transforms in a representation of the Lorentz algebra. It is not a bivector, it is a local 1-form that is $\mathfrak{so}(1,3)$-valued. So as a 1-form it has components $\omega_\mu$ and as a $\mathfrak{so}(1,3)$-valued object we may expand it in a basis of the Lorentz algebra. The commutators of the $\gamma$-matrices form a basis of $\mathfrak{so}(1,3)$, so we get your expansion $\omega = \omega_\mu\mathrm{d}x^\mu = {\omega_\mu}^{ab}[\gamma_a, \gamma_b] \mathrm{d}x^\mu$. For more on the spin connection, see also this answer of mine.

*A spinor field is now a function that takes values in some spinorial representation of $\mathfrak{so}(1,3)$, e.g. that labeled by $(1/2,1/2)$, the Dirac representation. Therefore, the spin connection can act on it. Put another way, a spinor field is a section of an associated bundle (the spinor bundle) to the bundle the spin connection lives on, other equivalently, the spin connection lives in the spinor bundle's frame bundle. Note that this is a spinor field. A "spinor" would more commonly be understood to not live on a manifold at all and just be a single vectors in the $(1/2,1/2)$-representation space.
However, all this talk of bundles is overkill for many physical applications, though it is good to be aware of its existence. Most of the time, it suffices to take the local viewpoint (in which the bundles are products), so that the spin connection is simply a $\mathfrak{so}(1,3)$-valued field that acts on other fields that take values in some representation of $\mathfrak{so}(1,3)$.
The expression
$$ \psi = \psi_s + \psi_v^a \gamma_a +\dots$$
you write down makes no sense in any of these contexts. You can pick a basis of the representation vector space the spinor takes values in and expand it in terms of it, but the $\gamma$-matrices act on the spinor, they are not a basis for its space.

A: I think that you actually mean "element of the Dirac algebra" where you say "Dirac spinor".
The Dirac algebra is the Clifford algebra of Minkowski space. This is the smallest algebra that contains Minkowski space $\mathbb R^{1,3}$ itself, and so that for elements $v,w\in \mathbb R^{1,3}$ we have $vw = \langle v,w\rangle$, where $vw$ is the product in the Dirac algebra, and $\langle v,w\rangle$ is the inner product of the two, which is a scalar, and as such an element of the Dirac algebra as well. This has a representation as an algebra of $4\times 4$ matrices, as you know well.
If we write $\gamma^0,\gamma^1,\gamma^2,\gamma^3$ for the image of an orthonormal basis of $\mathbb R^{1,3}$ in the Dirac algebra, then it is not hard to see that elements of the form $\gamma_{i_1}\cdots\gamma_{i_n}$ indeed generate the Dirac algebra over $\mathbb R$ (or $\mathbb C$ if we look at the complex Dirac algebra, as we do in many situations), in other words, every element of the Dirac algebra can be written in the form that you wrote down.
The invertible elements of the Dirac algebra contain an important subgroup, namely $\text{Spin}(\mathbb R^{1,3})$ of elements of norm 1. Elements of the spin group are not called spinors either. This group has a unique complex irreducible representation (up to complex conjugation). It is elements of this representation that are almost spinors: namely, if we lift the metric structure of the tangent bundle of Minkowski space to a Spin structure, the sections are what are called Dirac spinors. This is what ACuriousMind was talking about.

A: These are K{\"a}hler-Dirac fermions
As was pointed out in the comments, consider a $4 \times 1$ column representing a Dirac spinor.  Clearly one can embed this in a $4 \times 4$ matrix of zeros and the equation
\begin{equation}
(\gamma^{\mu}\partial_{\mu} - m)\Psi = 0 \quad \quad (1)
\end{equation}
makes sense.  In fact one can write any $4 \times 4$ matrix as
$$
\Psi = f_0 + f_{\mu}\gamma^{\mu} + \frac{1}{2}f_{\mu \nu} \gamma^{\mu} \gamma^{\nu} + \frac{1}{6}f_{\mu \nu \sigma}\gamma^{\mu}\gamma^{\nu}\gamma^{\sigma} + f_{0123}\gamma^{0}\gamma^{1}\gamma^{2}\gamma^{3}
$$
including the column from above.
Now, consider the exterior derivative and its adjoint, $d$ and $\delta$.  One can construct a $p$-form field as
a linear combination of $p$-forms as
$$
\omega = f_{0} + f_{\mu} dx^{\mu} + \frac{1}{2}f_{\mu \nu} dx^{\mu} dx^{\nu} + \frac{1}{6}f_{\mu \nu \sigma}dx^{\mu}dx^{\nu}dx^{\sigma} + f_{0123} dx^{0}dx^{1}dx^{2}dx^{3}
$$
and apply the operator $(d - \delta)$ to $\omega$.  What one finds is that the action of $\gamma^{\mu}\partial_{\mu}$ on $\Psi$ is the same as the action of $(d - \delta)$ on $\omega$.  But since $\Psi$ is a $4 \times 4$ matrix, Eq. (1) is four copies of the Dirac equation, one for each column.  In turn,
$$
((d - \delta) - m)\omega = 0 \quad \quad (2)
$$
is equivalent to four copies of the Dirac equation since the two operators act identically on their respective objects.  However, Eq. (2) is valid for any metric, while Eq. (1) is only good in flat spacetime, and gauging the derivative does not make Eq.(1) and (2) equal.
The references I learned this from are
Banks and Rabin.
I hope this helps, let me know if I should clarify, maybe I can add some more later.


text:
Q: How to avoid mongo from returning duplicated documents by iterating a cursor in a constantly updated big collection? Context
I have a big collection with millions of documents which is constantly updated with production workload. When performing a query, I have noticed that a document can be returned multiple times; My workload tries to migrate the documents to a SQL system which is set to allow unique row ids, hence it crashes.
Problem
Because the collection is so big and lots of users are updating it after the query is started, iterating over the cursor's result may give me documents with the same id (old and updated version).
What I'v tried
const cursor = db.collection.find(query, {snapshot: true});
while (cursor.hasNext()) {
   const doc = cursor.next();
   // do some stuff
}

Based on old documentation for the mongo driver (I'm using nodejs but this is applicable to any official mongodb driver), there is an option called snapshot which is said to avoid what is happening to me. Sadly, the driver returns an error indicating that this option does not exists (It was deprecated).
Question
Is there a way to iterate through the documents of a collection in a safe fashion that I don't get the same document twice?
I only see a viable option with aggregation pipeline, but I want to explore other options with standard queries.

A: Finally I got the answer from a mongo changelog page:
MongoDB 3.6.1 deprecates the snapshot query option.
For MMAPv1, use hint() on the { _id: 1} index instead to prevent a cursor from returning a document more than once if an intervening write operation results in a move of the document.
For other storage engines, use hint() with { $natural : 1 } instead.
So, from my code example:
const cursor = db.collection.find(query).hint({$natural: 1});
while (cursor.hasNext()) {
   const doc = cursor.next();
   // do some stuff
}


text:
Q: Can you explain/simplify this regular expression (PCRE) in PHP? preg_match('/.*MyString[ (\/]*([a-z0-9\.\-]*)/i', $contents, $matches);

I need to debug this one. I have a good idea of what it's doing but since I was never an expert at regular expressions I need your help.
Can you tell me what it does block by block (so I can learn)?
Does the syntax can be simplified (I think there is no need to escape the dot with a slash)?

A: The regexp...
'/.*MyString[ (\/]*([a-z0-9\.\-]*)/i'

.* matches any character zero or more times
MyString matches that string. But you are using case insensitive matching so the matched string will spell "mystring" by but with any capitalization
EDIT: (Thanks to Alan Moore) [ (\/]*. This matches any of the chars space ( or / repeated zero of more times. As Alan points out the final escape of / is to stop the / being treated as a regexp delimeter.
EDIT: The ( does not need escaping and neither does the . (thanks AlexV) because:

All non-alphanumeric characters other than \, -, ^ (at the start) and
  the terminating ] are non-special in character classes, but it does no
  harm if they are escaped.
  -- http://www.php.net/manual/en/regexp.reference.character-classes.php

The hyphen, generally does need to be escaped, otherwise it will try to define a range. For example:
[A-Z]  // matches all upper case letters of the aphabet
[A\-Z] // matches 'A', '-', and 'Z'

However, where the hyphen is at the end of the list you can get away with not escaping it (but always best to be in the habit of escaping it... I got caught out by this].
([a-z0-9\.\-]*) matches any string containing the characters a through z (note again this is effected by the case insensitive match), 0 through 9, a dot, a hyphen, repeated zero of more times. The surrounding () capture this string. This means that $matches[1] will contain the string matches by [a-z0-9\.\-]*. The brackets () tell preg_match to "capture" this string.
e.g.
<?php
  $input = "aslghklfjMyString(james321-james.org)blahblahblah";
  preg_match('/.*MyString[ (\/]*([a-z0-9.\-]*)/i', $input, $matches);
  print_r($matches);
?>

outputs
Array
(
    [0] => aslghklfjMyString(james321-james.org
    [1] => james321-james.org
)

Note that because you use a case insensitive match...
$input = "aslghklfjmYsTrInG(james321898-james.org)blahblahblah";

Will also match and give the same answer in $matches[1]
Hope this helps....

A: Let's break this down step-by step, removing the explained parts from the expression.
"/.*MyString[ (\/]*([a-z0-9\.\-]*)/i"

Let's first strip the regex delimiters (/i at the end means it's case-insensitive):
".*MyString[ (\/]*([a-z0-9\.\-]*)"

Then we've got a wildcard lookahead (search for any symbol any number of times until we match the next statement.
"MyString[ (\/]*([a-z0-9\.\-]*)"

Then match 'MyString' literally, followed by any number (note the '*') of any of the following: ' ', '(', '/'. This is probably the error zone, you need to escape that '('. Try [ (/].
"([a-z0-9\.\-]*)"

Then we get a capture group for any number of any of the following: a-z literals, 0-9 digits, '.', or '-'.
That's pretty much all of it.


text:
Q: How do I output env as a runnable shell script You can trivially output your environment as a runnable shell script using
env > my_env

... later in another script ...
set -a
source my_env

This works for the most trivial cases, but fails if any special chars or spaces are in env.
How can I fix the above script so it works with stuff like a='"'"'" ?

A: Use set instead of env:
○ → set | grep LESS
LESS=-R
LESSCLOSE='/usr/bin/lesspipe %s %s'
LESSOPEN='| /usr/bin/lesspipe %s'

○ → env | grep LESS
LESS=-R
LESSOPEN=| /usr/bin/lesspipe %s
LESSCLOSE=/usr/bin/lesspipe %s %s

Thanks to this similar question we can do this to get JUST environment variables as follows:
○ → (set -o posix; set) | grep LESS
LESS=-R
LESSCLOSE='/usr/bin/lesspipe %s %s'
LESSOPEN='| /usr/bin/lesspipe %s'

Try this behemoth which should print just the difference from a "pristine" shell. YMMV:
diff --old-line-format='%L' --unchanged-line-format= --new-line-format= \
    <(bash -c 'set -o posix; set' | sort) \
    <(env -i bash -c 'set -o posix; set' | sort)

A: The following uses bash's printf %q to escape values correctly regardless of their content. It's guaranteed to handle literally any value possible -- quotes, newlines, etc -- so long as the shell sourcing its output is bash, and so long as the operating system in use supports the /proc/self/environ facility first provided by Linux to emit the contents of the environment as a NUL-delimited stream. It uses special quoting forms such as $'\n' as and where appropriate, so its output may not be honored by pure POSIX interpreters.
#!/usr/bin/env bash
while IFS= read -r -d '' kvname; do
  k=${kvname%%=*}
  v=${kvname#*=}
  printf '%q=%q\n' "$k" "$v"
done </proc/self/environ

Note that you'll want to source the output, not run it as an external executable, if you want your current shell's environment to change. If you don't want to set -a before sourcing, add a leading export to the format string.

A: Simplest solution seems to be
export -p > my_env


text:
Q: How to block/unblock Users in Angular with node i created Admin panel and add some users in database and show in admin panel . I want to block and unblock user by clicking in block button

Html

<button type="button" (click)="isDisabled = false" class="fa fa-ban" aria-hidden="true" >

[enter image description here][1]
Componet.ts
changestatus(user) {
     console.log(user);
     return false;
     this.adminServiceService.changeuserstatus(user)
     .subscribe((data: any) => {
       alert('User Disable');
       this.ngOnInit();
     });
   }
 }

Node
exports.isActive = function(req,res){
  user.findbyId(id, function(err, user){
    user.status= !user.status;
    user.save(function(err){
      if(err){
        console.error("Error!!!!");
      }
    })
  })
}

Node Route
router.get('/ban/id',jobProviderCtrl.isActive)

angular Route
    return this.http.get(`${this.uri}/banuser/${id}`);
  }```

Help me

  [1]: https://i.stack.imgur.com/XIj3q.png

A: You can try to create a middleware:
const adminAccess = function (req, res, next) {
  //write current user query here ..
  if(!user.status)
    res.redirect('login');
  next();
});

Then you can use this middleware in your routes:
router.get('/admin/dashboard', adminAccess, loadDashboard);


text:
Q: Ruby on rails, Form buttons get their routes mixed up While making a form in Ruby on Rails I encoutered something peculiar, My submit button performs the action of another button in the form.
<%=form_for(happening) do |f|%>
   <%=f.text_field :name, class:"updateInput" %>
   <%=f.submit "Save", class:"editButton" %>
   <%= button_to "Delete", happening, method: :delete, class:"editButton"%>
   <input type="datetime-local" value="<%= happening.get_html_date %>">
<%end%>

When I click the submit button in this form, it will be routed to the destroy action, rather than the update one.
When I remove the deletebutton, everything is routed properly.
Does someone have an explination for this? Thanks

A: You're seeing this behavior because there's more than meets the eye when you use the button_to helper. button_to doesn't just create a button -- it actually creates an entire form, with the actual button serving as the form's submit button.
By including your button_to helper within a form, you're violating HTML's "no nested forms" rule and effectively adding a second submit button for your form which overrides the intended submit button. There's a difference between a submit button and an input of type button in HTML, and as I mentioned already, button_to creates a submit button.
If you move that button_to outside of your form as Ahmad pointed out, you'll have un-nested your forms and your view should behave as expected.
Consult the API doc for additional details.

A: Your delete button should be outside your form.
<%=form_for(happening) do |f|%>
   <%=f.text_field :name, class:"updateInput" %>
   <%=f.submit "Save", class:"editButton" %>
   <input type="datetime-local" value="<%= happening.get_html_date %>">
<%end%>

<%= button_to "Delete", happening, method: :delete, class:"editButton"%>


text:
Q: Parsing the html page with images In that video I provided, the man is parsing Google pictures.
https://www.youtube.com/watch?v=MaWm1VpWj1A&list=LLiAY9i8Qha2Vx2j21Jk88PA&index=2&t=0s
import requests
from bs4 import BeautifulSoup as bs
import random
import json
import lxml.html

ua = "Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36
(KHTML, как Gecko) Chrome / 58.0.3029.110 Safari / 537.36"

headers = {"User-Agent": random.choice(ua)}

r = requests.get("https://www.google.ru/search?tbm=isch&q=яблоко",
headers=headers)

html = r.content

soup = bs(html, "lxml")

images = soup.find_all("div", {"class": "rg_meta notranslate"})

images = [i.text for i in images]
images = [json.loads(i) for i in images]

print(images)

but I've got nothing but

[]
Process finished with exit code 0

soup - displays html text, but images = soup.find_all("div", {"class": "rg_meta notranslate"}) - displays nothing
I've already reviewed a lot of articles and I can find something everywhere and output it using find_all - I can't do anything and why, I don't know.
please help me understand what's going on

A: To see the page as requests does, you have to turn off Javascript (NoScript is a browser extension that does it).
Then to grab the images you must identify them in the html :

As you can see here, there are no elements with classes "rg_meta" and "no_translate", that's why you get nothing.
As it has been suggested in the comments, you could use :
soup.find_all('img')

Alternatively, you could get the table with the class 'images_table', get its 'tbody' element, and iterate on every 'tr' and 'td' elements to get the images.


text:
Q: How to use encypted home directory after reinstallation I reinstalled Ubuntu on a machine with encrypted home directories. After that installation I have edited the fstab to boot the old home partition in /home. After doing so I can not login anymore with LDM. If I type my password, witch is the same as before, after a short moment of activity I am referred back to login page.
I think this is due to the fact, that my home directory is not decrypted correctly. But I read here that this should work. What am I supposed to do?

A: I found the solution: You have to install first the package »ecryptfs-utils«. If you can't login to X, you can do this still by entering a console by typing Crt+Alt+F2, login there, and typ:
   sudo apt-get install ecryptfs-utils

After that you can perform the following command:
   sudo ecryptfs-recover-private

This tool will ask you whether or not you remember your password, if this be the case you can type it in and after that your home directory should work again.


text:
Q: Could someone help me figure out what I am missing in this Trigger creation? I keep receiving the below error: I keep receiving the below error when I run an update to execute the trigger:
ERROR:  null value in column "invoice_number" of relation "invoice" violates not-null constraint
DETAIL:  Failing row contains (null, null, null, null, null, null, null, null, null, null, null, Paid, null, null).
CONTEXT:  SQL statement "INSERT INTO Invoice(service_notes)
         VALUES ('Paid')"
PL/pgSQL function paid_function() line 20 at SQL statement
SQL state: 23502

Here is my function:
CREATE OR REPLACE FUNCTION public.paid_function()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
paid_date date;
service_notes varchar(500);

BEGIN
    IF NEW.paid_date != OLD.paid_date THEN
         INSERT INTO Invoice(service_notes)
         VALUES ('Paid');
    END IF;
    RETURN NEW;
END;
$BODY$;

Here is the statement:
CREATE OR REPLACE TRIGGER trigger_paid
    AFTER UPDATE OF paid_date
    ON public.invoice
    FOR EACH ROW
    WHEN (new.paid_date != old.paid_date)
    EXECUTE FUNCTION public.paid_function();

Here is the update:
UPDATE Invoice SET paid_date = '10/25/2022'
WHERE invoice_number ='9003';`

I tried adding in all the attributes from the invoice table under declare but the error still comes through. I can't figure out what I am missing to make this work properly. The goal is to have the service notes say Paid if there is a date in the paid date column. Could someone help me figure out what I am missing in this Trigger creation? I also tried removing the of paid_date in the create trigger statement.
I am not sure what other details are needed. Comment back if more information is needed.


text:
Q: Reduce two rows into a single row in R I have a situation such like this:
df<-data.frame(A=c(1, NA), B=c(NA, 2), C=c(3, NA), D=c(4, NA), E=c(NA, 5))
df
   A  B  C  D  E
1  1 NA  3  4 NA
2 NA  2 NA NA  5

What I wanted is, conditioning on all length(!is.na(df$*))==1, reduce df to :
df
   A  B  C  D  E
 1 1  2  3  4  5

A: As long as the resulting rows are equal, you can use:
dfNew <- do.call(data.frame, lapply(df, function(i) i[!is.na(i)]))

which results in
dfNew
A B C D E
1 1 2 3 4 5


text:
Q: How to check disk-usage in specific schema and sum for all schema? pg9+ The documentation about disk-usage have no "fast and simple" clue or information... So is faster to check here.

*

*When I try SELECT pg_relation_filepath(oid), relpages FROM pg_class WHERE relname = 'big' it  is working fine... but "big" is not a "public.big", it is a "othername.big", if there are public also, will be ambiguous.

*When I try SELECT pg_relation_filepath(oid), relpages FROM pg_class WHERE relname = 'othername.big' not works.
I need to compare disk-usage of tables and to check (or sum) all schema disk-usage.

A: To get Schema size :
SELECT schemaname, pg_size_pretty(t.taille::bigint) AS taille_table, pg_size_pretty(t.taille_totale::bigint) AS taille_totale_table
  FROM (SELECT schemaname,
               sum(pg_relation_size(schemaname || '.' || tablename)) AS taille,
               sum(pg_total_relation_size(schemaname || '.' || tablename)) AS taille_totale
          FROM pg_tables
          WHERE relname_exists(tablename,schemaname)   -- see note
GROUP BY schemaname) as t ORDER BY taille_totale DESC;

And for Tables by Schema, you can do this :
SELECT schemaname, tablename, tablespace, pg_size_pretty(taille) AS taille_table, pg_size_pretty(taille_totale) AS taille_totale_table
  FROM (SELECT *,
               pg_relation_size(schemaname || '.' || tablename) AS taille,
               pg_total_relation_size(schemaname || '.' || tablename) AS taille_totale
          FROM pg_tables) AS tables
          WHERE relname_exists(tablename,schemaname)   -- see note
 ORDER BY taille_totale DESC;

NOTE: to avoid "ERROR: relation 'x.y' does not exist", needs to guard  the string before use it, so
use to_regclass(rel_name) in Postgres 9.4+... See https://stackoverflow.com/a/24089729
or use a generic (see "SwissKnife libraries") function for any pg version, as below
CREATE or replace FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $$
  SELECT EXISTS (
     SELECT 1
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
            WHEN COALESCE(x[2],'')>'' THEN   n.nspname = x[1]      AND c.relname = x[2]
            WHEN $2 IS NULL THEN         n.nspname = 'public'  AND c.relname = $1
            ELSE                         n.nspname = $2        AND c.relname = $1
     END
  )
$$ language SQL IMMUTABLE;

A: Using pg_class  and simplifying layout
Same results as Hervé's queries (that used pg_tables)... Was adapted from  https://wiki.postgresql.org/wiki/Disk_Usage
-- -- -- -- --
-- DISK-USAGE

CREATE VIEW pgvw_class_usage AS
  SELECT *, pg_size_pretty(table_bytes) AS table_size
  FROM (
    SELECT nspname , relname, total_bytes
           , total_bytes-index_bytes-COALESCE(toast_bytes,0) AS table_bytes
    FROM (
        SELECT nspname , relname
          , pg_total_relation_size(c.oid) AS total_bytes
          , pg_indexes_size(c.oid) AS index_bytes
          , pg_total_relation_size(reltoastrelid) AS toast_bytes
        FROM pg_class c
        LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
        WHERE relkind = 'r'
    ) a
  ) t
  ORDER BY 1,2
; -- eg. SELECT * FROM pgvw_class_usage WHERE relname='foo' AND nspname='bar';

CREATE VIEW pgvw_nsclass_usage AS
  SELECT *, pg_size_pretty(table_bytes) as table_size
  FROM (
    SELECT nspname, count(*) as n_tables,
           sum(total_bytes) as total_bytes, sum(table_bytes) as table_bytes
    FROM pgvw_class_usage
    GROUP BY nspname
  ) t
; -- eg. SELECT * FROM pgvw_nsclass_usage WHERE nspname='bar';

EXAMPLE:
      nspname       | n_tables | total_bytes | table_bytes | table_size
--------------------+----------+-------------+-------------+------------
 bench1             |        8 |     4718592 |     3825664 | 3736 kB
 dataset            |        4 |     8552448 |     6225920 | 6080 kB
 information_schema |        7 |      352256 |      294912 | 288 kB
 pg_catalog         |       54 |     9003008 |     4734976 | 4624 kB
(4 rows)


text:
Q: Angular project can't be Build? I migrated my current project from Bootstrap 4 to Bootstrap 5 and since then jenkins can't build the project anymore.
I just get the cryptic message :
An unhandled exception occurred: Cannot destructure property 'bold' of 'core_1.terminal' as it is undefined.

We searched for that error and couldn't find the meaning of this!
I can build the project on my local machine without any problems but jenkins just don't like to build it.
I just changed HTML and SCSS files nothing else!

A: If you ever worked with @angular-devkit package specially if you work with Ionic framework  you might have noticed following error at least once
An unhandled exception occurred: Cannot destructure property 'bold' of 'core_1.terminal' as it is undefined.

to solve this error you can run following commands in your terminal (administrator access is recommended)
npm -g install chalk

npm -g install @angular-devkit/core

In some cases it might not solve your problem than you can try to remove angular from your system and reinstall it globally. (use commands below)
npm uninstall -g @angular/cli

npm cache clean --force

npm install -g @angular/cli

Source


text:
Q: Freeing memory in C or C++ Let we declare a pointer
int *ptr;
ptr=malloc (10 *sizeof (int));
free (ptr);

The question is how free() will free memory. Let int be of 4 bytes and the memory will be 40 bytes for int.
The compiler will understand to remove first memory location provided by malloc but how it will clear another 9 int data that is other 36 bytes?

A: malloc leaves notes that free reads. In particular, it leaves a note that says how many bytes were allocated.


text:
Q: Change DataGridTemplateColumn when DataColumn is clicked WPF In my WPF document, I have a DataGrid:
<DataGrid>
    <DataGrid.ColumnHeaderStyle >
        <Style BasedOn="{StaticResource MaterialDesignDataGridColumnHeader}" TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="FontSize" Value="11"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
        </Style>
    </DataGrid.ColumnHeaderStyle>
    <DataGrid.RowStyle>
        <Style BasedOn="{StaticResource MaterialDesignDataGridRow}" TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <Trigger Property="DataGridCell.IsSelected" Value="True">
                    <Setter Property="Background" Value="Blue" />
                    <Setter Property="BorderBrush" Value="Blue" />
                </Trigger>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="Blue" />
                </Trigger>
                <Trigger Property="IsMouseOver" Value="False">
                    <Setter Property="Background" Value="Red" />
                </Trigger>
            </Style.Triggers>
            <Setter Property="ContextMenu" Value="{StaticResource TasksMenu}"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridRow}">
                        <Border x:Name="DGR_Border" BorderBrush="Transparent" BorderThickness="0" Margin="0,15,0,0" Background="{TemplateBinding Background}" SnapsToDevicePixels="True" Height="50" CornerRadius="10">
                            <Grid Height="auto" Width="auto">
                                <SelectiveScrollingGrid>
                                    <SelectiveScrollingGrid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </SelectiveScrollingGrid.ColumnDefinitions>
                                    <SelectiveScrollingGrid.RowDefinitions>
                                        <RowDefinition Height="*"/>
                                        <RowDefinition Height="Auto"/>
                                    </SelectiveScrollingGrid.RowDefinitions>
                                    <DataGridCellsPresenter Grid.Column="1" ItemsPanel="{TemplateBinding ItemsPanel}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" FontSize="5"/>
                                    <DataGridDetailsPresenter Grid.Column="1" Grid.Row="1" SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Visibility="{TemplateBinding DetailsVisibility}"/>
                                    <DataGridRowHeader Grid.RowSpan="2" SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical" FontSize="5" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                                </SelectiveScrollingGrid>
                            </Grid>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.RowStyle>
    <DataGrid.Columns>
        <DataGridTemplateColumn x:Name="THISISTHECOLUMN" Width="*" MaxWidth="60">
            <DataGridTemplateColumn.HeaderStyle>
                <Style BasedOn="{StaticResource MaterialDesignDataGridColumnHeader}" TargetType="{x:Type DataGridColumnHeader}">
                    <Setter Property="HorizontalAlignment" Value="Left" />
                    <Setter Property="FontSize" Value="11"/>
                </Style>
            </DataGridTemplateColumn.HeaderStyle>
            <DataGridTemplateColumn.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Style.Triggers>
                        <Trigger Property="DataGridCell.IsSelected" Value="True">
                            <Setter Property="Background" Value="Red" />
                            <Setter Property="BorderBrush" Value="Red" />
                        </Trigger>
                    </Style.Triggers>
                    <Setter Property="Padding" Value="20"/>
                    <!--<Setter Property="Height" Value="57"/>-->
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="DataGridCell">
                                <Border Margin="2" BorderThickness="2" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" CornerRadius="5">
                                    <ContentPresenter />
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <!--<Setter Property="BorderBrush"><Setter.Value><MultiBinding><MultiBinding.Converter><local:CellForegroundMultiValueConverter /></MultiBinding.Converter><Binding RelativeSource="{RelativeSource Self}" Path="Column.Header"/><Binding/><Binding Path="HasChanges" /></MultiBinding></Setter.Value></Setter>-->
                </Style>
            </DataGridTemplateColumn.CellStyle>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Background="Blue" Height="40" CornerRadius="10" BorderBrush="Transparent">
                        <TextBlock Margin="5 0" FontSize="15" Width="auto" Text="1" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="Yellow"/>
                    </Border>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Header 1" Binding="{Binding Header1, UpdateSourceTrigger=PropertyChanged}">
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <Setter Property="FontSize" Value="8" />
                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>
        <DataGridTextColumn Header="Header 2" Binding="{Binding Header2, UpdateSourceTrigger=PropertyChanged}">
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <Setter Property="FontSize" Value="8" />
                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>
        <DataGridTextColumn Header="Header 3" Binding="{Binding Header3, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <Setter Property="FontSize" Value="8" />
                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <Trigger Property="DataGridCell.IsSelected" Value="True">
                    <Setter Property="Background" Value="Blue" />
                    <Setter Property="BorderBrush" Value="Blue" />
                </Trigger>
            </Style.Triggers>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Padding" Value="20"/>
            <Setter Property="FontSize" Value="9"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                            <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="Foreground">
                <Setter.Value>
                    <MultiBinding>
                        <MultiBinding.Converter>
                            <local:CellForegroundMultiValueConverter />
                        </MultiBinding.Converter>
                        <Binding RelativeSource="{RelativeSource Self}" Path="Column.Header"/>
                        <Binding/>
                        <Binding Path="HasChanges" />
                    </MultiBinding>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

On button hover, the DataGridColumn changes from Red to Blue perfectly as intended, but when I click on it, the first DataGridTemplateColumn (labelled THISISTHECOLUMN) does not change colour. How can I make it so that when the main DataGridColumn is clicked, it also changes colour?
This is how it looks like so far:

A: Add a trigger to the DataGridRow style to change the DGR_Border border color on selection to Blue.
<Style BasedOn="{StaticResource MaterialDesignDataGridRow}" TargetType="{x:Type DataGridRow}">
   <Style.Triggers>
      <!-- ...your other triggers. -->
      <Trigger Property="IsSelected" Value="True">
         <Setter Property="Background" Value="Blue" />
      </Trigger>
   </Style.Triggers>
   <!-- ...rest of the style. -->
</Style>

Change the DataGridCell triggers to set a Blue Background and BorderBrush, instead of Red.
<Style TargetType="{x:Type DataGridCell}">
   <Style.Triggers>
      <Trigger Property="DataGridCell.IsSelected" Value="True">
         <Setter Property="Background" Value="Blue" />
         <Setter Property="BorderBrush" Value="Blue" />
      </Trigger>
   </Style.Triggers>
   <!-- ...your other setters. -->
</Style>


text:
Q: How to center a text while still being aligned to the left/right? I have an unordered vertical list..

home

portfolio

about

contact

css:
 div {
 width: 600px;
 }
 ul {
 text-align: center;
 }

What I really want is the list to be text aligned left, while the ul is still horizontally in the center. is there a way to that?

A: You can do something like this to center dynamically generated content of varying widths:
div { text-align: center; }

ul { display: inline-block; }

li { text-align: left; }

jsFiddle example
Alternatively, you can set a defined width on the parent, and use margin:0px auto, assuming it is a block level element.
ul {
    width: 100px;
    margin: 0px auto;
}

jsFiddle example


text:
Q: Fundamental group of infinitely many glued copies of a space Let $C=\{p\in \mathbb{R^3}: \left\|p\right\|_{\infty}\le 1\}$ be a cube in $\mathbb{R}^3$. Let $X$ be a compact, path-connected topological space  in $\mathbb{R}^3$ such that $X\subset C$, $\{z=1\}\cap X=(0, 0, 1)$ and $\{z=-1\}\cap X=(0, 0, -1)$.
Let $Y:=\bigcup_{n\in \mathbb{Z}} \{X+(0, 0, n)\}$.
For example if $X=S^2$, $Y$ is illustrated in the following picture
If $\pi_1(X)=0$, it is easy to show that $\pi_1(Y)=0$.
Now suppose $\pi_1(X)\neq 0$, what can we say about $\pi_1(Y)$ ? I know this is a vague question: I'm particularly interested to know if it is true that $\pi_1(X)$ is not finitely generated, and to "compute" $\pi_1(Y)$ in the case $X\sim S^1\times S^1$.
My attempt to study $\pi_1(Y)$. Let the group $\mathbb{Z}$ act on $Y$ by traslation. The projection $p: Y\to Y/\mathbb{Z}$ is a covering map. We know that $p_*$ is injective, so $\pi_1(Y)\hookrightarrow \pi_1(Y/\mathbb{Z})$. Maybe, studying $\pi_1(Y/\mathbb{Z})$ we can have some information on $\pi_1(Y)$.


text:
Q: How to add constraints to UIStackView inside of a UITableViewCell swift programmatically? I have a function that creates an array UIStackViews with UIButtons inside of it:
func generateStackViews() -> [UIStackView] {
    var stackViewArray = [UIStackView]()
    let finalButtonArray = generateButtons()
    for buttons in finalButtonArray{
        stackViewArray.append(createStackView(subViews: buttons))
    }
    return stackViewArray
}

I then add that array to a tableViewCell:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "First")!
    cell.contentView.addSubview(generateStackViews()[indexPath.row])
    return cell
}

Everything works fine, but when I try to add constraints to pin the stackViews to the cells, I get this error:

failure in -[UITableViewCell _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:]

I tried adding the constraints in the function that creates the stackViews and in the cellForRowAt function, tried to pin it to the contentView, cell and tableView, but neither worked and I got the same error message.
Where is my logic failing?

A: call this method to addContraints Programatically.
func addSubviewWithConstraint(to parentView: UIView, and childView: UIView, top:CGFloat, bottom:CGFloat, leading:CGFloat, trailing:CGFloat) {
    parentView.addSubview(childView)
    //Below line tells the view to not use AutoResizing
    childView.translatesAutoresizingMaskIntoConstraints = false
    // set top constraint
    let topConstraint = NSLayoutConstraint(item: childView, attribute: .top, relatedBy: .equal, toItem: parentView, attribute: .top, multiplier: 1, constant: top)
    // set Bottom constraint
    let bottomConstraint = NSLayoutConstraint(item: childView, attribute: .bottom, relatedBy: .equal, toItem: parentView, attribute: .bottom, multiplier: 1, constant: bottom)
    // set leading constraint
    let leadingConstraint = NSLayoutConstraint(item: childView, attribute: .leading, relatedBy: .equal, toItem: parentView, attribute: .leading, multiplier: 1, constant: leading)
    // set Bottom constraint
    let trailingConstraint = NSLayoutConstraint(item: childView, attribute: .trailing, relatedBy: .equal, toItem: parentView, attribute: .trailing, multiplier: 1, constant: trailing)
    //Add all constraints to parentView
    parentView.addConstraint(topConstraint)
    parentView.addConstraint(bottomConstraint)
    parentView.addConstraint(leadingConstraint)
    parentView.addConstraint(trailingConstraint)
}

and call the above method like this.
self.addSubviewWithConstraint(to: cell.contenetView, and: stackView, top: 0, bottom: 0, leading: 0, trailing: 0)


text:
Q: How to uninstall non dependency packages? How do you find all packages that were manually installed which are not a dependency of any other installed packages?

A: The short answer is: use aptitude like in the following:
aptitude -F%p search '?installed?not(?automatic)

But unfortunately this command returns many packages that match the query but are not what you expect, for two reasons:

*

*there are packages installed during initial installation of the system that result as non automatically installed

*packages installed as dependencies of a metapackage also can result as non automatically installed
The solution I came to some time ago is a match between the preceding command and the dpkg logs, that at least try to remove the influence of the point 1. in the preceding problems' list:
#!/bin/bash

export LC_COLLATE=C

eval $(lesspipe)

vars=($(less $(ls -rt /var/log/dpkg.log*) | grep 'status installed grub-pc' | head -1))
date="${vars[0]}"
time="${vars[1]}"

join \
  <(aptitude -F%p search '?installed?not(?automatic)' |
    sort) \
  <(less $(ls -rt /var/log/dpkg.log*) |
    awk -v date=$date -v time=$time '(($1 == date && $2 > time) || $1 > date) && $3 == "install" { print $4, $1, $2 }' |
    sort -u) |
  awk '{ print $2, $3, $1 }' |
  sort

This assume that grub-pc is the last package installed during initial installation, and is in no way perfect, but can give you a rough information to start from.


text:
Q: Why do I need to specify a name in spark_read_csv() and also assign it into an object? If I understand the usuage correctly (if not please correct me) sparklyr::spark_read_csv() should be used like so:
my_table <- spark_read_csv(sc = my_connnection,
name = "my_table",
path = "path/to/my/data")

This seems to me (I think wrongly) to violate DRY. I am naming my object twice, once in the assignment of the output of the function, and again in the supplied argument to name, which has no defaults and is "The name to assign to the newly generated table."
Why do I 'name' my output from the function twice? Is there a 'spark' object that takes the name argument of the function behind the scenes? Is there a reason to name them differently, or the same?

A: You don't have to assign it to an object. You can just access it by name:
dplyr::tbl(sc, "some_name")

or
sc %>% spark_session() %>% invoke("sql", "SELECT * FROM my_table")

but in general, it is a matter of design. sparklyr + dplyr combination treats Spark like a database. When you call spark_read_csv it create a temporary table under the name which can be used by the dplyr backend,
Unless you plan it by name you can use a random string (to avoid name clashes).


text:
Q: sqlite, how to avoid insert new record when I delete parent? I use C# and EF 4.4 Well, in SQLLite there is not exist the possibility to delete on cascade, or I don't know how.
Imagine that I have two tables, Table A and Table B. The table B has the IDtableA field, because is a child, and imagine that I have the following situation:
1.- user A load record 1 from TableA and load it in the context.
2.- user A load all the child records from table B.
3.- user B add a new record to table B that is child of table A.
4.- user A save changes and delete record 1 and all the childs that he loaded in the first time, but not include the new child add by the user B.
So in SqlLite I don't have a model, neither realationships between tables, when user B add a new child, not check if the parent exists.
is it posible ensure reference integrity in Sqlite?
Thanks.

A: SQLite supports foreign keys and "on delete cascade", but in the new versions.
You can see this article in official SQLite website:
sqlite.org/foreignkeys.html
The say:

This document describes the support for SQL foreign key constraints
  introduced in SQLite version 3.6.19.

Also, you have to explicitly enable foreign keys for every connection.
this question may help you: Enabling Foreign key constraints in SQLite
You can do it by changing the connection string and add:
foreign keys=true;


text:
Q: .NET Excel Interop Worksheet.Copy failing after 255 sheets Got a question that I've found only rarely asked, and seen no good responses for.
Very simple piece of code, in VB.NET:
Imports System.Data

Imports System.IO
Imports System.Runtime.InteropServices
Dim anExcelApplicationClass As Microsoft.Office.Interop.Excel.Application

    anExcelApplicationClass = New Microsoft.Office.Interop.Excel.Application
    anExcelApplicationClass.Visible = False
    anExcelApplicationClass.UserControl = False
    anExcelApplicationClass.DisplayAlerts = False
    anExcelApplicationClass.ScreenUpdating = False

    Dim devWorkbooks As Workbooks
    Dim devWorkbook As Workbook
    Dim masterTempWorksheet As Worksheet
    Dim tempWorksheet As Worksheet

    devWorkbooks = anExcelApplicationClass.Workbooks
    devWorkbook = devWorkbooks.Open(DevFilePath, 0, False, 5, "", "", False, XlPlatform.xlWindows, "", True, False, 0, True, False, False)

    Dim tempCounter As Integer = 0
    While tempCounter < 500
        tempCounter = tempCounter + 1
        masterTempWorksheet.Copy(Type.Missing, masterTempWorksheet)
        tempWorksheet = CType(devWorkbook.Sheets(3), Worksheet)
        tempWorksheet.Name = tempCounter.ToString()
    End While

For me, after 255 iterations, the code fails with a rather useless error of "Exception de HRESULT : 0x800A03EC".
From research, I've seen some people saying this is the limit of the number of worksheets, but I've seen others suggesting that there is no real limit, and that the actual limit is simply based on your system.
Note: I tried saving and closing, then re-opening the worksheet after some iterations, as suggested in here: http://support.microsoft.com/kb/210684/en-us. It did not solve the problem.
Anyone have any ideas on how to resolve this problem?

A: Necro-ing this thread just to post it as answered - the solution is to save, close, and re-open the worksheet, as suggested at http://support.microsoft.com/kb/210684/en-us, and by @HansPassant.
Although, I've since moved on towards a better solution, using OpenXML instead of the Interop library, so if anyone finds this question, I'd suggest a better answer would be to consult the OpenXML SDK, documentation for which can be found at https://msdn.microsoft.com/en-us/library/office/bb448854.aspx


text:
Q: Sending Mail using parse-cloud, mailgun and ember.js I am newbie to ember.js and node.I want to send email using mailgun in an ember.js app ,but can't find a way to do that. Found mailgun-js package but do not how to connect this package with ember.js using express. Or if there is any way that i could call a parse-cloud function in ember controller to send mail.

A: Ember runs in the browser while sending email is done (or: should under most circumstances be done) on the server. express and mailgun-js hint at that that's what you really want to do (as they are server-side node modules).
You'd have to hook the mail-sending into the REST backend on the server or provide it as an extra service that you might access through a jQuery-Ajax-Call from your ember app.


text:
Q: How to split GPS coordinate data in R I have a large field with latitude and longitude GPS coordinates.
My data looks like this:
> head(df2015, 10)
     X    Yield   Latitude Longitude
1   97 40.85889  0.8848444  120.8712
2   98 43.54383  2.1551468  120.8833
3   99 42.33718  3.4424795  120.8776
4  100 39.21862  4.7188642  120.8685
5  101 38.24887  6.0019946  120.8820
6  102 36.95594  7.2819180  120.8943
7  103 34.00766  8.5942431  120.8902
8  104 34.58568  9.8706278  120.8970
9  105 34.47788 11.1475653  120.8912
10 106 34.20532 12.4183101  120.8910

It is a rectangular plot (field). The actual data is here:
df2015 <- read.table("https://raw.githubusercontent.com/yamunadhungana/data/master/home.2015.csv", header = TRUE, sep = ",")

plot(df2015$Latitude, df2015$Longitude)

I would like to know how I can split this 600m by 400 m size plot into 4 sub-fields of equal size and put their names in my dataframe df2015. For example, I would like to group the rows by subplots A, B, C,D as shown above and put the levels in my original dataframe.

A: Here is an approach with findInterval from base R:
df2015 <- read.table("https://raw.githubusercontent.com/yamunadhungana/data/master/home.2015.csv", header = TRUE, sep = ",")
pos.matrix <- matrix(LETTERS[c(2,3,1,4)],byrow = TRUE, nrow = 2)
pos.matrix
#     [,1] [,2]
#[1,] "B"  "C"
#[2,] "A"  "D"

df2015$grid <- apply(cbind(findInterval(df2015[,"Latitude"],seq(0,400,by = 200)),
                           3-findInterval(df2015[,"Longitude"],seq(0,600,by = 300))),
                     1,function(x){pos.matrix[x[2],x[1]]})
df2015[1:10,]
#     X    Yield   Latitude Longitude grid
#1   97 40.85889  0.8848444  120.8712    A
#2   98 43.54383  2.1551468  120.8833    A
#3   99 42.33718  3.4424795  120.8776    A
#4  100 39.21862  4.7188642  120.8685    A
#5  101 38.24887  6.0019946  120.8820    A
#6  102 36.95594  7.2819180  120.8943    A
#7  103 34.00766  8.5942431  120.8902    A
#8  104 34.58568  9.8706278  120.8970    A
#9  105 34.47788 11.1475653  120.8912    A
#10 106 34.20532 12.4183101  120.8910    A

The grid position is now a new column in df2015. You could use split to break the data.frame into a list of grid positions.
Here is a visualization that confirms the proper assignment:
set.seed(3)
mysamp <- sample(seq_len(nrow(df2015)),250)
plot(NA, xlim = c(0,400), ylim = c(0,600), xlab = "Latitude", ylab = "Longitude")
text(df2015[mysamp,c("Latitude","Longitude")],
     labels = df2015[mysamp,"grid"], cex = 0.4)


text:
Q: PHP Login form handling My site has a login form which looks like this:
Email:___
Password:___
Login
The website system has three types of users: users, employers and administrators, and they are stored in three tables:
CREATE TABLE users (
  user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  first_name VARCHAR(20) NOT NULL,
  last_name VARCHAR(40) NOT NULL,
  email VARCHAR(80) NOT NULL,
  pass CHAR(60) NOT NULL,
  user_phone VARCHAR(11) NOT NULL,
  user_address VARCHAR(250) NOT NULL,
  active CHAR(32) NULL,
  last_login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                                     ON UPDATE CURRENT_TIMESTAMP,
  last_login_ip VARCHAR(15) NOT NULL,
  registration_time DATETIME NOT NULL,
  registration_ip VARCHAR(15) NOT NULL,
  PRIMARY KEY (user_id),
  UNIQUE KEY (email),
  INDEX login (email, pass)
) ENGINE = INNODB;

CREATE TABLE employers (
  employer_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  first_name VARCHAR(20) NOT NULL,
  last_name VARCHAR(40) NOT NULL,
  company_name VARCHAR(80) NOT NULL,
  email VARCHAR(80) NOT NULL,
  pass CHAR(40) NOT NULL,
  employer_phone VARCHAR(11) NOT NULL,
  employer_mobile VARCHAR(11),
  employer_address VARCHAR(250) NOT NULL,
  active CHAR(32) NULL,
  last_login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                                     ON UPDATE CURRENT_TIMESTAMP,
  last_login_ip VARCHAR(15) NOT NULL,
  registration_time DATETIME NOT NULL,
  registration_ip VARCHAR(15) NOT NULL,
  PRIMARY KEY (employer_id),
  UNIQUE KEY (email),
  INDEX login (email, pass)
) ENGINE = INNODB;

CREATE TABLE administrators (
   admin_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
   first_name VARCHAR(20) NOT NULL,
   last_name VARCHAR(40) NOT NULL,
   email VARCHAR(80) NOT NULL,
   pass CHAR(40) NOT NULL,
   last_login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                                     ON UPDATE CURRENT_TIMESTAMP,
   last_login_ip VARCHAR(15) NOT NULL,
   created_time DATETIME NOT NULL,
   PRIMARY KEY (admin_id)
) ENGINE = INNODB;

After a user logs in, the login.php script will handle it. How does login.php tell this person is a user, employer or administrator? Login.php needs to validate users by query relative tables. Do I need to create a new table indicating the relationship between users/employers/administrators? If so, how will the new table look like?
Also, where can I find some PHP website source code that contains examples like this?


text:
Q: Xcode 12.0.1 - No Downloadable Simulators Running Xcode 12.0.1. I need a simulator for iOS 12.x. When going to the "Components" screen there is a header for "Simulator" and "Size" but there are no simulators showing. How can I download an older simulator? I've tried getting to this components screen from "Preferences" as well as through "Devices and Simulators" but again it's blank offering no ability to download any other simulator. I also tried from the iOS 14 simulator directly, but there is no option there to download an older version.

A: This looks to be a bug reported by many. It was stated that downloading Xcode directly from Apple versus the Apple Store would fix the problem, but it has not. I downloaded Xcode 12.2 Beta 2 which did resolve the issue so I assume the forthcoming release will solve the problem officially.


text:
Q: My iPhone 5 isn't downloading apps There are a few apps that I found online that I'm trying to download, but my phone isn't letting me. When I click the link and it brings me to the app store, I click the "get" button, and then the "install" button, but instead of recognizing that, it just reloads and I have to click it again. I've tried it many times with many different apps, but it just keeps reloading until I give up. It didn't even give me an error message. I know I have plenty of storage, so that isn't the problem. Thank you for any insight.

A: There is a service disruption affecting the all iTunes stores. See Here

Wednesday, 14 October, 2015
All Store Services - Some users are affected
Users may be unable to access multiple services and stores or make purchases.

Next time this happens, check http://www.apple.com/support/systemstatus/


text:
Q: java.lang.NoSuchMethodError: No static method I just start using RxJava in my projects, i have got this error :
java.lang.NoSuchMethodError: No static method getService()Lcom/app/seddik/yomii/api/GalleryPhotosService;
In this class the error has occured, and says :
 No static method getService()Lcom/app/seddik/yomii/api/GalleryPhotosService; in class Lcom/app/seddik/yomii/api/GalleryPhotosService; or its super classes (declaration of 'com.app.seddik.yomii.api.GalleryPhotosService' appears in /data/app/com.app.seddik.yomii-2/base.apk:classes27.dex)
                                                       at com.app.seddik.yomii.data.datasource.GalleryPhotosDataSource.(GalleryPhotosDataSource.java:40)
public class GalleryPhotosDataSource extends ItemKeyedDataSource<Integer, GalleryPhotosItems> {

private GalleryPhotosService galleryPhotosService;

private CompositeDisposable compositeDisposable;

private MutableLiveData<NetworkState> networkState = new MutableLiveData<>();

private MutableLiveData<NetworkState> initialLoad = new MutableLiveData<>();

/**
 * Keep Completable reference for the retry event
 */
private Completable retryCompletable;

GalleryPhotosDataSource(CompositeDisposable compositeDisposable) {
    this.galleryPhotosService = GalleryPhotosService.getService();
    this.compositeDisposable = compositeDisposable;
}
....

The error appear in this line :
        this.galleryPhotosService = GalleryPhotosService.getService();

My gradle dependencies :
 apply plugin: 'com.android.application'
 apply plugin: 'me.tatarka.retrolambda'

android {
compileSdkVersion 27
buildToolsVersion "27.0.0"
defaultConfig {
    applicationId "com.app.seddik.yomii"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'

})

retrolambdaConfig 'net.orfjackal.retrolambda:retrolambda:2.5.1'
// Support libraries
compile 'com.android.support:appcompat-v7:27.1.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:27.1.0'
compile 'com.android.support:support-v4:27.1.0'
// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.4.0'
compile 'com.squareup.retrofit2:converter-gson:2.4.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

compile 'de.hdodenhof:circleimageview:2.2.0'
compile 'com.android.support:recyclerview-v7:27.1.0'
compile 'com.android.support:cardview-v7:27.1.0'
// Glide
compile 'com.github.bumptech.glide:glide:4.6.1'
compile 'com.github.bumptech.glide:compiler:4.6.1'
compile 'com.github.bumptech.glide:okhttp3-integration:4.6.1'
compile 'com.squareup.picasso:picasso:2.5.2'
// Others
compile 'com.github.chrisbanes:PhotoView:2.1.3'
compile 'com.github.varunest:sparkbutton:1.0.5'
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.andkulikov:transitionseverywhere:1.7.8'
compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.3.0'
compile 'com.zhihu.android:matisse:0.4.3'
compile 'com.seatgeek:placesautocomplete:0.3-SNAPSHOT'
compile 'id.zelory:compressor:2.1.0'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'com.github.florent37:shapeofview:1.1.2'
 // Firebase Messaging
compile 'com.google.firebase:firebase-messaging:17.1.0'
compile 'cn.pedant.sweetalert:library:1.3'
compile 'com.android.support:multidex:1.0.1'
 //Google services
compile 'com.google.android.gms:play-services-location:15.0.0'
compile 'com.google.android.gms:play-services-places:15.0.0'

// find bugs
compile 'com.google.code.findbugs:jsr305:2.0.1'
// Timber for logging
compile 'com.jakewharton.timber:timber:4.6.1'
//Architecture Components
compile "android.arch.lifecycle:extensions:1.1.0"
//Paging
compile "android.arch.paging:runtime:1.0.1"
//Rx
compile 'io.reactivex.rxjava2:rxjava:2.2.0'
compile  'io.reactivex.rxjava2:rxandroid:2.1.0'

testCompile 'junit:junit:4.12'
}apply plugin: 'com.google.gms.google-services'

This my interface Retrofit Service :
public interface GalleryPhotosService {

 // Retrofit services
static GalleryPhotosService getService() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(AppConfig.URL_UPLOAD_PHOTOS)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    return retrofit.create(GalleryPhotosService.class);
}}


text:
Q: Trying to git rebase my last 7 commits I'm working on a local git repo on a branch named "106"
I want to clean up my commit log so I run the command:
git rebase -i HEAD~7 106

but instead of giving me the last 7 commits it gives me around the last 30.
I figure that's fine, I will just leave all those old commits as pick and they wont be affected. But I get this error after changing the commits I want to:
The previous cherry-pick is now empty, possibly due to conflict resolution. If you wish to commit it anyway, use:

git commit --allow-empty

Otherwise, please use 'git reset'

and it stops at some commit that happened before I even forked the repo.
I try the same rebase command except with HEAD~2 and it shows my the last 2 commits. I fixup one and pick the other and it works fine.
I do it again with HEAD~3 and it works fine.
Once I get to HEAD~6 it just shows me this huge list of commits and always gives me that cherry pick message. I am changing nothing else in the rebase command.


text:
Q: symmetries of a circle and the $O_2$ group: why there are both rotations AND reflections, and not either rotations OR reflections?(geometric view) I'm reading "Camila Jordan, David Jordan Groups - Modular Mathematics series", section 1.2 Symmetries of a circle.

In this section we consider the unit circle. A typical point on the unit circle has coordinates $(\cos\theta, \sin\theta)$ for some $\theta$. In contrast to the square, this circle has infinitely many symmetries. They are all the rotations $rot_{\theta}$ together with all the reflections $ref_{\theta}$. As for the square, these symmetries form a group, the group of symmetries of the circle, but this time the group is infinite. The neutral element is $rot_0$. Each rotation $rot_{\theta}$ has the rotation $rot_{-\theta}$ as inverse while each reflection $ref_{\theta}$ is its own inverse. This group is known as orthogonal group $O_2$. The group $O_2$ acts on the circle by rotations and reflections. Now let us consider the stabilizer of an arbitrary point $P=(\cos\theta, \sin\theta)$ on the circle. Which elements of the group $O_2$ send $P$ to itself? There are just two, namely $rot_0$ and $ref_{2\theta}$

My question is: why does this $O_2$ consist of both rotations and reflections? As if we take any arc on a circle, we can cover all the circle by rotating this arc. Why we would need reflections then?

A: Think of the circle as being oriented, say counterclockwise. Then rotations preserve this orientation, while reflections change it. Hence there are at least two kind of symmetries...
Note however that rotations can be obtained by composing two reflections about different axes. So in some sense reflections alone do suffice.


text:
Q: Why is this class causing a memory leak? I have imported a config library into my project to allow me to manage data files with PHP with ease.
/**
 * Config Class for simple config manipulation of multiple formats.
 */
class Config{
    const DETECT = -1; //Detect by file extension
    const PROPERTIES = 0; // .properties
    const CNF = Config::PROPERTIES; // .cnf
    const JSON = 1; // .js, .json
    const YAML = 2; // .yml, .yaml
    //const EXPORT = 3; // .export, .xport
    const SERIALIZED = 4; // .sl
    const ENUM = 5; // .txt, .list, .enum
    const ENUMERATION = Config::ENUM;
    /** @var array */
    private $config = [];
    private $nestedCache = [];
    /** @var string */
    private $file;
    /** @var bool */
    private $correct = false;
    /** @var int */
    private $type = Config::DETECT;
    /** @var int */
    private $jsonOptions = JSON_PRETTY_PRINT | JSON_BIGINT_AS_STRING;
    public static $formats = [
        "properties" => Config::PROPERTIES,
        "cnf" => Config::CNF,
        "conf" => Config::CNF,
        "config" => Config::CNF,
        "json" => Config::JSON,
        "js" => Config::JSON,
        "yml" => Config::YAML,
        "yaml" => Config::YAML,
        //"export" => Config::EXPORT,
        //"xport" => Config::EXPORT,
        "sl" => Config::SERIALIZED,
        "serialize" => Config::SERIALIZED,
        "txt" => Config::ENUM,
        "list" => Config::ENUM,
        "enum" => Config::ENUM,
    ];

    /**
     * @param string $file     Path of the file to be loaded
     * @param int    $type     Config type to load, -1 by default (detect)
     * @param array  $default  Array with the default values that will be written to the file if it did not exist
     * @param null   &$correct Sets correct to true if everything has been loaded correctly
     */
    public function __construct($file, $type = Config::DETECT, $default = [], &$correct = null){
        $this->load($file, $type, $default);
        $correct = $this->correct;
    }

    /**
     * @param $k
     * @param $v
     */
    public function __set($k, $v){
        $this->set($k, $v);
    }

    public function set($k, $v = true){
        $this->config[$k] = $v;
        foreach($this->nestedCache as $nestedKey => $nvalue){
            if(substr($nestedKey, 0, strlen($k) + 1) === ($k . ".")){
                unset($this->nestedCache[$nestedKey]);
            }
        }
    }

    /**
     * @param       $k
     * @param mixed $default
     *
     * @return bool|mixed
     */
    public function get($k, $default = false){
        return ($this->correct and isset($this->config[$k])) ? $this->config[$k] : $default;
    }
    /**
 * @param       $file
 * @param int   $type
 * @param array $default
 *
 * @return bool
 */

public function load($file, $type = Config::DETECT, $default = []){
    $this->correct = true;
    $this->type = (int) $type;
    $this->file = $file;
    if(!is_array($default)){
        $default = [];
    }
    if(!file_exists($file)){
        $this->config = $default;
        $this->save();
    }else{
        if($this->type === Config::DETECT){
            $extension = explode(".", basename($this->file));
            $extension = strtolower(trim(array_pop($extension)));
            if(isset(Config::$formats[$extension])){
                $this->type = Config::$formats[$extension];
            }else{
                $this->correct = false;
            }
        }
        if($this->correct === true){
            $content = file_get_contents($this->file);
            switch($this->type){
                case Config::PROPERTIES:
                case Config::CNF:
                    $this->parseProperties($content);
                    break;
                case Config::JSON:
                    $this->config = json_decode($content, true);
                    break;
                case Config::YAML:
                    $content = self::fixYAMLIndexes($content);
                    $this->config = yaml_parse($content);
                    break;
                case Config::SERIALIZED:
                    $this->config = unserialize($content);
                    break;
                case Config::ENUM:
                    $this->parseList($content);
                    break;
                default:
                    $this->correct = false;
                    return false;
            }
            if(!is_array($this->config)){
                $this->config = $default;
            }
            if($this->fillDefaults($default, $this->config) > 0){
                $this->save();
            }
        }else{
            return false;
        }
    }
    return true;
}

In my script, with gc_enable() enabled, I created some data files using this class.
$data = new Config($this->path . "file.yml", Config::YAML);
$data->set("key", "this will leak memory");

I never saved any references to $data, yet my system is leaking memory. I do not know why PHP is leaking memory to an object that has no references. What could be causing this memory leak?


text:
Q: discord.py-rewrite - How to overwrite and change cooldown for certain users? Since my previous post was locked, I decided to be more concise about what I want this time. So I have a discord bot, written in Python (3), and I want to decorate all my commands with user-basis cooldowns, to prevent potential abuse. But, I want the bot developers to bypass completely this cooldown, and if possible, I would like that if the command invoker's is in a specific list of ids, overwrite his cooldown (so that he would only have to wait 3 seconds instead of 5 for example). I tried this:
class Bot(commands.Bot):
    class Cooldown:
        def __init__(self, rate=1, per=3.0, ctype=commands.BucketType.user):
            self.rate = rate
            self.per = float(per)
            self.ctype = ctype
            self.cmd_cldwn = commands.cooldown(rate, per, ctype)
        def __call__(self):
            def pred(ctx):
                if ctx.author.id in bot_developers:
                    return True
                ctx = self.cmd_cldwn(ctx)
                return commands.Command.is_on_cooldown(self, ctx)
            return commands.check(pred)

But then I don't know how to use it. Could someone please help me?

A: I actually found the solution, by creating a CooldownMapping class.


text:
Q: Android content provider sqlite bitwise operation selection Can I do bitwise operation in sqlite selection in Android content provider?
I created a cursor loader to load data from database, but no result return. The returning cursor's counts is zero.
new CursorLoader(getActivity(), Person.PERSON_CONTENT_URI,
            Person.FULL_PROJECTION,
            "( " + Person.FLAG + " & 2 ) = ?",
            new String[]{
                    String.valueOf(2)
            },
            Person.USER_NAME + " asc");

sqlite do support bitwise selection operation. Here is an example tested in PC commandline.
$ sqlite3 test.db
SQLite version 3.8.5 2014-08-15 22:37:57
Enter ".help" for usage hints.
sqlite> create table person(name text, flag integer);
sqlite> insert into person values('a', 1), ('b', 2), ('c', 4), ('d', 8);
sqlite> select * from person where (flag & 4) == 4;
c|4

Why the implementation in Android doesn't support it?
How can I perform bitwise operation in sqlite selection clause in Android?

A: It's a pitfall in Android API.
As @Mike's comments, the integer selection argument must quoted in where string, can not pass as a text argument.
new CursorLoader(getActivity(), Person.PERSON_CONTENT_URI,
        Person.FULL_PROJECTION,
        "( " + Person.FLAG + " & 2 ) = 2",
        null,
        Person.USER_NAME + " asc");

Thanks, this save my day.


text:
Q: Unable to set value for Apex variable in Process Builder I am trying to complete the trailhead challenge.
As part of this, I am required to invoke an apex method from process builder.
The issue is that I am unable to select the invocable variable as the process builder UI keeps on hiding the section using which I can select my invocable variable.
Apex Class :
public class ProjectCalloutService {
    //Complete the implementation for business and callout logic

    @InvocableVariable
    public ID oid;

    @InvocableMethod
    public static void postOpportunityToPMS(){

    //Insert a log record to test whether the invocation from Process Builder is working or not

    Log__c l = new Log__c();
    l.LogText__c = 'This is a test' + System.now();
    //insert l;

    /*
    Opportunity o = [SELECT ID,Name FROM Opportunity WHERE Id = :oid];
    l.LogText__c = 'Name = '+o.Name;
    l.LogText__c = 'Id = '+o.Id;
    */
    insert l;

    }
}

Process Builder Screenshots

As you can see from the pic below the UI which says "Set Apex Variables" just vanishes too fast for me to even click.

Has anyone experienced this ?

A: Change your method signature from this(It doesn't take any arguments):
@InvocableMethod
public static void postOpportunityToPMS(){

to this(It takes list of Ids as argument):
@InvocableMethod
public static void postOpportunityToPMS(List<Id> oidList){

This should work!


text:
Q: What's the difference between "type json" and "parse json" in fluentd and what should I use? I stumbled upon the following two options of parsing json with fluentd:
<filter foo.bar>
  @type parser
  key_name log
  reserve_data true
  <parse>
    @type json
  </parse>
</filter>

and
<filter foo.bar>
  @type parser
  format json
  key_name log
  reserve_data true
</filter>

Both work, but what is the difference and what should I use? Both take about 30 seconds to process the message ... somehow really long in my opinion...

A: Ok, i apologize - stupid question - the syntax only has changed between the documentation 1.0 and 0.12... so version 1.0 should be used i think.