text:
Q: How to stop Codemagic in post-clone script? I added build triggers with a specific tag pattern in codemagic, I want to stop codemagic build in the post-clone script if the latest commit is not from a specific user. Is it possible to stop codemagic or fail in the post clone script?

A: I found the Codemagic cheat sheet. There is the following script:
- name: Verify Device Farm test
    script: |
      set -e
      set -x
      export AWS_RESULT=$(cat $CM_BUILD_DIR/.scripts/test-result.json | jq -r '.run.result')
      if [ $AWS_RESULT != "PASSED" ]
      then
        echo "AWS tests did not pass, the result was $AWS_RESULT"
        exit 1
      else
        echo "AWS tests PASSED!"
      fi

Maybe a similar logic as in the if/else clause will help you?

A: If you're using yaml configuration, you can skip the build based on the webhook information already using changesets and conditions.
With post-clone script it's a bit more difficult, but to expand on @mkobuolys's answer:
set -e
set -x
export AUTHOR_NAME=$(git --no-pager show -s --format='%an' $CM_COMMIT)
if [ $AUTHOR_EMAIL != "example_user" ]
then
  echo "Wrong user"
  exit 1
else
  echo "Correct user"
fi

To get the email instead of the name, you can use %ae.


text:
Q: Apply class to Fancybox links/buttons that control 'next', 'previous', and 'close' I'm using the following jquery to close a div when anything without the class 'click' is clicked (for empty space and certain other divs).
$(document).click(function (event) {
    if (!$(event.target).hasClass('click')) {
        $('#div').hide();
              }
});

I don't want opening the fancybox gallery to close the div (fancybox 2.1.5), so I've applied the 'click' class to everything related to fancybox in my html.

I can click any of the images without hiding the div. But, when I click the "next" or "previous" or "close" links/buttons that fancybox generates over the image, the div closes.
I edited jquery.fancybox.js, adding the 'click' class to the href links for those buttons, that didn't work.
Any ideas how to apply this class to those links? Or some workaround?
Here's a FIDDLE illustrating the problem.

A: I think this is what you are looking for:
WORKING:DEMO : UPDATED
JS : UPDATED
$(document).mouseup(function (e) /* it executes on mouse click anywhere on document*/
{
var container = $(".click, a, .fancyboc_gal, .fancybox_container, img"); /* all those div's or links on which if clicked should not close your behind div(#othercontent)*/

if (!container.is(e.target) /* Now Check that click you did is not on gallery  */
    && container.has(e.target).length === 0) // ... nor a descendant of the container
{
    $("#othercontent").hide();
}

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: vision.PeopleDetector function in Matlab Have anyone ever used vision.PeopleDetector function from Computer Vision System Toolbox in Matlab?
I've installed it and tried to apply to images I have.
Although it detects people on the training image, it detects nothing on real photos. Either it doesn't detect people at all or detects people at parts of the image where they are not presented.
Could anyone share the experience of using this function?
Thanks a lot!
Here is a sample image:

A: The vision.PeopleDetector object does indeed detect upright standing people in images. However, like most computer vision algorithms it is not 100% accurate. Can you post a sample image where it fails?
There are several things you can try to improve performance.

*

*Try changing the ClassificationModel parameter to 'UprightPeople_96x48'. There are two models that come with the object, trained on different data sets.

*How big (in pixels) are the people in your image? If you use  the default 'UprightPeople_128x64' model, then you will not be able to detect a person smaller than 128x64 pixels.  Similarly, for the 'UprightPeople_96x48' model the smallest size person you can detect is 96x48.  If the people in your image are smaller than that, you can up-sample the image using imresize.

*Try reducing the ClassificationThreshold parameter to get more detections.

Edit:
Some thoughts on your particular image. My guess would be that the people detector is not working well here, because it was not trained on this kind of images. The training sets for both models consist of natural images of pedestrians. Ironically, the fact that your image has a perfectly clean background may be throwing the detector off.
If this image is typical of what you have to deal with, then I have a few suggestions. One possibility is to use simple thresholding to segment out the people. The other is to use vision.CascadeObjectDetector to detect the faces or the upper bodies, which happens to work perfectly on this image:
im = imread('postures.jpg');
detector = vision.CascadeObjectDetector('ClassificationModel', 'UpperBody');
bboxes = step(detector, im);
im2 = insertObjectAnnotation(im, 'rectangle', bboxes, 'person', 'Color', 'red');
imshow(im2);


text:
Q: Is there a way to check if a memory address is between two other addresses? Let's say that, "hypothetically", I had this code:
//two separate arrays of the same object that for the purposes of this question we will assume are not adjacent in memory
ObjectName* m_objects0 = new ObjectName[10];
ObjectName* m_objects1 = new ObjectName[10];

//and a pointer to a single object
ObjectName* m_pObject = nullptr;

If I wanted to iterate over every object in m_objects0 until I reached the end, then "jump" to the start of m_objects1 to iterate over it, how would I check if the address of m_pObject sits between the start and end addresses of either array? (my only info being the start and end addresses of each array) Is it even feasible?
The only way I can think of accomplishing it is to somehow convert an address to an int.

A: You can check if a given pointer is (in)equal to any other pointer using the == and != operators.
However, you can check if a given pointer is <(=) or >(=) another pointer only when both pointers are pointing within the same object/array, otherwise the behavior is undefined.
So, while m_pObject is pointing at an element in m_objects0, you can't check if it is (not) pointing at an element in m_objects1 using address ranges.
However, you can do something like this instead:
ObjectName* m_objects0 = new ObjectName[10];
ObjectName* m_objects1 = new ObjectName[10];

...

ObjectName* object_ptrs[] = {
    m_objects0, m_objects0 + 10,
    m_objects1, m_objects1 + 10
};

for(int i = 0; i < 4; i += 2)
{
    ObjectName* m_pObject = object_ptrs[i];
    ObjectName* m_pObjects_end = object_ptrs[i+1];

    while (m_pObject != m_pObjects_end)
    {
        ...
        ++m_pObject;
    }
}

...

Online Demo
Which, you could generalize a bit further (ie, if you needed more than 2 arrays) using something this instead:
#include <vector>
#include <utility>

ObjectName* m_objects0 = new ObjectName[10];
ObjectName* m_objects1 = new ObjectName[10];
...

std::vector<std::pair<ObjectName*,ObjectName*>> object_ptrs;
object_ptrs.emplace_back(m_objects0, m_objects0 + 10);
object_ptrs.emplace_back(m_objects1, m_objects1 + 10);
...

for(auto &p : object_ptrs)
{
    ObjectName* m_pObject = p.first;
    ObjectName* m_pObjects_end = p.second;

    while (m_pObject != m_pObjects_end)
    {
        ...
        ++m_pObject;
    }
}

...

Online Demo


text:
Q: Question about the theory behind an important footnote to entry 109 in Gauss's diary Entry 109 in Gauss's diary (and the related material in Gauss's Nachlass) is the main subject of David Cox's famous article "The Arithmetic-Geometric mean of Gauss". This entry deals with the agm of two complex numbers $a,b$, taken as a multi-valued function. It reads as follows:

Between two given numbers there are always infinitely many means both arithmetic-geometric and harmonic-geometric, the observation of whose mutual connection has been a source of happiness for us.

The harmonic-geometric mean of two numbers $a,b$ (which we denote as $H(a,b)$) is $M(a^{-1},b^{-1})^{-1}$. According to Cox, this entry is a continuation of a previous study of the agm, which resulted in the following relation between the infinitely many values of the agm:
$$
(1)\qquad \frac{1}{(\mu)} = \frac{1}{M(a,b)}+\frac{4ik}{M(a,\sqrt{a^2-b^2})}.
$$
Relation (1) is not the most general formula for the different values of the agm - this is written as:
$$
(2) \qquad\frac{1}{(\mu)} = \frac{d}{M(a,b)}+\frac{ic}{M(a,\sqrt{a^2-b^2})},
$$
where d and c are relatively prime numbers and $d \equiv 1\pmod{{4}}, c\equiv 0\pmod{{4}}$. The main purpose of part 3 of Cox's article is to check if Gauss only knew (1) or that he even knew (2) (Gauss never stated (2)). Looking into diary entry 109 in volume 10-1, I saw an additional piece of evidence that is not considered at Cox's article; this is a footnote that Gauss writes next to this entry, and reads in Latin as:

Terminus constans expressionis
$$\frac{Ad\phi}{\sqrt{f+2g\cos\phi + h\cos^2\phi}}$$
est Medium Geometrico harmonicum inter
$$\frac{A}{\sqrt{\frac{\sqrt{(f+h)^2-4g^2} + f-h}{2}}}$$ et $$\frac{A}{((f+h)^2-4g^2)^{\frac{1}{4}}}$$.

Now, after a lot of effort, I deciphered what was Gauss's intention in his cryptic Latin expression "Terminus constans expressionis" - the Latin phrase "Terminus constans expressionis" seems to mean the "constant term" $A$ in the Fourier expansion of the expression $\frac{1}{\sqrt{f+2g\cos\phi+h\cos^2\phi}}$, (the trigonometric series $A+A'\cos\phi+A''\cos2\phi+...$) which is actually equal to $\frac{1}{\pi}\int_0^{\pi}\frac{d\phi}{\sqrt{f+2g\cos\phi+h\cos^2\phi}}$. This interpretation of Gauss's Latin is consistent with Gauss's notation in other places in his writings - for example, in p.52 of Cox's article, Cox mentions Gauss's result that $\frac{2}{\pi}\int_0^{\pi/2}\frac{d\phi}{\sqrt{1+\mu \cos^2\phi}} = M(\sqrt{1+\mu},1)^{-1}$ - a result that Gauss describes by using the same Latin expression (the meaning of this result is that the constant term in the Fourier expansion of $\frac{1}{\sqrt{1+\mu \cos^2\phi}}$ is $M(\sqrt{1+\mu},1)^{-1}$).
Note that the Gaussian result that is mentioned in Cox's article is a very special case of Gauss's much more general result stated in his Latin footnote; put $f = 1, g =0 , h = \mu$, and you will get this special case.
Classification of the integral in Gauss's footnote
By employing the substitution $t = \tan(\frac{\phi}{2})$ (the "universal trigonometric substitution") Gauss's integral can be brought into the form:
$$
\int_0^{\pi}\frac{d\phi}{\sqrt{f+2g\cos\phi + h\cos^2\phi}}= \int_0^{\infty}\frac{2dt}{(1+t^2)\sqrt{f+2g\frac{1-t^2}{1+t^2} + h(\frac{1-t^2}{1+t^2})^2}} = \int_0^{\infty}\frac{2dt}{\sqrt{(f+2g+h)+(2f-2h)t^2+(f-2g+h)t^4}}.
$$
The denominator of the integrand is therefore a square root of a fourth degree polynomial - and this is the definition of a specific case of elliptic integral. In addition, substitution $x = t^2, 2dt = \frac{dx}{\sqrt{x}}$, brings the denominator into the form of a square root of a cubic:
$$\int_0^{\infty}\frac{dx}{\sqrt{(f+2g+h)x+(2f-2h)x^2+(f-2g+h)x^3}}$$
and every cubic of the form $a_0x^3+a_1x^2+a_2x$ can be transformed into Weierstrass normal form $4s^3-g_2s-g_3$ under the following suitable change of variables:
$$s = (\frac{a_0}{4})^{\frac{1}{3}}x+\frac{a_1}{3(\frac{a_0}{4})^{\frac{2}{3}}}$$
$$g_2 = \frac{\frac{4a_1^2}{3a_0}-a_2}{(\frac{a_0}{4})^{\frac{1}{3}}}$$
$$g_3 = \frac{36a_0a_1a_2-32a_1^3}{27a_0^2}$$
Therefore, Gauss's result is possibly about broadening the concept of the AGM algorithm to a wider class of integrals.
Special cases of Gauss's hgm formula, numerical verification

*

*Note also that in the special cases where $h=1, f = g^2$, than we have to calculate the harmonic-geometric mean of two equal numbers equal to $\frac{1}{\sqrt{g^2-1}}$, a prediction that was verified by me by calculating specific integrals on Wolfram Alpha; for example, if $h=1, g=2, f = 4$, than the result of the integral is $\frac{1}{\sqrt{3}}$. This shouldn't come as a surprise, because in this case the indefinite integral is elementary (one can see it directly via the "universal trigonometric substitution"), and it's also evident from the fact that the hgm algorithm was not really needed here.

*The significance of Gauss's formula appears clearly in cases when there is a need to run the hgm algorithm. For  example, if we take $h = 1, g =5, f = 24$, than:
$$
M(\sqrt{\frac{\sqrt{(f+h)^2-4g^2}+f-h}{2}},((f+h)^2-4g^2)^{1/4})^{-1} = M(\sqrt{\frac{\sqrt{525}+23}{2}},(525)^{1/4})^{-1} = 0.208811,
$$
and this numerical result is in exact accordance with a calculation of the integral $\frac{1}{\pi}\int_0^{\pi}\frac{d\phi}{\sqrt{24+10cos\phi+cos^2\phi}}$ on Wolfram Alpha.
Questions regarding Gauss's hgm formula
Therefore my questions are:

*

*I'm trying to put Gauss's result in context, but I didn't find articles connecting this specific elliptic integral to the AGM algorithm. Therefore, I'd like to know if this result is known to the mathematical community. Maybe some of the mathematicians here who are familiar with the theory of elliptic integrals can see the connection.

*Schlesinger remarks that the expression "has been a source of happiness for us" was a kind of code-expression that Gauss used to refer to new results in number theory, and speculates that the appearence of this expression in diary entry 109 means that Gauss understood the connection between this note and the theory of binary quadratic forms. Also, the notation of Gauss in his footnote (he uses $f,g,h$) reminds one of his notation for quadratic forms. So, is there any relation of this footnote to binary quadratic forms?

A: I asked David Cox about how to prove Gauss's AGM formula, and he showed me that despite that at first glance the integral in Gauss's footnote looks more general than the usual version, a few algebraic operations can transform the elliptic integral in Gauss's footnote into the standard form.
His proof consists of two steps:

*

*Transforming the standard form of the elliptic integral into an alternative form by using the universal trigonometric substitution.

*Transforming the integral in Gauss's footnote, again by the universal trigonometric substitution, into the alternative form of standard integral, ad than settling a few algebraic details.

Step one
The well-known formula
$$\frac{2}{\pi}\int_0^{\pi/2}\frac{d\phi}{\sqrt{1+\mu cos^2\phi}} = M(\sqrt{1+\mu},1)^{-1}$$
can be written
$$\frac{1}{\pi}\int_0^{\pi}\frac{d\phi}{\sqrt{1+\mu cos^2\phi}} = M(\sqrt{1+\mu},1)^{-1}$$
The substitution $t = \mathbb{tan(\phi/2)}$ turns it into:
$$ \frac{1}{\pi}\int_0^{\infty}\frac{dt}{\sqrt{(1+\mu) + 2(1-\mu)t^2 +(1+\mu)t^4}} = M(\sqrt{1+\mu},1)^{-1} $$
Under the radical, factor out $1+\mu$ to get
$$ \frac{1}{\sqrt{1+\mu}}\frac{1}{\pi}\int_0^{\infty}\frac{dt}{\sqrt{1+2\lambda t^2 + t^4}} = M(\sqrt{1+\mu},1)^{-1}, \lambda = \frac{1-\mu}{1+\mu} $$
Hence:
(1) $$\frac{1}{\pi}\int_0^{\infty}\frac{dt}{\sqrt{1+2\lambda t^2 + t^4}} = \frac {\sqrt{1+\mu}}{M(\sqrt{1+\mu},1)}, \mu = \frac{1-\lambda}{1+\lambda}$$
Step two
The goal is to express
(2) $$\frac{1}{\pi}\int_0^{\pi}\frac{d\phi}{\sqrt{f+2gcos\phi+hcos^2\phi}}$$
in terms of the AGM. This is done by transforming Gauss's integral into the form (1). First use  $t = \mathbb{tan(\phi/2)}$ to transform the integral into
$$\frac{1}{\pi}\int_0^{\infty}\frac{dt}{\sqrt{(f+h+2g)+2(f-h)t^2+(f+h-2g)t^4}}$$
If we set $a=f+h+2g,b = f-h, c = f+h-2g$, then this integral can be written
$$\frac{1}{\pi}\int_0^{\infty}\frac{dt}{\sqrt{a+2bt^2+ct^4}}$$
Now define $\delta = (a/c)^{1/4}$ so that $\delta^4 = a/c$. The substitution $t = \delta \tau $ turns the above integral into
$$\frac{1}{\pi}\int_0^{\infty}\frac{\delta d\tau}{\sqrt{a+2b\delta^2\tau^2+c\delta^4\tau^4}} = \frac{1}{\pi}\int_0^{\infty}\frac{d\tau}{\sqrt{(a/\delta^2)+2b\tau^2+(c\delta^2)\tau^4}}$$
The definition of $\delta$ implies $a/\delta^2 = c\delta^2$. Factoring out $c\delta^2$ under the radical transforms this integral into
(3) $$\frac{1}{\sqrt{c}\delta}\frac{1}{\pi}\int_0^{\infty}\frac{d\tau}{\sqrt{1+2\lambda\tau^2+\tau^4}}, \lambda = \frac{b}{c\delta^2} = \frac{f-h}{\sqrt{(f+h)^2-4g^2}}$$
since $b=f-h$ and $c\delta^2 = c\sqrt{a/c} = \sqrt{ac} = \sqrt{(f+h+2g)(f+h-2g)} = \sqrt{(f+h)^2-4g^2}$
Note that $f-h$ and $\sqrt{(f+h)^2-4g^2}$ appear in Gauss's formula, as does $\sqrt{c}\delta = ((f+h)^2-4g^2)^{1/4}$. The integral (3) can now be computed using (1).
Concluding remarks
Gauss's integral can be turned into the standard one without too much difficulty. Therefore, the main importance of Gauss's footnote is that it demonstrates the great scope of the AGM algorithm; even elliptic integrals that are not given in the standard form can be transformed into a form which can then be computed using the AGM. Gauss's footnote has, however, no connection to the deeper issues concerning multiple values of the arithmetic-geometric and harmonic-geometric means, which diary entry 109 is about.
Schlesinger probably mentioned Gauss's formula in the subtext to entry 109 just to give an example of Gauss's use of the term "harmonic-geometric mean".


text:
Q: Optimization of multiple aggregations in SELECT I read in a Microsoft T-SQL Performance Tuning whitepaper that correlated sub-queries can be costly in terms of performance on a large table:

...Compare this to the first
solution that would scan the whole table and execute a correlated subquery for every
row. The difference in performance is negligible on a small table. But on a large table it
may amount to hours of processing time...

Is there a general way to convert a query with several aggregations based upon different criteria as correlated sub-queries into a single query that uses JOINs instead of correlated sub-queries?
Consider an example:
Prepare the schema:
CREATE TABLE Student (
    ID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
    Name NVARCHAR(255) NOT NULL
);

CREATE TABLE Grade (
    ID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
    StudentID INT NOT NULL FOREIGN KEY REFERENCES Student(ID),
    Score INT NOT NULL,
    CONSTRAINT CK_Grade_Score CHECK (Score >= 0 AND Score <= 100)
);

INSERT INTO Student (Name) VALUES ('Steven');
INSERT INTO Student (Name) VALUES ('Timmy');
INSERT INTO Student (Name) VALUES ('Maria');

INSERT INTO Grade (StudentID, Score) VALUES (1, 90);
INSERT INTO Grade (StudentID, Score) VALUES (1, 81);
INSERT INTO Grade (StudentID, Score) VALUES (1, 82);
INSERT INTO Grade (StudentID, Score) VALUES (1, 82);

INSERT INTO Grade (StudentID, Score) VALUES (2, 99);
INSERT INTO Grade (StudentID, Score) VALUES (2, 63);
INSERT INTO Grade (StudentID, Score) VALUES (2, 97);
INSERT INTO Grade (StudentID, Score) VALUES (2, 90);

INSERT INTO Grade (StudentID, Score) VALUES (3, 66);
INSERT INTO Grade (StudentID, Score) VALUES (3, 61);
INSERT INTO Grade (StudentID, Score) VALUES (3, 60);

The query in question:
SELECT Name,
    (SELECT AVG(Score) FROM Grade WHERE StudentID = Student.ID AND Score < 65) AS 'F',
    (SELECT AVG(Score) FROM Grade WHERE StudentID = Student.ID AND Score >= 65 AND Score < 70) AS 'D',
    (SELECT AVG(Score) FROM Grade WHERE StudentID = Student.ID AND Score >= 70 AND Score < 80) AS 'C',
    (SELECT AVG(Score) FROM Grade WHERE StudentID = Student.ID AND Score >= 80 AND Score < 90) AS 'B',
    (SELECT AVG(Score) FROM Grade WHERE StudentID = Student.ID AND Score >= 90 AND Score <= 100) AS 'A'
FROM Student

Produces the following result:
Name    F     D     C     B     A
-----------------------------------------
Steven  NULL  NULL  NULL  81    90
Timmy   63    NULL  NULL  NULL  95
Maria   60    66    NULL  NULL  NULL

I am aware of the technique that you can use with COUNT() where you perform a single SELECT with a JOIN and then use a CASE statement to optionally add 1 to a counter when the primary keys line up between your join AND your condition is true. I am looking for a similar sort of technique that can be applied for different types of aggregations (as opposed to just COUNT).
Is there an effective way to convert this example query to use a JOIN instead of multiple sub-queries?

A: Maybe I'm missing something, but the solution using a CASE does work for aggregates as well:
SELECT st.name,
       avg(CASE WHEN g.score < 65 THEN g.score ELSE NULL END) as F,
       avg(CASE WHEN g.score >= 65 AND g.score < 70 THEN g.score ELSE NULL END) as D,
       avg(CASE WHEN g.score >= 70 AND g.score < 80 THEN g.score ELSE NULL END) as C,
       avg(CASE WHEN g.score >= 80 AND g.score < 90 THEN g.score ELSE NULL END) as B,
       avg(CASE WHEN g.score >= 90 AND g.score <= 100 THEN g.score ELSE NULL END) as A
FROM Grade g
  JOIN Student st ON g.studentid = st.ID
GROUP BY st.name

A: I tried something like the following, using CTE, but the result is a bit different from what you got, cause it calculates the Average over all grades:
;WITH
Scores(ID,Score) AS(
    SELECT S.ID,AVG(Score)
    FROM Student S
    JOIN Grade G
        ON S.ID = G.StudentID
    GROUP BY S.ID)

SELECT ST.Name
    ,CASE WHEN S.Score  < 65 THEN S.Score ELSE NULL END AS 'F'
    ,CASE WHEN S.Score  BETWEEN 65 AND 70 THEN S.Score ELSE NULL END AS 'D'
    ,CASE WHEN S.Score  BETWEEN 70 AND 80 THEN S.Score ELSE NULL END AS 'C'
    ,CASE WHEN S.Score  BETWEEN 80 AND 90 THEN S.Score ELSE NULL END AS 'B'
    ,CASE WHEN S.Score  BETWEEN 90 AND 100 THEN S.Score ELSE NULL END AS 'A'
FROM Scores S
JOIN Student ST
    ON S.ID = ST.ID

A: Try this:
SELECT s.Name
    ,SUM(CASE Score_g WHEN 'F' THEN Score_avg END) as 'F'
    ,SUM(CASE Score_g WHEN 'D' THEN Score_avg END) as 'D'
    ,SUM(CASE Score_g WHEN 'C' THEN Score_avg END) as 'C'
    ,SUM(CASE Score_g WHEN 'B' THEN Score_avg END) as 'B'
    ,SUM(CASE Score_g WHEN 'A' THEN Score_avg END) as 'A'
FROM Student s,
     (
      SELECT StudentId, score_g, avg(score) as score_avg
      FROM  (
            SELECT StudentID, Score
            CASE
              WHEN Score < 65                   THEN 'F'
              WHEN Score >= 65 AND Score < 70   THEN 'D'
              WHEN Score >= 70 AND Score < 80   THEN 'C'
              WHEN Score >= 80 AND Score < 90     THEN 'B'
              WHEN Score >= 90 AND Score <= 100 THEN 'A'
              ELSE 'X'
            END AS Score_g
            FROM Grade
        ) g
       GROUP BY StudentId, score_g
    ) t
WHERE s.ID = t.StudentID
GROUP BY s.Name

If you really hate subqueries, you can use:
SELECT s.name
    ,AVG(CASE WHEN Score < 65                   THEN SCORE END) AS 'F'
    ,AVG(CASE WHEN Score >= 65 AND Score < 70   THEN SCORE  END) AS 'D'
    ,AVG(CASE WHEN Score >= 70 AND Score < 80   THEN SCORE  END) AS 'C'
    ,AVG(CASE WHEN Score >= 80 AND Score < 90     THEN SCORE END) AS 'B'
    ,AVG(CASE WHEN Score >= 90 AND Score <= 100 THEN SCORE  END) AS 'A'
FROM Grade g, Student s
WHERE g.StudentID = s.ID
GROUP BY s.name

But in this case Student table have to contain unique entries for one student entity.

A: If your DBMS supports PIVOT, you could also try something like this:
;WITH marked AS (
  SELECT
    StudentID,
    Score,
    Mark = CASE
      WHEN Score < 65 THEN 'F'
      WHEN Score < 70 THEN 'D'
      WHEN Score < 80 THEN 'C'
      WHEN Score < 90 THEN 'B'
      ELSE 'A'
    END
  FROM Grade
),
pivoted AS (
  SELECT
    StudentID,
    F, D, C, B, A
  FROM marked m
  PIVOT (
    AVG(Score) FOR Mark IN (F, D, C, B, A)
  ) p
)
SELECT
  s.Name,
  p.F,
  p.D,
  p.C,
  p.B,
  p.A
FROM Student s
  INNER JOIN pivoted p ON s.ID = p.StudentID


text:
Q: MySql (Aurora) transpose issues (getting null) I have a table like this in MySQL (Aurora):
A    B    C
1   100   60
1   102   40

My end goal is to transpose this and make it look like this:
A   B_1   C_1   B_2   C_2
1   100   60    102    40

My query is:
SELECT Table.A,
MAX(Table.B) AS `B_1`,
(CASE WHEN Table.B = MAX(Table.B) then Table.C END) AS `C_1`,
MIN(Table.B) AS `B_2`,
(CASE WHEN Table.B = MIN(Table.B) THEN Table.C END) AS `C_2`
FROM
TABLE
GROUP BY Table.A

But I am getting results as :
A   B_1   C_1   B_2   C_2
1   100   null  102    40

Can someone help me fix this null issue?

A: Based on the result it looks like you want the B_1 value to be min(B) and C_1 to be the corresponding C value from the same row. Likewise the B_2 value to be max(B) and C_2 to be the corresponding C value from the same row.
In your query you have normal columns appearing in SELECT without including them in the GROUP BY. This will result an error in newer MySQL (and in all other databases).
You can first calculate the MIN(B) and MAX(B) and then join result with table again to pick up the C columns.
select minb as 'B_1',
       max(c1) as 'C_1',
       maxb as 'B_2',
       min(c2) as 'C_2'
from (
  select
    s.minb,
    if (s.minb=m.B, m.C, null) as c1,
    s.maxb,
    if (s.maxb=m.B, m.C, null) as c2
  from test m
    join (
      select A,
        min(B) as `minb`,
        max(B) AS `maxb`
      from test
      group by A
    ) as s on s.A=m.A
  ) as q
group by minb, maxb

See dbfiddle


text:
Q: Jquery tabs - Showing a confirmation before activate I'm using jquery UI's tabs.  When a user switches tabs, I'm checking for unsaved changes, and prompting the user accordingly.  However, before the user even clicks Yes or No, the tab loads anyway.  Does anyone know how I can get my function to NOT return anything until after the result has come back from my fancybox dialog?
You can see I've tried a couple of different methods to return my boolean value in CheckSomething().
$("#myTabs").tabs({
    select:
        function (event, ui) {
            return CheckSomething();
        },

    show:
        function (event, ui) {
            //do some stuff
        }
});

function CheckSomething() {
    var loadMyTab = true;  //If I set this to false, then it always returns false.
    if (myCondition) {
        //Show a FancyBox prompt.

        if (fancyYes) {
            //return true;
            loadMyTab= true;
        }
        else {
            //return false;
            loadMyTab = false;
        }
    }
    else {
        //return true;
        loadMyTab = true;
    }
    return loadMyTab;
}

A: With a standard confirm instead of a fancy is working can it be a fast solution? http://jsfiddle.net/nuywj/

A: I ended up going w/ a standard javascript confirm box instead of FancyBox.  That solved my problem, because Confirm will block code from being executed:
function CheckSomething() {
    if (myCondition) {
        return confirm("Are you sure you want to change tabs without saving?");
    }
    else {
        return true;
    }
}


text:
Q: Midpoint removal from 5-pt Likert scale I have removed midpoints from a 5-point Likert scale instrument on my supervisor's advice. When I did some reliability analyses - SPSS showed that almost half of my cases were excluded. So we substituted the means for the missing cases. Is this right?
The midpoint was removed because it is assigned to answers such as: I don't know, neither agree/disagree. This can inflate the means. This is a conceptual argument that was made to me.

A: I'm not sure why your advisor thought it was a good idea to remove a response option from the data after collection, as @RNM noted. As well, mean substitution is seldom a really good option for missing data.
If you have to work with the altered data, one option you can do with SPSS if you have access to the MVA procedure is to use the EM imputation option to create an estimate of the covariance matrix of the items and use MATRIX IN to read that into RELIABILITY. That's likely to produce more defensible results.

A: First, you created missing data where there was none. Perhaps your supervisor had something particular in mind, but I can't see what it could be. The midpoint is not missing.
Second, you used a very poor method of imputation - mean substitution. This makes the missing data much too regular. If you really insist on creating a problem then, at least, you could solve it appropriately, probably using some form of multiple imputation.
But ask your supervisor why creating missing data was suggested.


text:
Q: Is there a safe way to cast float64 to int64 in Go? I am aware of the int() or int64() typecast functions, the Go provides.
Is there a safe way to cast float64 to int64 (with truncation,) given the largest representable 64-bit floating point number math.MaxFloat64 is much larger than math.MaxInt64? A way, that triggers an overflow error?

A: If you are converting (not casting or typecasting) from a float64 to an int64, then you can compare the float value to the closest double precision integer values of math.MaxInt64 and math.MinInt64. These numbers cannot be exactly stored in a float64 value, however they will be stored as the next integer value above or below those:
float64(math.MaxInt64) // 9223372036854775808
float64(math.MinInt64) // -9223372036854775808

So as long as your float64 value is between these two values, you know it can be converted to an int64 without overflow.
Note however that if you are converting in the other direction, you cannot guarantee that a float64 can accurately represent all int64 values up to MaxInt64, since a double precision float point value only holds 52 bits of precision. In that case you must check that the int64 value is between -1<<53 and 1<<53.
In either case you can handle larger values with the math/big package.


text:
Q: Tutorial on making a picture like this in Photoshop I always wanted to make a background like this but I could never find a tutorial on this. I also do not know what the effect is called so it makes it even harder for me to find.

This is the effect I am talking about, at the background. Does anyone know whats it called, or does anyone have a tutorial on this?

A: Granted that you want to do it in Photoshop, but you can also create the effect in GIMP with the Line Nova filter (Filters > Render > Line Nova...) ("Fill a layer with rays emanating outward from its center using the FG color"). It helps to make a small alteration to the script (line-nova.scm) to make it more useful by changing the "40" in:
  SF-ADJUSTMENT _"Number of lines"     '(200 40 1000 1 1 0 1)

to something like "10":
  SF-ADJUSTMENT _"Number of lines"     '(200 10 1000 1 1 0 1)

This would widen the filter's default range of lines (by extending the bottom end) to enable you to produce something more closely resembling your screenshot.

A: "Starburst" tutorials:

*

*http://mintyferret.com/photoshop-tutorials/starburst-tutorial/

*http://www.youtube.com/watch?v=rJ9l9zDXTgE


text:
Q: noexcept specifier for _Not_fn function call operator In this question I consider the libstdc++ implementation of the _Not_fn call wrapper.
It defines four overloads of function call operator as follows:

 #define _GLIBCXX_NOT_FN_CALL_OP( _QUALS )                          \
       template<typename... _Args>                                  \
    decltype(_S_not<__inv_res_t<_Fn _QUALS, _Args...>>())           \
    operator()(_Args&&... __args) _QUALS                            \
    noexcept(noexcept(_S_not<__inv_res_t<_Fn _QUALS, _Args...>>())) \
    {                                                               \
      return !std::__invoke(std::forward< _Fn _QUALS >(_M_fn),      \
                            std::forward<_Args>(__args)...);        \
    }
       _GLIBCXX_NOT_FN_CALL_OP( & )
       _GLIBCXX_NOT_FN_CALL_OP( const & )
       _GLIBCXX_NOT_FN_CALL_OP( && )
       _GLIBCXX_NOT_FN_CALL_OP( const && )
 #undef _GLIBCXX_NOT_FN_CALL

It is easy to see, that noexcept specification is set as:

noexcept(noexcept(_S_not<__inv_res_t<_Fn _QUALS, _Args...>>()))

where __inv_res_t is an alias template:

template<typename _Fn2, typename... _Args>
using __inv_res_t = typename __invoke_result<_Fn2, _Args...>::type;

and _S_not is a static member function template:

template<typename _Tp>
static decltype(!std::declval<_Tp>())
_S_not() noexcept(noexcept(!std::declval<_Tp>()));

Now, following the logic behind noexcept specification I conclude, that:

*

*Function call operator conceptually has the same noexcept specification as _S_not<__inv_res_t<_Fn _QUALS, _Args...>>.

*_S_not<__inv_res_t<_Fn _QUALS, _Args...>> is marked as noexcept depending on whether a negation applied to the result of std::__invoke(...) is noexcept.

From my point of view, this noexcept specification doesn't cover the case when the callable object, wrapped into not_fn, may or may not throw itself while being invoked with a particular set of arguments passed to not_fn function call operator. In other words, it is not checked if std::__invoke(...) itself inside a function call operator might throw or not.
Do I miss something in this implementation?
The implementation from cppreference.com has a bit simpler noexcept specification. However, this implementation doesn't work with the latest g++ due to a known issue.

A: There is actually no requirement that not_fn propagate noexcept. It is specified in [func.not_fn], each of the four call operators just looks something like:

template<class... Args>
  auto operator()(Args&&...) const&
    -> decltype(!declval<invoke_result_t<const FD&, Args...>>());

No noexcept. That said, P0356 proposes to add it and the current noexcept specifier makes no sense and could cause harm by being wrong, so filed 87538.

Update: this has been fixed for 7.4, 8.3 and 9.1.


text:
Q: Accessing static object from custom View class in Android I have a view class IntroScreen, which is inflated in my xml layout.
Inflation works great until I try to access a static String[] element
defined inside my onCreate method. Somehow it gives me a NullPointerException even though the call to inflate my IntroScreen view happens after I initialize my String[] object. Here's some code:
//class MainActivity which holds onCreate()
static String[] stringArray;

//inside onCreate

stringArray = new String[20];
stringArray[0] = "the world";
stringArray[1] = "is round";

//a few lines down the code... still inside onCreate()
intro = (IntroScreen)this.findViewById(R.id.hereintro);

//inside my IntroScreen which extends view
//constructors are as follows:
public IntroScreen(Context c){
    super(c);
}

public IntroScreen(Context c, AttributeSet a){
 super(c, a);
 boolean b = false;

 if(MainActivity.stringArray[0].equals("the world"))b = true; //problem here
 //above line of code gives null pointer exception
}

//inside onDraw()
//need more calls to MainActivity.stringArray in order to create custom view
//but calls won't work at all

My question is how can I access this static String[] array? I can't pass
it to my IntroScreen view since it's inflated via xml in the line of code
intro = (IntroScreen)this.findViewById(R.id.hereintro);

Any ideas of suggestions,
many thanks

A: The constructor of IntroScreen is called before onCreate() gets called, so your array is not yet initialized. Simply make sure to initialize it before inflating your activity.

A: pass that string array parameter to public IntroScreen(Context c, AttributeSet a)


text:
Q: Output text only when search has been run I have a custom post type that I'm searching through with a custom query. I want to output a message if there's too many results (that works fine). But the problem I have is when you first goto the page and no search has been performed, I don't want that message to appear. How can I stop it appearing when no search has been performed?
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'posts_per_page'    => 5,
    'post_type'         => 'researchdatabase',
    'post_status'       => 'publish',
    'paged'             => $paged
);

if($searchTerm != "") {
    $args['s'] = $searchTerm;
}

$the_query = new WP_Query($args);

if ($the_query->have_posts()) {
    $counter = 1; ?>

        <?php echo $the_query->post_count; ?> research items
        <?php if($the_query->post_count > 20) { ?>

Refine your search criteria to see fewer results.
        <?php } ?>

    <?php while ($the_query->have_posts()) { $the_query->the_post(); ?>

        <?php // output results ?>

    <?php $counter++;
    } // end while

    // reset post data
    wp_reset_postdata();

} else {
    echo 'No results';
} // end if
?>

A: Just change the condition:
<?php if($the_query->post_count > 20) { ?>

With:
<?php if($the_query->post_count > 20 && is_search()) { ?>

is_search() return true if any search term is sent for the current WP_Query.

A: "no search has been performed" equals "no search term in the query", why don't you just check search term first?
if(!empty($searchTerm)) {
    $args = array(
        's' => $searchTerm
        'posts_per_page'    => 5,
        'post_type'         => 'researchdatabase',
        'post_status'       => 'publish',
        'paged'             => (get_query_var('paged')) ? get_query_var('paged') : 1
    );

    $the_query = new WP_Query($args);
     // Your code.
}

BTW: if you want to display total count of search results, you should use $the_query->found_posts not $the_query->post_count it only count posts on first page.


text:
Q: Vimeo video upload does not return given parameters (POST upload) Following the build and HTML form from the Vimeo docs I managed to properly upload a video, but, as setting the video properties/metadata is not allowed before the upload is completed I require that some parameters are returned to me.
The docs state:

We will retain any parameters you have provided, and add one new
  parameter video_uri.

But they fail to return anything other than the video_uri.

My form is composed of this name, privacy.view and the file:
(Prestashop-smarty tpl)

    <input type="hidden" name="privacy.view" value="nobody">

    <input maxlength="20" class="is_required validate form-control" type="text" id="contentName"
           name="contentName" value="" required/>

    <input type="file" name="file_data" id="exampleInputFile">

    CANCELAR
    <button type="submit" name="submitFileContent" class="btn btn-default save-profile">
    GUARDAR
    </button>

</form>

I expected Vimeo to return video_uri, name and privacy.view but it's only returning the last one.
I really appreciate any help you can provide.
Edit:
I'm passing my own url as the "redirect_url" so no further redirects are being done after vimeo sends the user back to me.
Just in case it can provide anything to the troubleshooting here is the request:
$response = $lib->request('/me/videos', array('redirect_url' => Tools::getHttpHost(true).__PS_BASE_URI__."filecontent"), 'POST');

A: I see how this is confusing in the docs, and will make a note to clear it up.
The parameters we include in the redirect are not user input fields that you request in the form. The parameters we retain in the redirect are any manual querystring parameters you included in the redirect url.
E.g. if you set your redirect_url to be http://dashron.com?secret_key=abc123, we will retain the secret_key parameter when we redirect the user once the upload is complete.


text:
Q: iPhone 7 recording issues For a while now my Voice Notes on WhatsApp record blank. I mean you can't hear anything. The same goes for Voice Memos app.
I can make cell calls without a problem, use speech-to-text and even record a video with sound.
I also noticed that when I record a video on WhatsApp, after that the Voice Note works normally I can record but after that the next Voice Note is blank again.
My hand is not on the mic when I record and I don't think I have another app that is using the mic.
I'm new to iOS so I'm not sure what's going wrong.


text:
Q: Having trouble accessing a list value inside a map | C++ I've made a map that has string keys with either string values or list values. It gives me no syntax errors and has worked fine for me so far until I've tried accessing the list value. I've tried setting it as a variable, using auto, and no go. Don't know what else to try, any help is appreciated.

using map = std::map<std::string, std::variant<std::string, std::list<std::string>>>;
std::list<std::string> TagList{ "Paid", "Needs invoice" };

 map m{ {"TIME",TimeHourAndMin}, {"HEADER","Title"},{"TAGS", TagList},{"CONTENT", "Hey this is content!"} };

// E0135 class "std::variant<std::string, std::list<std::string, std::allocator<std::string>>>" has no member "begin"
// E0135 class "std::variant<std::string, std::list<std::string, std::allocator<std::string>>>" has no member "end"
for (auto it = m["TAGS"].begin(); it != m["TAGS"].end(); it++) {

        }

A: The problem is that m["TAGS"] is of type std::variant and so doesn't have a begin method. Since you want to get the list out of your variant you can use the std::get function to do that
auto it = std::get<std::list<std::string>>(m["TAGS"]).begin();


text:
Q: JLabel as Background Image I can't seem to figure this out.
Please help I need this to work out to continue my project.
Awww I have to add this for allowing me to post
import javax.swing.*;
import java.awt.*;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {

public static void Draw(){
    DrawFrame();
}

public static void DrawFrame(){
    int h = 600;
    int w = 340;
    JFrame frame = new JFrame();
    JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png"));

    frame.setResizable(false);
    frame.setSize(h, w);
    frame.setTitle("MarioCraft");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.add(background1);

    background1.setVisible(true);
    background1.setIcon(new ImageIcon("/res/mariocraft_main.png"));
    background1.setText("Background failed to load");

    }

}

A: A JLabel always displays the image at its actual size so you should not be manually setting the size of the frame.
Instead the code should be something like:
JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png"));

JFrame frame = new JFrame();
frame.add(background1);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);

A: You need to add the JLabel instance to the JFrame before you realize it (i.e. make it visible). Also, remove these three calls:
background1.setVisible(true);
background1.setIcon(new ImageIcon("/res/mariocraft_main.png"));
background1.setText("Background failed to load");

They are completely unnecessary. Also, another approach to setting a background image to a component is to override it's paintComponent method and draw the image directly to it's Graphics object.

A: Do you want to set JLabel as background image for the JFrame. Then,
frame.setContentPane(new JLabel(new ImageIcon("someimage.jpg"));

See a sample code snippet taken for here
frame.setLayout(new BorderLayout());
frame.setContentPane(new JLabel(new ImageIcon("someimage.jpg")));
frame.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
frame.add(l1);
frame.add(b1);

A: import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Mainframe extends JFrame
{
    public JLabel image ;

    public Container c;

    public Mainframe()
    {
        c=this.getContentPane();
        image=new JLabel(new ImageIcon("bg.jpg"));
        image.setSize(500, 550);

        c.setLayout(new FlowLayout());
        c.add(image);

         add(image);

         this.setSize(500, 550);
         this.show();
         this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args)
    {
            new Mainframe();
    }

}


text:
Q: Oracle / JDBC: retrieving TIMESTAMP WITH TIME ZONE value in ISO 8601 format A lot have been said (and written on SO) on parts of the subject, but not in a comprehensive, complete way, so we can have one "ultimate, covering-it-all" solution for everyone to use.
I have an Oracle DB where I store date+time+timezone of global events, so original TZ must be preserved, and delivered to the client side upon request. Ideally, it could work nicely by using standard ISO 8601 "T" format which can be nicely stored in Oracle using "TIMESTAMP WITH TIME ZONE" column type ("TSTZ").
Something like '2013-01-02T03:04:05.060708+09:00'
All I need to do is to retrieve the above value from DB and send it to client without any manipulations.
The problem is that Java lacks support of ISO 8601 (or any other date+time+nano+tz data type) and the situation is even worse, because Oracle JDBC driver (ojdbc6.jar) has even less support of TSTZ (as opposed to Oracle DB itself where it's well supported).
Specifically, here's what I shouldn't or cannot do:

*

*Any mapping from TSTZ to java Date, Time, Timestamp (e.g. via JDBC getTimestamp() calls) won't work because I lose TZ.

*Oracle JDBC driver doesn't provide any method to map TSTZ to java Calendar object (this could be a solution, but it isn't there)

*JDBC getString() could work, but Oracle JDBC driver returns string in format '2013-01-02 03:04:05.060708 +9:00', which is not compliant with ISO 8601 (no "T", no trailing 0 in TZ, etc.). Moreover, this format is hard-coded (!) inside Oracle JDBC driver implementation, which also ignores JVM locale settings and Oracle session formatting settings (i.e. it ignores NLS_TIMESTAMP_TZ_FORMAT session variable).

*JDBC getObject(), or getTIMESTAMPTZ(), both return Oracle's TIMESTAMPTZ object, which is practically useless, because it doesn't have any conversion to Calendar (only Date, Time and Timestamp), so again, we lose TZ information.

So, here are the options I'm left with:

*

*Use JDBC getString(), and string-manipulate it to fix and make ISO 8601 compliant. This is easy to do, but there's a danger to die if Oracle changes internal hard-coded getString() formatting. Also, by looking at the getString() source code, seems like using getString() would also result in some performance penalty.

*Use Oracle DB "toString" conversion: "SELECT TO_CHAR(tstz...) EVENT_TIME ...". This works fine, but has 2 major disadvatages:

*

*Each SELECT now has to include TO_CHAR call which is a headache to remember and write

*Each SELECT now has to add EVENT_TIME column "alias" (needed e.g. to serialize the result to Json automatically)
.

*Use Oracle's TIMESTAMPTZ java class and extract relevant value manually from its internal (documented) byte array structure (i.e. implement my own toString() method which Oracle forgot to implement there). This is risky if Oracle changes internal structure (unlikely) and demands relatively complicated function to implement and maintain.

*I hope there's 4th, great option, but from looking all over the web and SO - I can't see any.
Ideas? Opinions?
UPDATE
A lot of ideas have been given below, but it looks like there is no proper way to do it. Personally, I think using method #1 is the shortest and the most readable way (and maintains decent performance, without losing sub-milliseconds or SQL time-based query capabilities).
This is what I eventually decided to use:
String iso = rs.getString(col).replaceFirst(" ", "T");

Thanks for good answers everyone,
  B.

A:
JDBC getObject(), or getTIMESTAMPTZ(), both return Oracle's TIMESTAMPTZ object, which is practically useless, because it doesn't have any conversion to Calendar (only Date, Time and Timestamp), so again, we lose TZ information.

That would be my recommendation as the only reliable way to get the information you seek.
If you are on Java SE 8 and have ojdbc8 then you can use getObject(int, OffsetDateTime.class). Be aware that when you use getObject(int, ZonedDateTime.class) you may be affected by bug 25792016.

Use Oracle's TIMESTAMPTZ java class and extract relevant value manually from its internal (documented) byte array structure (i.e. implement my own toString() method which Oracle forgot to implement there). This is risky if Oracle changes internal structure (unlikely) and demands relatively complicated function to implement and maintain.

This is what we ultimately went with until bug free JSR-310 support is available in the Oracle JDBC driver. We determined this was the only reliable way to get the information we want.

A: A slight improvement to #2:
CREATE OR REPLACE PACKAGE FORMAT AS
  FUNCTION TZ(T TIMESTAMP WITH TIME ZONE) RETURN VARCHAR2;
END;
/
CREATE OR REPLACE PACKAGE BODY FORMAT AS
  FUNCTION TZ(T TIMESTAMP WITH TIME ZONE) RETURN VARCHAR2
  AS
  BEGIN
    RETURN TO_CHAR(T,'YYYYMMDD"T"HH24:MI:SS.FFTZHTZM');
  END;
END;
/

The in SQL this becomes:
SELECT FORMAT.TZ(tstz) EVENT_TIME ...

It's more readable.
If you ever need to change it, it's 1 place.
The downside is it is an extra function call.

A: you need two values: time utc in millis since 1970 and timezone offset fom utc.
So store them as a pair and forward them as a pair.
class DateWithTimeZone {
long timestampUtcMillis;
// offset in seconds
int tzOffsetUtcSec;
}

A Date is a pair of numbers. It is not a String. So a machine interface should not contain a date represented by a iso string, although that is handy to debug.
If even java cannot parse that iso date, how do you think that your clients can do?
If you design an interface to your clients, think how they can parse that. And in advance write a code that shows that.

A: This is untested, but seems like it ought to be a workable approach.  I'm not sure about parsing the TZ name out, but just treating the two parts of the TZTZ object as separate inputs to Calendar seems like the was to go.
I'm not sure whether longValue() will return the value in local or GMT/UCT.  If it's not GMT, you should be able to load a calendar as UTC and ask it for a Calendar converted to local TZ.
public Calendar toCalendar(oracle.sql.TIMESTAMPTZ myOracleTime) throws SQLException {
    byte[] bytes = myOracleTime.getBytes();
    String tzId = "GMT" + ArrayUtils.subarray(bytes, ArrayUtils.lastIndexOf(bytes, (byte) ' '), bytes.length);
    TimeZone tz = TimeZone.getTimeZone(tzId);
    Calendar cal = Calendar.getInstance(tz);
    cal.setTimeInMillis(myOracleTime.longValue());
    return cal;
}

A: Do you really care about sub-millisecond precision?  If not converting from a UTC millisecond + timezone-offset to your required string is a one-liner using joda-time:
    int offsetMillis = rs.getInt(1);
    Date date = rs.getTimestamp(2);

    String iso8601String =
            ISODateTimeFormat
                    .dateTime()
                    .withZone(DateTimeZone.forOffsetMillis(offsetMillis))
                    .print(date.getTime());

Prints, for example (current time in +9:00):
2013-07-18T13:05:36.551+09:00

Regarding the database:  Two columns, one for the offset, one for the date.  The date column could be an actual date type (thus making many, timezone-independent anyway, db date functions available).  For time-zone dependent queries (such as the mentioned global hourly histogram) perhaps a view could expose columns: local_hour_of_day, local_minute_of_hour, etc.
This is likely how one would have to do it if no TSTZ datatype was available--which, considering Oralce's poor support, is the nearly the case for practical purposes.  Who wants to use an Oracle specific features anyway!  :-)

A: Since it looks like there's no magical way of doing this right, the simplest and the shortest method would be #1. Specifically, this is all the code needed:
// convert Oracle's hard-coded: '2013-01-02 03:04:05.060708 +9:00'
// to properly formatted ISO 8601: '2013-01-02T03:04:05.060708 +9:00'
String iso = rs.getString(col).replaceFirst(" ", "T");

it seems that just adding 'T' is enough, although a perfectionist would probably put more cosmetics (regex can optimized, of course), e.g.: rs.getString(col).replaceFirst(" ", "T").replaceAll(" ", "").replaceFirst("\+([0-9])\:", "+0$1:");
B.

A: The solution with oracle is SELECT SYSTIMESTAMP FROM DUAL


text:
Q: Как исправить "Нет такого файла или каталога" в Linux? При запуске любой Linux программы из shell получаем ошибку вида:
bash: /usr/bin/wine: Нет такого файла или каталога
Переменные окружения PATH выставлены корректно и сам файл существует.

A: Файл ld-linux.so.2(ld-linux-x86-64.so.2 для 64 битной архитекруры) пуст или поврежден. Исправляется заменой его на рабочий из резервной копии.


text:
Q: avoid initializing list with data So, I have two forms. The form1 has a button to open the form2. In the form2 I have a list of elements that I fill with elements I create in the form2. My problem is, when I close my form2 and reopen it, my list is empty. I know that is because Im initializing my list again (ListaComida = new List<Comida>();), so I get my data erased but I dont see how to solve this.
My code
Form1
public partial class Form1 : Form

{

    public Form1()
    {
        InitializeComponent();
}

    private void addDia_Click(object sender, EventArgs e)
    {

        string dia = (DateTime.Today.ToString("dd/MM/yyyy"));
        TabPage myTabPage = new TabPage(dia);
        tabControl1.TabPages.Add(myTabPage);
    }

    private void AddComida_Click(object sender, EventArgs e)
    {
        FormAddComida addComida = new FormAddComida();
        DialogResult resultaod = addComida.ShowDialog();
    }
}

Form2
public partial class FormAddComida : Form
    {
        public List<Comida> ListaComida;

        public FormAddComida()
        {
            InitializeComponent();
            ListaComida = new List<Comida>();

        }

        private void addComidaAdicionar_Click(object sender, EventArgs e)
        {
            Comida comidaAdicionada = new Comida(tbNome.Text,
                Convert.ToInt32(tbCalorias.Text),
                Convert.ToInt32(tbHidratos.Text),
                Convert.ToInt32(tbProteinas.Text),
                Convert.ToInt32(tbGorduras.Text)
                );

            ListaComida.Add(comidaAdicionada);
            RefreshListaComida();

        }

        private void RefreshListaComida()
        {

            lbListaComida.Items.Clear();
            lbListaComida.Items.AddRange(ListaComida.ToArray());

        }

        private void AddComidaCancelar_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }

A: You can use MemoryCache, even if you close your form your List will stay in Memory and you can retrieve by the Key. But if you need to save this data permanently (or long time running the app )i recommend you store in a DB.
    using System.Runtime.Caching;

    private ObjectCache cache = MemoryCache.Default;

    public class Food
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }

    public void AddFood()
    {
        FoodList.Add(new Food { Name = "Pizza", Price = 10 });
        FoodList.Add(new Food { Name = "Fries", Price = 5 });

        cache.Add("UserCacheFood", FoodList, DateTimeOffset.MaxValue);
    }

    public List<Food> ReturnListFromCache()
    {
        return (List<Food>)cache.Get("UserCacheFood");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        AddFood();
        var result = ReturnListFromCache();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        var ret2 = ReturnListFromCache();
    }


text:
Q: rake aborted! NameError: uninitialized constant Users I seem to have run into a problem with my database. I have been using Rails to create a website and I have a database for Users. There was a change I needed to make so I rake db:drop and now I see this error:
database issue
Here is my users controller:
class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
      if @user.save
        session[:user_id] = @user.id
        redirect_to @user
      else
        render 'new'
      end
  end

  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :phone_number, :address_one, :address_two, :city, :country, :state, :zip)
    end
end

my user model:
class User < ActiveRecord::Base
  has_secure_password
  validates :email, presence: true

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.id).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.password = "a"
      user.email = user.uid
      user.save!
    end
  end
end

and my current users database table
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :password_digest
      t.string :phone_number
      t.string :address_one
      t.string :address_two
      t.string :city
      t.string :country
      t.string :state
      t.string :zip
    end
  end
end

Thanks for the any advice or help given!

A: The migration filename and class name should be same. The two need to be consistent for rails to dynamically load the appropriate class.
class CreateUsers < ActiveRecord::Migration change it to class Users < ActiveRecord::Migration
Run rake db:migrate


text:
Q: Define generic type in superclass which refers to the type of the subclass it is in Question
Is there a way to implement a generic type or something similar in a superclass, which will always refer to the subclass it is in?
Explanation of what i need
I have the superclass
public abstract class MySuperclass{

   public abstract *magicalTypeReference* getInstance();

}

And when i create a subclass of it, i want the * magicalTypeReference * to become the type of the subclass it is in.
public class FirstSubclass extends MySuperclass{

  @Override
  public FirstSubclass getInstance(){return this;}

}

public class SecondSubclass extends MySuperclass{

  @Override
  public SecondSubclass getInstance(){return this;}

}

Why a normal generic type wont do the job
Something similar can technically be done with generic types.
public abstract class MySuperclass<E extends MySuperclass>{

   public abstract E getInstance();

}

public class FirstSubclass extends MySuperclass<FirstSubclass>{

  @Override
  public FirstSubclass getInstance(){return this;}

}

public class SecondSubclass extends MySuperclass<SecondSubclass>{

  @Override
  public SecondSubclass getInstance(){return this;}

}

But generic types do not guarantee that the type later is forced to be the subclass. Technically you can create a Subclass using another Subclass as the generic type. Like this
public class SecondSubclass extends MySuperclass<FirstSubclass>{

  @Override
  public FirstSubclass getInstance(){return this;}

}

Is there some construct in java that can provide a "type safe" way of implementing this?

A: This is not possible in Java.
Consider if hypothetically what you want were possible, you could implement FirstSubclass like this:
public class FirstSubclass extends MySuperclass {

  @Override
  public FirstSubclass getInstance() { return new FirstSubclass(); }

}

Then you could have a subclass of it that doesn't override the getInstance() method:
public class SubSubclass extends FirstSubclass { }

SubSubclass also implements the MySuperclass interface, due to inheritance. However, SubSubclass's getInstance() method is inherited from FirstSubclass, which returns a FirstSubclass. Therefore, SubSubclass does not satisfy the contract of the MySuperclass interface since its getInstance() method does not return a SubSubclass.

A: Instead of declaring your MySuperClass like
public abstract class MySuperClass<E extends MySuperClass>

if you declare like
public abstract class MySuperClass<E extends MySuperClass<E>>

you can make subclasses avoid referencing each other in a partial sense.
This solution will definitely avoid situations like this
public class SecondSubclass extends MySuperclass<FirstSubclass>{

@Override
public FirstSubclass getInstance(){return this;}

}

public class FirstSubclass extends MySuperclass<SecondSubclass>{

@Override
public SecondSubclass getInstance(){return this;}

}

where one class contains the other and vice versa.


text:
Q: Connection refused error when trying to access http://metadata.google.internal I'm getting connection refused error when trying to access http://metadata.google.internal from inside a pod running on OpenShift deployed on GCP:
sh-4.4$ curl 'http://metadata.google.internal/computeMetadata/v1/project/?recursive=true' -H 'Metadata-Flavor: Google'
curl: (7) Failed to connect to metadata.google.internal port 80: Connection refused

How can I solve it?


text:
Q: AJAX скрипт не делает запрос по указанному адресу Метод контроллера Spring Boot:
    @PostMapping("/bills/add")
    @ResponseBody
    public String createBill(@RequestParam String currency) {

        String phone = authentication().getName();
        String answer = null;
        if(currency.isEmpty()) {
            answer = "Please choose currency type";
            return answer;
        }
        accountService.addBill(phone, currency);
        answer = "Success!!!";
        return answer;
    }

Thymeleaf:
<div>
<form id="currency_form">
        <select class="form-control" th:id="currency" th:name="currency" style="width:auto">
            <option value="">Select currency</option>
            <option th:each="currency : ${T(com.github.irybov.bankdemoboot.Currency).values()}"
                    th:value="${currency.name()}"
                    th:text="${currency.name()}">
            </option>
        </select>
    <button type="submit" class="btn btn-success add_bill">
        Add new bill</button>

    <p th:text="${message}" th:value="${#strings.isEmpty('currency')}" class="error"/>
</form>
</div>

JQuery:
<script>
    $(document).ready(function(){
        $('.add_bill').click(function(){
            var type = ('#currency').val();
            $('#currency_form').submit(function (ev) {
                ev.preventDefault();
                $.ajax({
                    type: 'POST',
                    url: 'http://localhost:8080/bankdemo/bills/add?currency='+type,
                    success: function(msg) {
                        alert(msg);
                    }
                    error: function (xhr, statusText, err) {
                      alert(xhr.status);
                    }
                });
            });
        });
    });
</script>

HTML изначально формируется по адресу
http://localhost:8080/bankdemo/accounts/show

    @GetMapping("/accounts/show")
    public String getAccount(ModelMap modelMap) {

        String current = authentication().getName();
        AccountResponseDTO account = accountService.getAccountDTO(current);
        modelMap.addAttribute("account", account);
        modelMap.addAttribute("currencies", currencies);

        return "/account/private";
    }

так вот проблема в том, что почему-то при выполнении AJAX url становится в браузерной строке
http://localhost:8080/bankdemo/accounts/show?currency=USD

вместо того, чтобы выполнить запрос по пути, который указан в скрипте.
Если через Postman забить правильный url руками, то метод контроллера отлично отрабатывает, возвращая строку ответа и статус 200.

A: Полагаю, что все из-за того что вы пытаетесь передать данные через адресную строку.
Это POST запрос, а значит данные должны быть переданы через тело запроса.
Для этого есть параметр data
Попробуйте следующее
Пробрасываем CSRF
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>

<script>
    $(document).ready(function(){
        // как-то сильно много обработчиков у вас в скрипте
        // уберем лишнее
        // $('.add_bill').click(function(){
            // отсюда валюту убрал
            $('#currency_form').submit(function (ev) {
                ev.preventDefault();
                // ПЕРЕНЕС СЮДА ОПРЕДЕЛЕНИЕ ВАЛЮТЫ
                var type = $('#currency').val();
                // еще Вы у себя забыли знак доллада перед ('#currency')
                // получаем название заголовка и значение токена
                var token = $("meta[name='_csrf']").attr("content");
                var header = $("meta[name='_csrf_header']").attr("content");
                // определяем массив с заголовками запроса и прокидываем в него CSRF
                var requestHeaders = {};
                requestHeaders[header] = token;
                $.ajax({
                    type: 'POST',
                    // убираем данные из урла
                    url: 'http://localhost:8080/bankdemo/bills/add',
                    // передаем данные в тело запроса
                    data: {
                        "currency": type
                    },
                    // пробрасываем в запрос наши заголовки
                    headers: requestHeaders,
                    success: function(msg) {
                        alert(msg);
                    }, // <- ЗАПЯТУЮ ЕЩЕ ЗАБЫЛИ
                    error: function (xhr, statusText, err) {
                      alert(xhr.status);
                    }
                });
            });
        // }); // это закрытие обработчика кнопки. его мы убрали пока что
    });
</script>


text:
Q: Uncountably many points of an uncountable set in a second countable are limit points I'm trying to solve the following exercise from Munkres book. Can you please check it?
Let $X$ be a second countable space and let $A$ be an uncountable subset of $X$. Show that an uncountable number of points of $A$ are limit points of $A$.
"Proof".
Let $C = \{x \in A: \textrm{x is a limit point of A} \}$. We want to show that $C$ is uncountable, so suppose not, then C is countable.
Let $B$ be a countable basis for $X$. Then for each $a \in A \setminus C$ we have
that a is not a limit point of $A$ so we can find a basis element $U_{a}$ such that $U_{a} \cap A = \{a\}$.
The above defines an injection from the set $A \setminus C$ to $B$ by just mapping each $a \in A \setminus C$ to $U_{a}$. Since $B$ is countable (because $X$ is 2nd countable) then $A \setminus C$ is countable.
But then $(A \setminus C) \cup C = A$ is countable, contradiction because $A$ is uncountable.

A: Arturo Magidin made a good point: if the assumption "to the contrary" is never used in a proof by contradiction, it is not really a proof by contradiction. This is a nice direct proof: let $F$ be the set of points of $A$ that are not  limit points of $A$. For each $a\in F$ there is a basis element containing $a$ and nothing else from $A$. All such $U_a$ are distinct by construction. Hence, $F$ is at most countable, and therefore $A\setminus F$ must be uncountable.

A: Just an observation: for the real line (or any Euclidean space, in fact), the limit points of an uncountable subset (all limit points, not only those which are elements of the uncountable set) should have cardinality of the continuum, since we can apply Cantor-Bendixson theorem to the uncountable closed set $\overline{A} = A \cup A' = A \cup (A' \setminus A)$ in order to get a perfect set (thus, of size continuum) included in $\overline{A}$, so either $A$ or $A' \setminus A$ should include continuum many limit points of $A$.


text:
Q: Dynamically or button click Search specific tab in tab control in c# i making some application for my office and in this application there are so many tabs (more than 50) i want to search tabs using textbox ,if its possible can someone kind enough to show how can i search dynamically instead clicking a search button
this is my code that i tried
     private void button62_Click(object sender, EventArgs e)
   {
       if (secondtabcontainer.TabPages.ContainsKey.Equals("chattextbox"))
           secondtabcontainer.SelectedTab = secondtabcontainer.TabPages["tabPage17"];

   }

   private void textBox55_TextChanged(object sender, EventArgs e)
   {

       string chattextbox;
       chattextbox = textBox55.Text;
   }

A: Try this in TextChanged event:
private void textBox55_TextChanged(object sender, EventArgs e)
{
    string sTabName = textBox55.Text;

    foreach (TabPage tab in secondtabcontainer.TabPages)
    {
        if (sTabName.Equals(tab.Name))
        {
            secondtabcontainer.SelectedTab = tab;
            break;
        }
    }
}

A: You should maintain a dictionary (Dictionary<string, string>) containing "Tab Display Name-TabID" pairs:
Dictionary<string, string> tabs = new Dictionary<string, string>();
// sample entries
tabs.Add("First Tab", "tab1");
tabs.Add("Second Tab", "tab2");
// ...
tabs.Add("chattextbox", "tab17");

Then add the tabs to the Items collection on a new ComboBox control.
Add your code to the SelectedValueChanged' event handler attached to theComboBox`.
// `TabsList` is a new control that make the tabs searchable.
protected void TabsList_SelectedValueChanged(object sender, EventArgs e)
{
    if (TabsList.SelectedIndex != -1)
    {
        var tabid = tabs[TabsList.SelectedText];
        secondtabcontainer.SelectedTab = secondtabcontainer.TabPages[tablid];
    }
}

This should allow you to type-ahead the name of a tab and automatically switch once you've made you selection.


text:
Q: Logicify Location picker using dynamic change for input I'm using Logicify Location Picker.
I want to load the map based on the lat and lng value as demonstrated in this example:

Lat.: <input type="text" id="us2-lat"/>
Long.: <input type="text" id="us2-lon"/>

But in my case i want to keep these fields for lat and long hidden and trigger change dynamically when i get the value of lat and lng based on the city name through this function:
$("#city").change(function() {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': "" + $("#city").val() + ", Pakistan"
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      $("#lat").val(results[0].geometry.location.lat()).trigger('change');
      $("#lng").val(results[0].geometry.location.lng()).trigger('change');
      alert($("#lat").val() + " " + $("#lng").val());
    } else {
      alert("Something got wrong " + status);
    }
  });
});

here are my hidden fields:
<input type="hidden" id="lat">
<input type="hidden" id="lng">

plus i have a select with id = "city" having some city names i.e lahore
and here is what i'm doing:
            var inital_lat = "31.554397"; /*lahore pakistan*/
            var inital_lng = "74.356078";
            $('#locationpicker').locationpicker({
              location: {
                latitude: inital_lat,
                longitude: inital_lng
              },
              radius: 100,
              inputBinding: {
                latitudeInput: $("#lat"),
                longitudeInput: $("#lng")
              }
            });
            $("#city").change(function() {
              var geocoder = new google.maps.Geocoder();
              geocoder.geocode({
                'address': "" + $("#city").val() + ", Pakistan"
              }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                  $("#lat").val(results[0].geometry.location.lat()).trigger('change'); /* i've also tried .change() */
                  $("#lng").val(results[0].geometry.location.lng()).trigger('change');

                  alert($("#lat").val() + " " + $("#lng").val());
                } else {
                  alert("Something got wrong " + status);
                }
              });
            });

if i make textfields type = text and enter some value and press enter the map dynamically changes, but for dynamic change (keeping fields hidden) it does not  work.
Any help would be greatly appreciated.
Update:
here is a code from locationpicker.jquery.js file:
 if (inputBinding.latitudeInput) {
   inputBinding.latitudeInput.on("change", function(e) {
     if (!e.originalEvent) {
       return
     }
     GmUtility.setPosition(gmapContext, new google.maps.LatLng($(this).val(), gmapContext.location.lng()), function(context) {
       context.settings.onchanged.apply(gmapContext.domContainer, [GmUtility.locationFromLatLng(context.location), context.radius, false]);
     });
   });
 }
 if (inputBinding.longitudeInput) {
   inputBinding.longitudeInput.on("change", function(e) {
     if (!e.originalEvent) {
       return
     }
     GmUtility.setPosition(gmapContext, new google.maps.LatLng(gmapContext.location.lat(), $(this).val()), function(context) {
       context.settings.onchanged.apply(gmapContext.domContainer, [GmUtility.locationFromLatLng(context.location), context.radius, false]);
     });
   });
 }

Looks like it looks for the change in lat and lng field, and thats what i'm doing changing it dynamically. whats the matter?

A: I have the same problem, for a quick solution you can change the code of the library locationpicker.jquery.js from the code you have pasted to this:
if (inputBinding.latitudeInput) {
   inputBinding.latitudeInput.on("change", function(e) {
     if (!e.originalEvent) {
       //return
     }
     GmUtility.setPosition(gmapContext, new google.maps.LatLng($(this).val(), gmapContext.location.lng()), function(context) {
       context.settings.onchanged.apply(gmapContext.domContainer, [GmUtility.locationFromLatLng(context.location), context.radius, false]);
     });
   });
 }
 if (inputBinding.longitudeInput) {
   inputBinding.longitudeInput.on("change", function(e) {
     if (!e.originalEvent) {
       //return
     }
     GmUtility.setPosition(gmapContext, new google.maps.LatLng(gmapContext.location.lat(), $(this).val()), function(context) {
       context.settings.onchanged.apply(gmapContext.domContainer, [GmUtility.locationFromLatLng(context.location), context.radius, false]);
     });
   });
 }

Just comment twice the return in if (!e.originalEvent) {
This is NOT the best solution, because you are changing the library, and if you update the library you lose your changes.

A: The way you trigger the textboxes won't work.
Trigger using an event object. Refactor your $("#city").change() event like this
            $("#city").change(function (evt) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
                'address': "" + $("#city").val() + ", Pakistan"
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    evt.type = 'change';//change the event's type to change whatever it was originally
                    $("#lat").val(results[0].geometry.location.lat()).trigger(evt); //use the modified event object to trigger rather passing event's name
                    $("#lng").val(results[0].geometry.location.lng()).trigger(evt);

                    alert($("#lat").val() + " " + $("#lng").val());
                } else {
                    alert("Something got wrong " + status);
                }
            });
        });

Hope this helps.


text:
Q: Bicep: Creating random string I'm coming from a Terraform background and AWS. Now I'm using Bicep with Azure, so please bear with me :)
In Terraform, we create random passwords with the random_password resource. We then stored this as a value in the AWS Systems Manager Parameter Store. This allowed us to have secure (enough...) passwords, which got created and stored in some secure database without us having to enter or even know the password. If somebody would need to know the password, it would get logged. Lovely ;)
Now...
How do I do something like this with Bicep? I'm only finding the uniqueString() function. But this only creates 13 character long random strings and also doesn't have any "special" characters like !@#$%&*()-_=+[]{}<>:? and such.
For quite obvious reasons, I don't want to have some sort of statement in my code, which sets the secret to some clearly readable value. Which is why we used random_password in Terraform.
What's the right approach to solve this in Bicep?
I found the blog post "Automatically generate a password for an Azure SQL database with ARM template" by Vivien Chevallier, but that isn't good, IMO. To circumvent the short comings of the uniqueString() function and make it comply to the password complexity rules, the person adds a constand prefix of "P" and suffix of "x!". This reduces the quality of the password, as there now 3 known characters. Out of 16.

A: The intent in Bicep is that one creates fully idempotent templates so that you should receive the same output every time you attempt to deploy anything in Bicep. As such, randomString and newGuid both accept parameters you can use to seed the result, but you'll always get the same result for the new values you put in.
For the reasons above, you're encouraged to provide your own generated password to kick off template deployment externally so there's nothing about the Bicep template that's changing from one deployment to another. On top of that, you're not really encouraged to expose the password in an output value since those are all logged indefinitely, so I highly recommend writing out the value to a Key Vault secret as in the following
@secure() //Prevents it from being logged, but also removes it from output
param password string = newGuid() //Can only be used as the default value for a param

@description('The name of the Key Vault to save the secret to')
param KeyVaultName string

@description('The name of the secret in Key Vault')
param KeyVaultSecretName string

//Save as Key Vault secret
resource KeyVault 'Microsoft.KeyVault/vaults@2021-06-01-preview' existing = {
  name: KeyVaultName
}

resource KVSecret 'Microsoft.KeyVault/vaults/secrets@2021-06-01-preview' = {
  name: replace(replace(SecretName, '.', '-'), ' ', '-')
  parent: KeyVault
  properties: {
    contentType: 'text/plain'
    attributes: {
      enabled: true
    }
    value: password
  }
}

output PasswordSecretUri string = KVSecret.properties.secretUri

And then you can use the GUID output as your password for your use-case knowing that it will be different every time you run the Bicep deployment.

A: uniqueString() is not meant for generating passwords at all, it's for generating names for resources.
As far as I know, there is no purpose-built method to generate a password in a Bicep/ARM template.
What we have done is generate passwords with sufficient length and complexity using a password generator, and store those in Azure DevOps variable groups as secrets.
Then we pass them in to the template as secure string parameters, so they don't get logged anywhere.
We also don't store those generated passwords anywhere else, they are thrown away after generating them and storing them in Azure DevOps.

A: This is not supported by bicep and there are no such plans based on a request in their repo.

This is not something we would like to take on as generating a cryptographically secure password, with a variety of restrictions based on the resource type is better handled in a deployment script or by using a key vault to generate the password.

A: For some secrets in Azure, uuid is not good enough, for example, the VM's password

message": "The supplied password must be between 6-72 characters long and must satisfy at least 3 of password complexity requirements from the following: 1) Contains an uppercase character 2) Contains a lowercase character 3) Contains a numeric digit 4) Contains a special character 5) Control characters are not allowed

I did an improvement based on @Whit Waldo 's answer
$ cat deploy.bicep

param guidValue string = newGuid()

var adminPassword = '${toUpper(uniqueString(resourceGroup().id))}-${guidValue}'

output adminPasswordOutput string = adminPassword

$ az group create --name "test" --location "Central US"
$ az deployment group create --name test --resource-group test --template-file deploy.bicep


text:
Q: LightBox2 producing error Site: http://www.onlinetestspace.com/project45/before-after
I have followed lightBox instructions http://leandrovieira.com/projects/jquery/lightbox/ and chrome is giving me the error:

Uncaught TypeError: Object # has no method 'lightBox'.

Can somebody please help me out?

A: I just investigate the things and i guess you are using old version of JQuery file (jQuery 1.2.3). Use the latest version of JQuery file and this will fix your problem.

A: The reason I was getting this error, was simply because of 2 conflicting files.


text:
Q: Obtain a Neyman-Pearson Test of H0: p1=p2=2/5 against the alternative p1=1/2 and p2=1/5 when the type 1 error is 0.05 I kinda have some trouble trying to start with this question.

I  know how to derive a Neyman-Pearson Test and its critical region. My main concern is deriving the Likelihood function of the sample given its null hypothesis and its alternative hypothesis.
I'd like to solve this on my own but I'm not sure how to start it.


text:
Q: Trouble ADDING points to quiz game. It adds 2 instead of 1. JS I've looked into the stackoverflow recommendations about posts with similar titles and nothing solved my issue. Im new to JS, im trying to make a simple multiple choice quiz. If you get it correct you score a point, if not, u don't get any but the question counter increases, the thing is after the first question everything adds double the value, here's a quick video showcasing de error: https://gyazo.com/9fbdf63508b2713992935d813f29788e  pay attention to the bottom-right corner.
This is a side project and I've been stuck on it for almost 2 weeks now.. no joke. Any help is extremely appreciated, my main language is Spanish so that's the reason of the variables names. Here's the code:

let pregunta = document.getElementById('preguntafinal');
let puntaje = document.getElementById('puntaje');
let opcion1 = document.getElementById('opcion1');
let opcion2 = document.getElementById('opcion2');
let opcion3 = document.getElementById('opcion3');
let opcion4 = document.getElementById('opcion4');
let puntito1 = document.querySelector('puntito1');
let idPreg = 0;
let respSeleccionada;
let puntosTotales = 0;
let preguntasTotales = 0;

function iterarJuego() {
  pregunta.innerText = arrayPreguntas[idPreg].preg;
  opcion1.innerText = arrayPreguntas[idPreg].opcionuno;
  opcion2.innerText = arrayPreguntas[idPreg].opciondos;
  opcion3.innerText = arrayPreguntas[idPreg].opciontres;
  opcion4.innerText = arrayPreguntas[idPreg].opcioncuatro;;
  elegirRespuesta();
}

function elegirRespuesta() {
  opcion1.addEventListener("click", asd => {
    respSeleccionada = arrayPreguntas[idPreg].opcionuno;
    funAnalizar(respSeleccionada);
  });
  opcion2.addEventListener("click", asd => {
    respSeleccionada = arrayPreguntas[idPreg].opciondos;
    funAnalizar(respSeleccionada);
  });

  opcion3.addEventListener("click", asd => {
    respSeleccionada = arrayPreguntas[idPreg].opciontres;
    funAnalizar(respSeleccionada);
  });

  opcion4.addEventListener("click", asd => {
    respSeleccionada = arrayPreguntas[idPreg].opcioncuatro;
    funAnalizar(respSeleccionada);
  });
}

function funAnalizar() {
  console.log(respSeleccionada);
  console.log(arrayPreguntas[idPreg].error);
  if (respSeleccionada == arrayPreguntas[idPreg].error) {
    console.log("correcto");
    respCorrecta(respSeleccionada);
  } else if (respSeleccionada != arrayPreguntas[idPreg].error) {
    console.log("incorrecto");
    respIncorrecta(respSeleccionada);
  }
}

function respCorrecta() {
  puntosTotales++;
  preguntasTotales++;
  puntaje.innerText = puntosTotales + "/" + preguntasTotales;
  idPreg++;
  iterarJuego(idPreg);
  console.log("ja");
}

function respIncorrecta() {
  preguntasTotales++;
  puntaje.innerText = puntosTotales + "/" + preguntasTotales;
  idPreg++;
  iterarJuego(idPreg);
  console.log("jant");
}

arrayPreguntas = [{
  idPreg: 0,
  preg: "Que significa AI en Japonés?",
  opcionuno: 'amor',
  opciondos: 'carcel',
  opciontres: 'pizza',
  opcioncuatro: 'caja',
  error: 'amor'
}, {
  idPreg: 1,
  preg: "Cual es el hiragana 'ME' ?",
  opcionuno: 'ぬ',
  opciondos: 'ね',
  opciontres: 'ぐ',
  opcioncuatro: 'め',
  error: 'め'
}, {
  idPreg: 2,
  preg: "En hiragana: DESAYUNO , ALMUERZO , CENA ?",
  opcionuno: 'ぬ',
  opciondos: 'ね',
  opciontres: 'ぐ',
  opcioncuatro: 'め',
  error: 'め'
}, {
  idPreg: 3,
  preg: "Como se dice madre y padre ?",
  opcionuno: 'chichi hana',
  opciondos: 'hana mitsu',
  opciontres: 'kirei chichi',
  opcioncuatro: 'undo chichi',
  error: 'kirei chichi'
}, {
  idPreg: 4,
  preg: "Que significa きれい ?",
  opcionuno: 'rey y reina',
  opciondos: 'lindo y linda',
  opciontres: 'hermoso y hermosa',
  opcioncuatro: 'salvaje y saldro',
  error: 'lindo y linda'
}]

iterarJuego();

That's the .js ..if for some reason the html is needed ill add it with an edit.

A: Redid everything into English, it was messy (BTW there's a button called "Tidy" in the editor) but I couldn't find the bug, I might've corrected it without being aware I had? Anyways, I liked the flow of the code so instead of giving up I made some improvements.
The terse syntax is from HTMLFormElement interface:
Figure I
// <form id="QA"> name attribute can be used as id
const QA = document.forms.QA;
// We can make a reference to all form controls in <form>
const IO = QA.elements;
// With that defined, referencing form controls is simple
IO.question // <output id='question'>
IO.next     // <button id='next'>

The HTMLFormControlsCollection interface allows us to group form controls by a common name attribute and use array methods on them or extract a value of a checked or selected form control:
Figure II
// 1 of 4 <input id='optB' name='opt' type='radio' value='optB' checked>
IO.opt       // HTMLCollection of all [name='opt']
[...IO.opt]  // Array of all [name='opt']
IO.opt.value // Automatically gets the value of the checked [name='opt']

I replaced the 4 click handlers with one submit handler:
Figure III
// <form> is bound to the submit event
QA.onsubmit = evaluate;
function evaluate(e) {
  e.preventDefault();

If you decide to handle the submit event remember to use e.preventDefault()
otherwise the  will attempt to send data to a server, and the response
will kill the page.

<!DOCTYPE html>

  <title></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <form id='QA'>
      <fieldset>
        <legend><output id='score'></output></legend>
        <output id='question'></output>

            <input id='optA' name='opt' type='radio' value='optA'>

            <input id='optB' name='opt' type='radio' value='optB'>

            <input id='optC' name='opt' type='radio' value='optC'>

            <input id='optD' name='opt' type='radio' value='optD'>

        <menu>
          <button id='next'>Next</button>
        </menu>
      </fieldset>
    </form>


text:
Q: How to get updated page content after a JS event using phantomjs? I have a page with a simple form. This form has ONE input text.
I have this code:
page.open("http://www.example.com", function (status) {
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js", function() {
        page.evaluate(function() {
            $('input[name=myText]').val('my content');
        });
    });
});

(as you can see i also loaded jquery)
Now, when i set the content of this input text, the page changes, the content of the page changes.
My question is: how can I get the updated content?
The problem is that i need to submit the form but i can not do it after:
$('input[name=myText]').val('my content');

because when i set it there is an JS event on the page that changes the content.
SO I must read the new content, find the form using JQuery and then submit it.
Could someone help me?
Thank you!

A: So your page.evaluate() call has a side effect and that changes the page. The question is whether this change occurs instantaneously. But you cannot assume that it does - particularly if it causes a fetch of new content from a remote webserver.
That being the case the best thing you can try is to sleep for a while and then assume your page has the new content. Or alternatively, when you feel more advanced, poll on a regular basis for a DOM object you are expecting to appear. But the beginner should try a sleep:
....
page.evaluate( function() { ... } );
window.setTimeout(
    function() {
        /* press submit button */
    },
    5000 /* wait 5 seconds (5,000ms) */
);
....


text:
Q: Is the fixed point set of a self-diffeomorphism of odd order orientable? Let $M$ be a smooth oriented manifold and let $f \colon M \to M$ be a self-diffeomorphism with $f^p = \text{id}_M$ for some odd $p > 0$. Then $f$ is orientation preserving and it follows from the slice theorem that the fixed point set
$$
F = \{ x \in M : f(x) = x\}
$$
is a smooth submanifold of $M$. Is $F$ orientable?


text:
Q: Dynamic creation of tables (classes) with DataMapper? So, i'm trying to make a small "social network" for educational purposes but i'm stuck at giving the users "friends" in the database. You can probably do it in a easier way but the only way that I could think of was to have a separate table for each user that contains their friends.
However, to do this, I need to create tables dynamically with a variable as table name. I've tried with const_set but it seems like it doesn't work with DataMapper for some reason (or I might just be stupid). Keep getting errors like uninitialized constant Serial when I'm trying to add properties.
So what should I do? Is there a solution? Can I create tables dynamically some other way? Or is there an easier way of saving the friends.
Thanks.

A: module DMSerial
  def self.included base
    base.class_eval do
      include DataMapper::Resource
      property :id,           base::Serial
    end
  end
end

def create_model model_name, &block
  Object.const_set(model_name, Class.new)
  model = Object.const_get(model_name)
  model.class_eval {include DMSerial}
  model.class_eval &block
end

[1,2,3].each do |num|

  create_model "Model#{num}" do
    property :val,  Integer, :default => num
  end

end


text:
Q: Ajax form not submitting to controller action Ajax form is not submitting to controller action. Here is the code
@using (Ajax.BeginForm("searchCustomers", "Transaction", new { phoneNumber = Model.CustomerMobile }, new AjaxOptions
                {
                    UpdateTargetId = "custList",
                    InsertionMode = InsertionMode.Replace
                }))
                {

                            Customer Mobile No:
                            @Html.TextBoxFor(x => x.CustomerMobile, new { @class = "form-control", id = "custMobile" })

                        @*

                            Customer Name
                            @Html.TextBoxFor(x => x.CustomerName, new { @class = "form-control", id = "custName" })

*@
                        <input type="submit"  class="btn btn-default" value="Get Customer Details" >

                }

Here is the controller action
 public ActionResult searchCustomers(string phoneNumber)
    {
        if (phoneNumber==null)
        {
            return PartialView(new List<Models.Customer>());
        }

        var c = Database.Session.Query<Models.Customer>()
            .Where(x => x.MobileNumber.Like(phoneNumber) )
            .ToList();
        return PartialView(c);

    }

but the ajax form is not submitting. I've added the JavaScript files as bundles. I've another @Html.Action("searchCustomers", new { phoneNumber = Model.CustomerMobile }) this one calls the controller action.

A: Everything is fine in your code. There are two javascript files that are needed for Ajax.Beginform to work.

*

*jquery-{Vaersion}.js

*jquery.unobtrusive-ajax.js

Check whether you have included those files to your view or not. Or if your view has any LayOut if those javascript files are included in your LayOut or not.


text:
Q: how to i fix my firebase rule issue which always getting false condition? My issue is that In my firebase database i want to access write in categories child only for admins and I have all the admins listed in the "ADMIN" child of my root. and inside admin child I stored all the users info with the child of their uids; Like this:

       root
         |
         |--ADMIN
         |   |
         |   |--Hu1QtgYoL4SF3nUFdTcrTamCdfb2
         |                |
         |                |-- id: "84bvMZRKbutMZh5zBwxaRZdA9mVI1yDEPVuxvIWrl2tElid..."
         |                |-- imageUri: ""
         |                |-- name: "Sahil"
         |                |-- password: "8zYQEN001zhQ7XZjzqHUnTIeCDIPvtI38Ra+X68a8/o=\n"
         |--CATEGORIES
               |--My_DATA

At present, I am using this rule for my firebase realtime database:

    {
      "rules": {
        "USERS": {
        ".read": "auth != null",  // 2021-8-14
        ".write": "auth != null",  // 2021-8-14
        },
        "CATEGORIES":{
          ".read": "auth != null",
          ".write": "root.child('ADMIN').child('auth.uid').exists()",
        },
          "ADMIN": {
          ".read": true,
          ".write": true,
          }
      }
    }

my rule is giving always false condition even if I type a uid which exists in admin child.

A: You wrote auth.uid as String. Try to change your rules to this:
{
  "rules": {
    "USERS": {
    ".read": "auth != null",  // 2021-8-14
    ".write": "auth != null",  // 2021-8-14
    },
    "CATEGORIES":{
      ".read": "auth != null",
      ".write": "root.child('ADMIN').child(auth.uid).exists()",
                                        //     removed quotes
    },
      "ADMIN": {
      ".read": true,
      ".write": true,
      }
  }
}


text:
Q: File size limit for macros-vba in excel? Is there a size limit where it may cause macros to not work some times? I'm at 450KB to 460KB after data entries. The issue is sometimes the time and date stamp doesn't work. I have the same form on 7 different computers and it happens randomly. Not sure if its a user error or code error but thought I ask the question on size limit.
Private Sub Worksheet_Change(ByVal Target As Range)

Dim CC As Range
Dim CB As Range

Application.EnableEvents = False
 If Not Intersect(Range("C16:C101"), Target) Is Nothing Then
 For Each CC In Intersect(Range("C16:C101"), Target)
    If CC.Value <> "" Then
        CC.Offset(, -2).Value = Date & " "
        CC.Offset(, -2).NumberFormat = "mm/dd/yy"
    End If
 Next CC
 End If
Application.EnableEvents = True

Application.EnableEvents = False
 If Not Intersect(Range("C16:C101"), Target) Is Nothing Then
 For Each CC In Intersect(Range("C16:C101"), Target)
    If CC.Value <> "" Then
        CC.Offset(, -1).Value = Time & " "
        CC.Offset(, -1).NumberFormat = "hh:mm"
    End If
 Next CC
 End If
Application.EnableEvents = True

Application.EnableEvents = False
 If Not Intersect(Range("x16:x101"), Target) Is Nothing Then
 For Each CC In Intersect(Range("x16:x101"), Target)
    If CC.Value <> "" Then
        CC.Offset(, 1).Value = Date & " " & Time
        CC.Offset(, 1).NumberFormat = "mm/dd/yy hh:mm"
    End If
 Next CC
 End If
Application.EnableEvents = True

Application.EnableEvents = False
 If Not Intersect(Range("AC16:AC101"), Target) Is Nothing Then
 For Each CB In Intersect(Range("AC16:AC101"), Target)
    If CB.Value <> "" Then
        CB.Offset(, -1).Value = Date & " "
        CB.Offset(, -1).NumberFormat = "mm/dd/yy"
    End If
 Next CB
 End If
Application.EnableEvents = True

Application.EnableEvents = False
  If Not Intersect(Range("Ah16:Ah101"), Target) Is Nothing Then
  For Each CB In Intersect(Range("Ah16:Ah101"), Target)
    If CB.Value <> "" Then
        CB.Offset(, -1).Value = Date & " " & Time
        CB.Offset(, -1).NumberFormat = "mm/dd/yy hh:mm:ss"
    End If
  Next CB
  End If
Application.EnableEvents = True

Application.EnableEvents = False
 If Not Intersect(Range("Am16:Am101"), Target) Is Nothing Then
 For Each CB In Intersect(Range("Am16:Am101"), Target)
    If CB.Value <> "" Then
        CB.Offset(, -1).Value = Date & " " & Time
        CB.Offset(, -1).NumberFormat = "mm/dd/yy hh:mm:ss"
    End If
 Next CB
 End If
Application.EnableEvents = True

End Sub


text:
Q: byte array in ios I'm trying to convert this Javascript code:
self.userSerialEvent = function (join, value, tokens) {
        var type = join.charCodeAt(0);
        var rawJoin = parseInt(join.substr(1)) - 1;
        var rawValue = parseInt(value);
        self.SJValues[join] = value;

        var payload = "\x00\x00" + String.fromCharCode(value.length + 2) + "\x12" + String.fromCharCode(rawJoin) + value;
        self.sendMsg("\x05\x00" + String.fromCharCode(payload.length) + payload);
    };

to objective c code for an ipad app.
However I cannot figure out how to properly form this
If I do a char array I cannot have variable length (which will happen when the value is added to the array).  And when I try to use NSMutableArray I cant insert bytes, plus my network send operation takes an NSData and I cannot convert a NSMutableArray to data.  I have also tried NSString but when I do:
NSString * payload = [NSString stringWithFormat:@"0000%d12%d%@",value.length+2,rawJoin,[value dataUsingEncoding:NSASCIIStringEncoding]];

I get the < > around the data in the string.  I have tried to create a character set and remove "<>" from the string but that only removed the end one (leaving the beginning < there)
My question is this: How can I form an array of bytes, that is of variable length and able to convert that array to NSData

A: Sounds like you are looking for NSMutableData.
NSMutableData *payload = [[NSMutableData alloc] init];
[payload appendBytes:"\000\000" length:2];
uint8_t length = value.length + 2;
[payload appendBytes:&length length:1];
[payload appendBytes:"\022" length:1];
// etc.