Q: Box shadow effect I'm trying to apply a shadow to a div, however I have been unable to achieve the desired effect. Effect to be 'below' the element.
Example: http://www.paulund.co.uk/creating-different-css3-box-shadows-effects
JSFiddle: http://jsfiddle.net/Ck7pG/
CSS
ul#nav li {
    display: inline;
    line-height: 40px;
}

 /* Shadow effect */
.shadow-effect {
    position: relative;
    -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
    -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}

.shadow-effect:before, .shadow-effect:after {
    content: "";
    position: absolute;
    z-index: -1;
    -webkit-box-shadow: 0 0 10px rgba(0,0,0,0.8);
    -moz-box-shadow: 0 0 10px rgba(0,0,0,0.8);
    box-shadow: 0 0 10px rgba(0,0,0,0.8);
    top: 20%;
    bottom: 0;
    left: 50px;
    right: 50px;
    -moz-border-radius: 100px / 10px;
    border-radius: 100px / 10px;
}

A: I just assumed your requirement from the website you provided,i think this is what you need
DEMO
.shadow-effect {
    position:relative;
    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px                 rgba(0, 0, 0, 0.1) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.shadow-effect:before, .shadow-effect:after {
    content:"";
    position:absolute;
    z-index:-1;
    -webkit-box-shadow:0 0 10px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 10px rgba(0,0,0,0.8);
    box-shadow:0 0 10px rgba(0,0,0,0.8);
    top:20%;
    bottom:0;
    left:50px;
    right:50px;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
}

.box h3{
    text-align:center;
    position:relative;
    top:80px;
}
.box {
    width:70%;
    height:100px;
    background:#FFF;
    margin:40px auto;
}

.effect6
{
    position:relative;
    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.effect6:before, .effect6:after
{
    content:"";
    position:absolute;
    z-index:-1;
    -webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
    box-shadow:0 0 20px rgba(0,0,0,0.8);
    top:50%;
    bottom:0;
    left:10px;
    right:10px;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
}


Q: Equivalent formulation of a regression (subtracting something from a dep var or controlling for it) From my Stata experiment, the following two approaches give the same coefficient and standard errors for X.
(1) regressing Y1-Y2 on X and Y2.

(2) regressing Y1 on X and Y2.

That is,
(1) gen Ydiff = Y1-Y2
    reg Ydiff X Y2

(2) reg Y1    X Y2

Is this generally true? Why would that be the case?

A: Yes, this is generally true.
Given data $(x_i, y_{1i}, y_{2i}),$ the second model supposes
$$y_{1i} = \beta_0 + \beta_1 x_i + \beta_2 y_{2i} + \varepsilon_i$$
for fixed unknown $\beta_j$ (which are estimated by reg).  The first model supposes
$$y_{1i} - y_{2i} = \alpha_0 + \alpha_1 x_i + \alpha_2 y_{2i} + \delta_i.\tag{**}$$
By subtracting $y_{2i}$ from both sides of the first model you obtain the equivalent model
$$y_{1i}-y_{2i} = \beta_0 + \beta_1 x_i + (\beta_2-1) y_{2i} + \varepsilon_i.\tag{*}$$
Comparing this term-by-term to the first model shows $(*)$ and $(**)$ are the same but merely use different notation with
$$\alpha_0 = \beta_0,\ \alpha_1=\beta_1,\ \alpha_2 = \beta_2 - 1,\ \text{ and }\delta_i=\varepsilon_i.$$
Consequently the model estimates will have the same relationships; in particular, $\hat\alpha_0 = \hat\beta_0$ (the estimated intercept) and $\hat\alpha_1=\hat\beta_1$ (the estimated slopes) must be equal whenever the estimates are unique (which is the case when the $x_i$ are not constant). (You will also notice that $\hat\alpha_2 = \hat\beta_2 - 1.$)
Furthermore, the residuals will be the same and will have the same meanings, so the software will report that the root mean squared errors are the same. That causes all the standard errors of the parameter estimates to be the same in the two models.
However, the software will likely report a different $R^2,$ because that depends also on the variance of the responses and there's no assurance the variance of the $y_{1i}$ (in the second model) will equal the variance of the $y_{1i}-y_{2i}$ (in the second model).

A: This is definitely not true in general.
The obvious case where this is true is when the Y2 is all zeros, then your equations are equal to each other.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y1 = x
y2 = x - x

# coef for x is 1 in both cases

And the obvious case where this is not true, set Y1 == Y2 (both non-zero) then in the first case, your dependent variable is all 0s, therefore the coefficient for X has to be 0, but in the second case, it won't be all 0s.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y1 = x
y2 = x

# coef for x is
#   eq(1): 0
#   eq(2): 0.5


Q: vsftpd: 550 Failed to change directory I'm using ubuntu 12.04. and ftp service I've installed vsftpd and it's working fine. But may I'm facing some user complexity.
My system directory like:
-/
--/home
----/rony
--/vol

When I list directories through ftp, it's going to /rony first. But when I cd /vol or cd .., it's showing 550 Failed to change directory error.

A: As http://en.wikipedia.org/wiki/List_of_FTP_server_return_codes states,

550   Requested action not taken. File unavailable (e.g., file not found, no access).

You either don't have file system permissions to access these directories or the server is set up such that it treats /home as the file system root.
You could of course have googled a bit and found something like http://www.linuxquestions.org/questions/linux-server-73/550-failed-to-change-directory-835003/


Q: If local rings are Noetherian, is scheme locally-Noetherian? If all the local rings of a scheme are Noetherian, is the scheme locally-Noetherian?

A: Take an algebraically closed field $k$, so that $k$ is infinite, and take a sequence $(\alpha_i)_{i\geq 1}$ of distinct elements in $k$. Consider $A = k[S,T_1,\ldots,T_n,\ldots]$ and the ideal $I$ of $A$ generated by all $(S-\alpha_i)T_{i+1} - T_i$ and $T_i^2$ for $i\in\mathbf{N}^*$. Finally, take $B = A / I$.
Then $B$ is not a noetherian ring (exercise !) and $B_{\mathfrak{p}}$ is noetherian for all prime ideals $\mathfrak{p}$ of $B$. As noetherianess is preserved by localization, it suffice to check that $B_{\mathfrak{p}}$ is noetherian for all maximal ideals $\mathfrak{p}$ of $B$. Now, the nilradical $N$ of $B$ is clearly the ideal generated by the images of the $T_i$'s (as those are clearly in $N$ and as the ideal $J$ they generated verifies that $B/J$ is a domain) and $B/N \simeq k[S]$, so the maximal ideals are (because $k$ is algebraically closed) of the form $\mathfrak{m} = (S-\lambda, T_1,\ldots,T_n,\ldots)$ for $\lambda\in k$. Take $\mathfrak{m}$ such an ideal. If $\lambda$ is an $\alpha_i$ then for $j\not=i$ you have $T_{j+1} =  T_{j} / (S - \alpha_i)$ in $B_{\mathfrak{m}}$ so that $B_{\mathfrak{m}}$ appears as the localization of a ring generated by two elements $S$ and $T_i$, and is therefore noetherian. If $\lambda$ is not an $\alpha_i$, an argument analogue to the one of the previous case shows that $B_{\mathfrak{m}}$ appears as a localization of a ring generated by $S$ and $T_1$ and is also noetherian.
Now, as an affine scheme is noetherian if and only if its ring of global sections is a noetherian ring, we have shown that $X=\textrm{Spec}(B)$ is a non-noetherian affine scheme (and if fact non locally noetherian : would it be locally noetherian it would be noetherian also, as it is quasi-compact being affine) whose local rings are all noetherian rings.

A: Take any infinite boolean ring, such as $\mathbb{F}_2 \times \mathbb{F}_2 \times \dotsc$. All localizations at prime ideals are local boolean rings, hence $\mathbb{F}_2$, but infinite boolean rings are not noetherian.
More generally, one can show that a commutative ring $R$ is von Neumann regular if and only if $R_\mathfrak{p}$ is a field for all prime ideals $\mathfrak{p}$. There are lots of von Neumann regular rings which are not noetherian.
This is one of many reasons why localizations at prime ideals are not as good as localizations at elements. In fact, we have the following result (which is useful for the definition of locally noetherian schemes):

If $A$ is a commutative ring and $f_1,\dotsc,f_n$ are elements of $A$ generated the unit ideal such that each $A_{f_i}$ is noetherian, then $A$ is noetherian, too.

The geometric explanation is that $A_{f_i}$ captures the information of the whole basic-open subset $D(f_i)$ of $\mathrm{Spec}(A)$, whereas $A_{\mathfrak{p}}$ only captures the information of sufficiently small neighborhoods of the point $\mathfrak{p}$.
The notion of a noetherian scheme is not so good as one might think. There are noetherian schemes, even varieties, whose ring of global sections is not noetherian (math.SE/818578).


Q: issue with empty slide in JSSOR Slider and goto currentIndex property not working in javascript Hi I am working on JSSOR SLider and am trying to load a set of images on to it from database.
I am able to load therse images onto slider but i am getting first slide as an empty slide and rest are working fine.
In my index.html

in my js file
$('#galleryItem').on('pageshow', function () {
    var verticaltext = "";

    if ($('#galleryItem').has('#HomeImgSliders').length) {

        $("#HomeImgSliders").append("");

    }

    var allItems = Tables.images.all().order("capturedYear", false).order("capturedMonth", false).order("capturedDate", false);

    allItems.list(null, function (results) {
        var verticaltext = "";
        results.forEach(function (r) {

            // alert(JSON.stringify(r));
            imageDetailsarr.push([r.capturedDate, r.name, r.ratingTreatment, r.ratingSkinCleansing, r.ratingPlucking, r.ratingView, r.ratingLastVal, r.capturedDate, r.capturedMonth, r.capturedYear]);

            //  console.log("record is " + r.name);
            verticaltext = verticaltext + "

"

            //

        });

        $("#HomeImgSliders").append(verticaltext);
        // $("#HomeSlides").append(verticaltext);
        sliderDataReady(verticaltext);
 });

});

How can i get rid of this empty image that is appearing as the first slide
2) Also how can i set the slider set to a particular slide image based on some integer value that changes every time. I tried GoTO/slideIndex /currentIndex properties but could not get it ?
Any help would be appreciated ?Thanks

A: Re 1: Please dump value of 'verticaltext', with it you can create a static slider to see why there is an empty slide.
Re 2: Please use $StartIndex option
var options = {
    ...,
    $StartIndex: 0,    //specify slide index to display at the beginning.
    ...
};


Q: Char movement, getting x/y speeds from 2 points So i'm trying to make a program in java and i need to figure out how much I should add to x and y to make the player movement a constant speed at any angle. The information i have is 2 points, a starting point and an and and I need the char to move from a to b at a constant speed. I'm currently trying to figure out a bunch of different Math methods but I just cant get it right. Thanks in advance.

A: It's actually quite simple. You have points A (A.x, A.y) and B (B.x, B.y) and need the update for your character position.
Start by calculating the direction vector dir = B - A (subtract component-wise, such that dir.x = B.x - A.x; dir.y = B.y - A.y).
If you add this entire vector to your character's position, you will move it by sqrt(dir.x^2 + dir.y^2) (Pythagorean theorem). Hence, the speed will be: speed = sqrt(dir.x^2 + dir.y^2) / frameTime.
So if you want a constant speed, you have to find a multiple of the direction vector. This will be:
update = dir * speed / sqrt(dir.x^2 + dir.y^2) * frameTime
characterPosition = characterPosition + update

Don't bother with angle calculations. Vector arithmetic is usually way more robust and expressive.

A: Since u didn't provide us code I can just guess what exactly you are trying.
So I'll start with some basics.
I guess you are not just trying to make a program
but the basic movement of an 2d based game engine.
However a constant moving is based of an update method
that reads the player input about 30 times while rendering.
Example from my Projects:
public void run() {
    boolean isRunning = true;
    long lastNanoTime = System.nanoTime(),nowNanoTime = System.nanoTime();
    final double secondAsNano = 1000000000.0;
    final double sixtiethOfSecondAsNano = secondAsNano / 30.0;
    int delta = 1;
    while(isRunning){
        nowNanoTime = System.nanoTime();
        if(delta * sixtiethOfSecondAsNano + lastNanoTime < nowNanoTime){
            update();
            delta++;
            if(delta == 30){
                delta = 1;
                lastNanoTime = nowNanoTime;
            }
        }
        render();
    }
}

public update(){
    if(Input.moveUP) setPlayerY(getPlayerY() - 0.2);
    if(Input.moveDOWN) setPlayerY(getPlayerY() + 0.2);
    if(Input.moveRIGHT) setPlayerX(getPlayerX() + 0.2);
    if(Input.moveLEFT) setPlayerX(getPlayerX() - 0.2);
}

I just cut it down to be easy readable so it might not work correct but it should explain you how its basically done.

A: Mathematically (I won't provide code, sorry), assuming you can move in any direction on a two dimensional plane, from the top of my head it could be something like this (taken from old school geometry):

*

*Having a speed, let's say 20 pixels per second (it could also be any other unit you chose, including in-game distance)

*Having a polling system, where you have 2 main variables: the last known coords for the char (point A: Ax, Ay), the time of the last known update.

*Having the time of the current update.

*Having the coords for the destination (point B: Bx, By).

*Figure out the current position of your character, which could be done like this (without converting from cartesian to polar coord system):

*Figure out angle of movement: find the deltas for X and Y (Dx=Bx-Ax and Dy=By-Ay respectively), and use tangent to find the angle where Angle = tan-1(Dy/Dx).

*Figure out the travelled distance (TD) from last poll to current poll where TD = speed * elapsed time

*Figure out the coords for the new position (Cx and Cy) using sine and cosine, where travelled X is Tx=TD*sin(Angle) and travelled Y is Ty=TD*cos(Angle).

*Now add the travelled distances to your original coords, and you get the current position. Where Cx=Ax+Tx and Cy=Ay+Ty.

How "smooth" movement is depends highly on the quality of your polling and somehow also on rounding for small distances.

A: I ended up figuring this out almost an hour after posting this. Sorry that my question was so vague, what I was looking for was the math behind what i was trying to do not the code itself but thanks to people who answered. Here is the solution I came up with in code :
            if (q.get(0)[0][0] > q.get(0)[1][0]) {
                if(q.get(0)[0][0] == q.get(0)[1][0]) {
                    currentLocation[0] -= 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] += 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
                else{
                    currentLocation[0] -= 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] -= 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
            } else {
                if(q.get(0)[0][0] == q.get(0)[1][0]) {
                    currentLocation[0] += 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] -= 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
                else{
                    currentLocation[0] += 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] += 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
            }

I figured out a way to get the result I wanted though I probably over complicated it. q is an ArrayList that holds 2d arrays that are 2x2 [a/b][x/y]. and currentLocation a 2 index array that's just [x/y]. The result is the affect I wanted where it draws a line in (X units) a pass from point a to b in any direction at the same speed. This question was poorly worded and i'm sorry for wasting peoples time.


Q: Trigger doesn't work (if statement) I have a problem. I want to create a trigger.
    DELIMITER $
    Create trigger xyz
    before delete on worker
    FOR EACH ROW
    Begin
    IF salary>2000
    then
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Zakaz usuwania';
    end if;
    End$
    DELIMITER ;

delete from pracownik where id=5

I get an error:

Error Code: 1054. Unknown column 'salary' in 'where clause'


Q: By a great deal or by a great degree? If i want to say that (A) is longer than (B) to a great extent?
Can i say "(A)  is longer than (B) by a great degree" or by a great deal" or there is another expression that can be used ?

A: You could simply say "much greater than." There is a mathematical symbol for this. From Wolfram Mathworld:

"Much greater" is used to indicate a strong inequality in which a is
  not only greater than b, but much greater (by some convention), is
  denoted a>>b. For an astronomer, "much" may mean by a factor of 100
  (or even 10), while for a mathematician, it might mean by a factor of
  10^4 (or even much more).
Euclid used the terminology that if a is greater than  b and b is
  greater than  c, then a is said to be much (or far) greater than c. In
  that sense, "far greater than" is synonymous with "greater than" for a
  dense set of ordered quantities.

In your case, the sentence would be: "The length of a is much greater than the length of b."

A: A comparison of lengths would benefit from expressions like "A is twice as long as B" or "A is half again as long as B", rather than the fuzzier phrases like "by a great deal."  (Or strong, rather than long, if strength is what is being compared.)
With less measurable attributes, one might speak of A as a great deal more intriguing, fascinating, arresting, awesome, (informally) mind-blowing, than B.


Q: Sass styles are not applying I wanted to know why my styles of class="project-borders" and class="project-overlay" are not applying to div elements of data-modal="modal3" and data-modal="modal6". These styles are applying to every div element where used, except these two. I don't understand what's the problem even though the classes are the same across every div element. You can see the styles by removing class="project-borders" from div elements of data-modal="modal3" and data-modal="modal6".
Here is the visual representation:- Codepen
Please any help would be appreciated.
My HTML:

Coffee Grounds

Startup Employee Directory

Words Guessing Game

Motorcycle Parallax

Picture Portfolio

Video Creator Portfolio

My SASS:
.projects{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    width: 80%;
    margin: 0 auto;
    column-gap: 50px;
    row-gap: 50px;
    // margin-top: 60px;
    padding-top: 6%;

    img{
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
}

.project-borders{
    position: relative;
    border: 2px solid #000;

    img{
        width: 100%;
        height: 100%;
        cursor: pointer;
        position: absolute;
        left: 10px;
        top: 10px;
    }

    &::before{
        position: absolute;
        border: 2px solid #ffde59;
        content: "";
        display: block;
        position: absolute;
        top: 25px;
        left: 25px;
        right: -20px;
        bottom: -20px;
    }

    .project-overlay{
        position: absolute;
        left: 10px;
        top: 10px;
        bottom: 0;
        transition: .5s;
        background-color: rgb(76, 72, 68);
        transition: .5s ease;
        width: 100%;
        height: 100%;
        opacity: 0;

        & p{
            position: absolute;
            font-size: 20px;
            top: 45%;
            width: 100%;
            text-align: center;
            color: #fff;
            transition: .5s;
            opacity: 0;
        }
    }
    &:hover .project-overlay{
            cursor: pointer;
             opacity: 1;
             z-index: 1;

    }
    &:hover .project-overlay p{
        cursor: pointer;
        display: block;
        opacity: 1;
        z-index: 1;
    }
}

A: Based on your codepen, it doesn't seem like the 3rd and 6th modals are the problem with the styles displaying. The real problem is that all the content in your modals are absolutely positioned which takes them out of the ordinary context of the document, which causes the project-borders containers to have a height that only consists of the borders. You'll need to define a fixed height for that container for things to display correctly like so...
.project-borders {
    position: relative;
    border: 2px solid #000;
    height: 209px;
}


Q: Parsing dl tag using Jsoup I am trying to parse a
 tag using Jsoup. The
 tag contains
 tags and
 tags. I have a HashMap (HashMap<String, List<String>) in which I want to put the
s as keys and
s as values (there are multiple
 tags per
 tag.
The HTML looks like this:

    Parameters:

    y - the ordinate coordinate

    x - the abscissa coordinate

    Returns:

    the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

I've tried the following:
String title = "";
List<String> descriptions = new ArrayList<>();
for (int i = 0; i < children.size(); i++) {
    Element child = children.get(i);

    if(child.tagName().equalsIgnoreCase("dt")) {
        if(descriptions.size() != 0) {
            block.fields.put(title, descriptions);
            descriptions.clear();

        }

        title = child.text();
    }
    else if(child.tagName().equalsIgnoreCase("dd")) {
        descriptions.add(child.text());

        if(i == children.size() - 1) {
            block.fields.put(title, descriptions);
        }
    }
}

I expected to get this:
 * Parameters -> y - the ordinate coordinate
 *               x - the abscissa coordinate
 * Returns    -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

But I got this:
 * Parameters -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

 * Returns    -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

A: You need to insert a copy of your descriptions list into the map, currently you manipulate 1 instance of the list. So instead of:
block.fields.put(title, descriptions);

create a new list, e.g.:
block.fields.put(title, new ArrayList<>(descriptions));


Q: Make links have the same distance I am trying to make a simple website and I need some help.
I have this div

<?php require "./Pages/header.html"; ?>

And the header html:
Home
Shop Information
Products
Cart
Login
Contact

I want something like this:
Home       Shop Information             Products             Cart               Login                    Contact
where Home will be at the beggining of the div and Contact will be at the end of the div and all these links will have the same distance, but I dont want to use   spaces.

A: Make use of ul

Home

Shop Information

Products

Cart

Contact

CSS
 ul li
 {
     display:inline;
     padding:5px;
 }

Here is the Demo

A: There are a lot of options. You can use margin-right or padding.
JS-fiddle:
http://jsfiddle.net/7Uq9y/
Home
Shop Information
Products
Cart
Login
Contact

css:
a{
    margin-right: 50px;
}

A: Can you try using  tag

Home
Shop Information
Products
Cart
Login
Contact

CSS:
nav {
      display:block;
      margin-left:auto;
      margin-right:auto;
  }

A: CSS Using your existing html/php code :
div#header a {
    margin-right: 10px;
    width: 150px;
    display: inline-block;
}

A: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>Test Website</title>

Home

Shop Information

Products

Cart

Login

Contact


Q: Unknown column 'Username' in 'where clause' mysql_select_db($database_binary, $binary);
$query_account = sprintf("SELECT * FROM users WHERE Username = %s", GetSQLValueString($colname_account, "text"));
$account = mysql_query($query_account, $binary) or die(mysql_error());
$row_account = mysql_fetch_assoc($account);
$totalRows_account = mysql_num_rows($account);

$maxRows_trade = 20;
$pageNum_trade = 0;
if (isset($_GET['pageNum_trade'])) {
  $pageNum_trade = $_GET['pageNum_trade'];
}
$startRow_trade = $pageNum_trade * $maxRows_trade;

$colname_trade = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_trade = $_SESSION['MM_Username'];
}
mysql_select_db($database_binary, $binary);
$query_trade = sprintf("SELECT * FROM asset WHERE Username = %s", GetSQLValueString($colname_trade, "text"));
$query_limit_trade = sprintf("%s LIMIT %d, %d", $query_trade, $startRow_trade, $maxRows_trade);
$trade = mysql_query($query_limit_trade, $binary) or die(mysql_error());
$row_trade = mysql_fetch_assoc($trade);

if (isset($_GET['totalRows_trade'])) {
  $totalRows_trade = $_GET['totalRows_trade'];
} else {
  $all_trade = mysql_query($query_trade);
  $totalRows_trade = mysql_num_rows($all_trade);
}
$totalPages_trade = ceil($totalRows_trade/$maxRows_trade)-1;

$maxRows_withdrawreq = 10;
$pageNum_withdrawreq = 0;
if (isset($_GET['pageNum_withdrawreq'])) {
  $pageNum_withdrawreq = $_GET['pageNum_withdrawreq'];
}
$startRow_withdrawreq = $pageNum_withdrawreq * $maxRows_withdrawreq;

$colname_withdrawreq = "-1";
if (isset($_SESSION['Username'])) {
  $colname_withdrawreq = $_SESSION['Username'];
}
mysql_select_db($database_binary, $binary);
$query_withdrawreq = sprintf("SELECT * FROM withdrawal WHERE Username = %s", GetSQLValueString($colname_withdrawreq, "text"));
$query_limit_withdrawreq = sprintf("%s LIMIT %d, %d", $query_withdrawreq, $startRow_withdrawreq, $maxRows_withdrawreq);
$withdrawreq = mysql_query($query_limit_withdrawreq, $binary) or die(mysql_error());
$row_withdrawreq = mysql_fetch_assoc($withdrawreq);

I am getting an error:

Unknown column 'Username' in 'where clause'

How can I solve it?

A: The asset and withdrawal tables do not have a column called Username. So add that column to these tables or change WHERE condition in the sql statement related to these tables.These sql statements refer to the Username column in the WHERE clause that does not exist:
SELECT * FROM **asset** WHERE **Username**

SELECT * FROM **withdrawal** WHERE **Username**

New CREATE statements including Username column:
    CREATE TABLE asset ( Asset varchar(100) NOT NULL, optiontype varchar(200)
NOT NULL,
    Invested varchar(200) NOT NULL, Username varchar(100) NOT NULL,
    Entry Rate varchar(200) NOT NULL, Rate varchar(200) NOT NULL, Entry Time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Expiration Time varchar(200) NOT NULL, Status varchar(200) NOT NULL, Returns varchar(200) NOT NULL, Customer varchar(200) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8;

CREATE TABLE withdrawal ( id varchar(100) NOT NULL, Username varchar(100) NOT NULL,
Date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Customer varchar(200) NOT NULL, Amount varchar(100) NOT NULL, currency varchar(100) NOT NULL, email varchar(100) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8;


Q: Firebase storage upload stopped working on react-native I am using
"firebase": "^3.6.0",
"react": "15.3.2",
"react-native": "0.37.0",
"react-native-camera": "git+https://github.com/lwansbrough/react-native-camera.git",
"react-native-fetch-blob": "^0.10.0",
"react-native-vector-icons": "^3.0.0",
"react-native-video": "^0.9.0"

And i'm trying to upload a video recorded with react-native-video to firebase - this worked but suddenly it stopped working and now it doesn't succeed.
I'm using the following code where this.props.file.path looks something like this:
file:///storage/emulated/0/Pictures/vidid.mp4
  accept = () => {
    let rnfbURI = RNFetchBlob.wrap(this.props.file.path)
    Blob
    .build(rnfbURI, { type : 'video/mp4;'})
    .then((blob) => {
      // upload image using Firebase SDK
      firebase.storage()
        .ref()
        .child('testImageName')
        .put(blob, { contentType : 'video/mp4' })
        .then((snapshot) => {
          console.log(snapshot)
          blob.close()
          done()
        })
    })
}

I tried writing Firebase support, but then won't help me since this is a workaround.
My blob object looks like this:
 { listeners: {},
   isRNFetchBlobPolyfill: true,
   multipartBoundary: null,
   _ref: 'file:///storage/emulated/0/Pictures/VID_20161113_142100.mp4',
   _blobCreated: true,
   _closed: false,
   cacheName: 'blob-559cd5c4-e880-4742-a3fe-dfae7e1a0df0',
   type: 'video/mp4;',
   size: '3665375' }


Q: How to reuse objects between Automake program and tests targets? I have a non-recursive Makefile.am with something like the following:
SHARED_SRCS = src/bar.cpp src/baz.cpp

bin_PROGRAMS = foo

foo_SOURCES = src/main.cpp $(SHARED_SRCS)
foo_CXXFLAGS = -I$(srcdir)/src $(SOME_CFLAGS)
foo_LDADD = $(SOME_LIBS)

check_PROGRAMS = test1 test2 test3
TESTS = test1 test2 test3

test1_SOURCES = tests/test1.cpp $(SHARED_SRCS)
test2_SOURCES = tests/test2.cpp $(SHARED_SRCS)
test3_SOURCES = tests/test3.cpp $(SHARED_SRCS)
test1_CXXFLAGS = $(foo_CXXFLAGS)
test2_CXXFLAGS = $(foo_CXXFLAGS)
test3_CXXFLAGS = $(foo_CXXFLAGS)
test1_LDADD = $(foo_LDADD)
test2_LDADD = $(foo_LDADD)
test3_LDADD = $(foo_LDADD)

However, every target builds its own SHARED_SRCS, getting them built 4 times, even when sharing the same flags.
Is there a way to get them built without creating a convenience library, e.g. libbar.a or libtool's libbar.la?

A: No, there's not. The point is that you're not rebuilding the sources, you're rebuilding binaries.
What you can do is build an intermediate .o consisting only of the shared sources, and then use that in your tests, and binaries.


Q: How to move changes as uncommitted from one branch to another on Git I want to move all changes that are in a branch relative to master to another branch.
I don't want them as commits just as changes so that i can modify them and remove some of the changes and commit as one. I don't want to retain the old committed history.
I tried git format-patch master --stdout > mypatch.path
and git apply
but that applies as commits which i can't modify after that.

A: I would do this to move the changes from branch1 to branch2:
git checkout branch2

git merge --squash branch1

No commit has been created or "copied" between the branches. The changes can be modified before committing if need be.

A: If I understand what you want to do correctly, one way would be to start with your first branch:
git checkout branch1

Create a new branch from there:
git checkout -b branch2

Reset back to master, which will remove any commits that were made on branch1, but leave the changes as unstaged:
git reset master

You can then modify the files further and commit them as one commit.


Q: What is $\operatorname{Hom}(S,Q^\vee)$ for a Grassmannian? Let $G(k,V)$ be the Grassmannian of $k$-planes in a complex vector space $V$ of dimension $n$. There is the famous universal exact sequence of vector bundles on $G(k,V)$
$$
0 \to S \to V \otimes \mathcal O \to Q \to 0.
$$
Moreover, one can define the tangent bundle $T_{G(k,V)}=\operatorname{Hom}(S,Q)$.
Explicitly, what can we say about $\operatorname{Hom}(S,Q^\vee)$?


Q: Popup not working and no errors Popup.alert is not working using "ionic-framework: 2.0.0-alpha.42".
I am using "ionic-framework: 2.0.0-alpha.42" locally and "ionic@2.0.0-beta.15" globally in NPM.
Using this document as an example.
this.popup.alert({
    title: "New Friend!",
    template: "Your friend, Obi wan Kenobi, just accepted your friend request!",
    cssClass: 'my-alert'
}).then(() => {
    console.log('Alert closed');
});

That code is not working. I do not see a popup and i do not see "Alert closed" ever shown in the console. I pull in "popup" through the constructor.
private popup: Popup;
constructor(popup: Popup) {
    this.popup = popup;
}

A: I figured out the issue. You need to add
<ion-overlay></ion-overlay>
to your app.html. I saw that no where in the documentation.


Q: Is there any way to run a python script using the google API / Oauth function without needing to authenticate the account every time the script runs? Here is a quickpython  script that I wrote to upload a file to Google Drive:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
drive = GoogleDrive(gauth)

upload_file_list = [#placeholderfilename]
for upload_file in upload_file_list:
    gfile = drive.CreateFile({'parents': [{'id': '#placeholderdriveID'}]})
    # Read file and set it as the content of this instance.
    gfile.SetContentFile(upload_file)
    gfile.Upload() # Upload the file.

This script works, but every time it runs it also opens a window to authenticate the account accessing the drive. My goal for this script is to run it every morning with no input. Is there a way to set up the API so I don't need to manually authenticate the account every time I access google drive? Or does Google not allow that?


Q: is register_next_step_handler exist in aiogram? we have something like:
bot = telebot.TeleBot(TOKEN)

@bot.message_handler(commands=['start'])
def process_start(message):
    text = 'start'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_mid)

def process_mid(message):
    text = 'mid'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_end)

def process_end(message):
    text = 'end'
    bot.send_message(message.chat.id, text)

bot.polling(none_stop=True)

in pyTelegramBotAPI
this function is for when you ask user for like a number and after he/she sends num you process it in that special func that you mentioned

A: evgfilim1:
Hello. You need to use FSM, it's more flexible than register_next_step_handler.
Check the example: https://github.com/aiogram/aiogram/blob/dev-2.x/examples/finite_state_machine_example.py
The linked page won't break as the implementation is not going to change in aiogram 2.x.


Q: Spring MVC Test with Hamcrest: How compare a XML's node directly against a Java object I am working with:

*

*Spring MVC Test

*Hamcrest

For an item from a collection such as:
<collection>
    <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="persona">
        <id>087</id>
        <nombre>Leonardo</nombre>
        <apellido>Jordan</apellido>
        <fecha>1981-07-05</fecha>
    </item>
    ....

The following works:
.andExpect(xpath("collection/item[1]").exists())
.andExpect(xpath("collection/item[1]/*").nodeCount(is(4)))
.andExpect(xpath("collection/item[1]/id").exists())
.andExpect(xpath("collection/item[1]/id").string(is("087")))
.andExpect(xpath("collection/item[1]/id").string(is(personasArray[0].getId())))
.andExpect(xpath("collection/item[1]/nombre").exists())
.andExpect(xpath("collection/item[1]/nombre").string(is("Leonardo")))
.andExpect(xpath("collection/item[1]/nombre").string(is(personasArray[0].getNombre())))
.andExpect(xpath("collection/item[1]/apellido").exists())
.andExpect(xpath("collection/item[1]/apellido").string(is("Jordan")))
.andExpect(xpath("collection/item[1]/apellido").string(is(personasArray[0].getApellido())))

I want to know if is possible do a direct comparison against an object and not for each field, consider an entity with 15 to 45 fields.
I need something like this:
.andExpect(xpath("collection/item[1]/*").how(is(personasArray[0])))

See the how part, it represents what is the correct method to use.
Same consideration for the path's String content.

A: It is possible to do such an assertion. But you'll need to write your custom ResultMatcher for that. I don't think it is a good idea to convert XML (nodes) to Java objects just to do a simple comparison in a unit test.
You may run into problems with XML namespace resolution or the Java hashCode equals contract if not implemented right.
Instead, you should use libraries that lets you focus on your unit tests and not on the details of a technology or a programming language.
I recommend you to use XMLUnit in your test. XMLUnit is a Java library for XML comparison.
The example below depicts how easy it is to compare a XML document with XMLUnit and a custom ResultMatcher.
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xmlunit.builder.Input;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;

@RunWith(SpringRunner.class)
@WebMvcTest(XmlUnitDemoTests.XmlUnitDemo.class)
public class XmlUnitDemoTests {

    static final String XML_CONTENT = "<node1><node2 id=\"1\">text</node2></node1>";

    @Autowired
    MockMvc mockMvc;

    @Test
    public void xmlUnit() throws Exception {
        mockMvc.perform(get("/xml"))
            .andExpect(xml(XML_CONTENT));
    }

    static ResultMatcher xml(String bodyValue) {
        return MockMvcResultMatchers.content().source(equalXml(bodyValue));
    }

    static Matcher equalXml(String value) {
        return isSimilarTo(Input.fromString(value).build());
    }

    @SpringBootApplication
    @RestController
    static class XmlUnitDemo {

        @RequestMapping(value = "xml", produces = "text/xml")
        String xml() {
            return XML_CONTENT;
        }
    }

}

Of course, you may load big XML files from classpath or select a node with XPatch before doing a comparison. Take a look at the XMLUnit documentation for more information on that.


Q: How do I pass a subdirectory path to the GunDB S3 storage driver so the same S3 bucket can be shared with non-Gun data? I see examples referencing a few parameters for the S3 storage driver for GunDB that look like this:
var Gun = require('gun');
var gun = Gun({
    file: 'data.json',
    s3: {
            key: '', // AWS Access Key
            secret: '', // AWS Secret Token
            bucket: '' // The bucket you want to save into
    }
});

I don't see a parameter to define a subdirectory/path within the S3 bucket, to facilitate sharing the bucket with non-GunDB data. Is there such an option/parameter?

A: @hillct there is an option called prefix, thank you for pointing out that the options aren't documented. Here is how to use it:
var Gun = require('gun');
var gun = Gun({
    file: 'data.json',
    s3: {
            key: '', // AWS Access Key
            secret: '', // AWS Secret Token
            bucket: '', // The bucket you want to save into
            prefix: 'gun/'
    }
});

And just in case, here are some of the other options:
{
  throttle: 15 // Throttle writes to S3 in 15 second intervals, keeps S3 API costs down.
  batch: 10 // Or if there are more than 10 things in queue, don't wait.
}


Q: How to set values in a 2d numpy array given 1D indices for each row? In numpy you can set the indices of a 1d array to a value
import numpy as np

b = np.array([0, 0, 0, 0, 0])

indices = [1, 3]

b[indices] = 1
b

array([0, 1, 0, 1, 0])

I'm trying to do this with multi-rows and an index for each row in the most programmatically elegant and computationally efficient way possible. For example
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])

indices = [[1, 3], [0, 1], [0, 3]]

The desired result is
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])

I tried b[indices] and b[:,indices] but they resulted in an error or undesired result.
From searching, there are a few work arounds, but each tends to need at least 1 loop in python.
Solution 1: Run a loop through each row of the 2d array. The draw back for this is that the loop runs in python, and this part won't take advantage of numpy's c processing.
Solution 2: Use numpy put. The draw back is put works on a flattened version of the input array, so the indices need to be flattened too, and altered by the row size and number of rows, which would use a double for loop in python.
Solution 3: put_along_axis seems to only be able to set 1 value per row, so I would need to repeat this function for the number of values per row.
What would be the most computationally and programatically elegant solution? Anything where numpy would handle all the operations?

A: In [330]: b = np.zeros((3,5),int)
To set the (3,2) columns, the row indices need to be (3,1) shape (matching by broadcasting):
In [331]: indices = np.array([[1,3],[0,1],[0,3]])

In [332]: b[np.arange(3)[:,None], indices] = 1

In [333]: b
Out[333]:
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])

put along does the same thing:
In [335]: b = np.zeros((3,5),int)
In [337]: np.put_along_axis(b, indices,1,axis=1)

In [338]: b
Out[338]:
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])

A: On solution to build the indices in each dimension and then use a basic indexing:
from itertools import chain

b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])

# Find the indices along the axis 0
y = np.arange(len(indices)).repeat(np.fromiter(map(len, indices), dtype=np.int_))

# Flatten the list and convert it to an array
x = np.fromiter(chain.from_iterable(indices), dtype=np.int_)

# Finaly set the items
b[y, x] = 1

It works even for indices lists with variable-sized sub-lists like indices = [[1, 3], [0, 1], [0, 2, 3]]. If your indices list always contains the same number of items in each sub-list then you can use the (more efficient) following code:
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
indices = np.array(indices)
n, m = indices.shape
y = np.arange(n).repeat(m)
x = indices.ravel()
b[y, x] = 1

A: Simple one-liner based on Jérôme's answer (requires all items of indices to be equal-length):
>>> b[np.arange(np.size(indices)) // len(indices[0]), np.ravel(indices)] = 1
>>> b
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])


Q: How to set the active profile when creating Spring context programmatically? tl;dr: how to create a Spring context based on an annotation-based configuration class, while supplying active profiles?
I am trying to create a Spring context using a class with the configuration specified using annotations.
org.springframework.context.ApplicationContext context =
    new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );

However when it starts up it crashes because it cannot find a required bean, but that bean does exist : albeit only under a certain profile "myProfile".
How do I specify the active profile? I have a feeling I need to use one the org.springframework.context.annotation.AnnotationConfigApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory) constructor but I'm not sure which ones is appropriate.

PS- I am not using Spring Boot, but am on Spring 4.2.4.RELEASE.

A: If you want classpath:resources/application-${spring.profiles.active}.yml to be working, setting system properties before refreshing is the way to go.
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
applicationContext.scan("com.sample");
applicationContext.refresh();

A: This should do the trick...
final AnnotationConfigApplicationContext appContext =  new AnnotationConfigApplicationContext();
appContext.getEnvironment().setActiveProfiles( "myProfile" );
appContext.register( com.initech.ReleaserConfig.class );
appContext.refresh();


Q: Javascript variable & ajax ; with JsonForm. Using .jsonForm() with a variable I'm using JsonForm: https://github.com/joshfire/jsonform/wiki#wiki-getting-started
I'm trying to load a form schema into $('form').Jsonfrom(), from an external .txt file,
attempting this by loading it into my .html file with ajax, putting it in a javascript variable , then calling $('form').Jsonfrom() with a click event .
Here is my code:
<script>
#Load in .txt to javascript variable using ajax
var stringData = $.ajax({
                    url: "schema.txt",
                    async: false
                 }).responseText;

#check that file is loaded correctly .- have check this works.
#alert(stringData);

#on clicking of a piece of text in a <p> wrapper call jsonForm function.
$(document).ready(function(){
  $("p").click(function(){
       $('form').jsonForm(stringData   )
  });
});

</script>

the error I'm getting in firebug is:

"TypeError: this.formDesc.schema is undefined"

& my stack trace is this:
http://tinypic.com/r/2uiybo4/5
Think my problem may be in the way in loading in the .txt file with ajax.
however if I comment in: alert(stringData);  . . . the scheme for the for is displayed perfectly.
Like so: http://tinypic.com/r/2ynl9qh/5
Also there is no problem with the scheme, as i have tried putting it directly into in $('form').Jsonfrom("here") & it works fine.

A: Managed to solve this .
had to use a templating language (jinja2) instead of ajax, to get my form schema into my html document.. so that json form ( a jquery form builder) couple execute on a full html doc on the page loading .
Silly !
Hope this helps .


Q: Checking DB health in github actions Im running a container with mssql, and want to know if the DB is healthy after a set of second, cant figure out how to return the value of this step that has the docker inspect command in it

docker inspect --format={{.State.Health.Status}} test-db

so I can tell it in a next step, ex. the output == 'healthy' and if this is true then go forward with the steps onto build down the line..
I dont know the format and my head is starting to explode.
If anyone could help me understand how to do this?
EDIT:
I know im close:

EDIT:
solution was to use those damned single quotes or the $() docker inspect --format={{.State.Health.Status}} test-db

A: try surrounding the {{ with single quote like
docker inspect --format='{{.State.Health.Status}}' test-db

and executing in the if condition like:
if [[ $(docker inspect --format='{{.State.Health.Status}}' test-db) == "healthy"  ]]


Q: Get functions called with GDB I am using GDB to understand a C++ program. I put a break in the middle of the running which turns to be something like:
break main.cpp:500
and I would like to see which functions have been called before. I tried "backtrace" but it shows only info about main, as previous calls to previous functions have already finished.
My question is how can I get (with GDB or another method) the info about which functions have been called before this point, even if the call has been returned.
Thanks

A: A gdb script might be a solution for your problem.
Create a script that puts break point to each possibly called function.
At break prints the stack with 'bt' and continue the execution.
You should put an other break point to main.cpp:500 to quit from debugging.

b 'main.cpp::500'
commands 1
    detach
    quit
end

break 'A::f1()'
break 'A::f2()'
while true
continue
bt
end

You can start the script like this:

gdb --command ./gdbscript.gdb fpmanager

If you have too much possibly called function you can grep the code to find all.


Q: Label the midpoint of a segment in ggplot In the plot below I'd like to label the arrows with the text in bar$lbl. I'd like to do so in a way that would keep any labels from overlapping (they wouldn't in the simple example below). I'd prefer not to calculate the label position by hand.
I'm familiar with getting pretty, non-overlapping labels on points with ggrepel and curious if there is a similar way to label the midpoints of segments?
Any advice appreciated.
library(ggplot2)
foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
                  y1=c(0.1,0.9),y2=c(0.6,0.5),
                  lbl=c("Arrow 1", "Arrow 2"))
p1 <- ggplot(data=foo,aes(x=x,y=y))
p1 <- p1 + geom_point(color="grey")
p1 <- p1 + geom_segment(data=bar,aes(x=x1, xend=x2, y=y1, yend=y2),
                        size = 0.75,arrow = arrow(length = unit(0.5, "cm")))
p1

A: I know you would prefer not to calculate the mid points by hand, however, it is often easier to work with variables inside the aesthetics then with statistics, so I did it calculating the midpoints before hand and mapping to the axis
library(ggplot2)
library(directlabels) # provides a geom_dl that works easier with labels

foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
                  y1=c(0.1,0.9),y2=c(0.6,0.5),
                  midx = c(0.45, 0.1), # x mid points
                  midy = c(0.35, 0.7), # y midpoints
                  lbl=c("Arrow 1", "Arrow 2"))

p1 <- ggplot(data=foo,aes(x=x,y=y))
p1 <- p1 + geom_point(color="grey")
p1 <- p1 + geom_segment(data=bar,aes(x=x1, xend=x2, y=y1, yend=y2),
                        size = 0.75,arrow = arrow(length = unit(0.5, "cm")))
p1 + geom_dl(data = bar, aes(x = midx, y = midy, label = lbl),
             method = list(dl.trans(x = unit(x, 'cm'), y = unit(y, 'cm'))))

A: Here are two ways to do it with a lot of tidying. You don't need to do anything by hand if you think about the fact that the midpoint has coordinates that are just the means of x values and the means of y values of the 2 endpoints. First way is to tidy your data frame, calculate the midpoints, then make it wide again to have x and y columns. That data frame goes into ggplot, so it's passed through all the geoms, but we override with data arguments to geom_point and geom_segment. geom_segment gets just the original copy of the bar data frame.
library(tidyverse)
foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
                                    y1=c(0.1,0.9),y2=c(0.6,0.5),
                                    lbl=c("Arrow 1", "Arrow 2"))

bar %>%
    gather(key = coord, value = value, -lbl) %>%
    mutate(coord = str_sub(coord, 1, 1)) %>%
    group_by(lbl, coord) %>%
    summarise(value = mean(value)) %>%
    ungroup() %>%
    spread(key = coord, value = value) %>%
    ggplot() +
        geom_point(aes(x = x, y = y), data = foo, color = "grey") +
        geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = bar, size = 0.75, arrow = arrow(length = unit(0.5, "cm"))) +
        geom_text(aes(x = x, y = y, label = lbl))

But maybe you don't want to do all that piping at the beginning, or you have to do this several times, so you want a function to calculate the midpoints. For the second version, I wrote a function that does basically what was piped into ggplot in the first version. You supply it with the bare column name where your labels are kept, which is the column it will be grouped on. Then you can just use that in your geom_text.
## cool function!
tidy_midpt <- function(df, lbl_col) {
    lbl_quo <- enquo(lbl_col)

    df %>%
        gather(key = coord, value = value, -!!lbl_quo) %>%
        mutate(coord = str_sub(coord, 1, 1)) %>%
        group_by(lbl, coord) %>%
        summarise(value = mean(value)) %>%
        ungroup() %>%
        spread(key = coord, value = value)
}

ggplot(data = bar) +
    geom_point(aes(x = x, y = y), data = foo, color = "grey") +
    geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), size = 0.75, arrow = arrow(length = unit(0.5, "cm"))) +
    geom_text(aes(x = x, y = y, label = lbl), data = . %>% tidy_midpt(lbl))

Created on 2018-05-03 by the reprex package (v0.2.0).


Q: MongoDB findOneAndUpdate not updating So, I've been working with MongoDB for a couple days, I have been doing a per-server mute role command but when I was doing the set muterole command, when using findOneAndUpdate function, it doesn't seem to update the values, I've been searching for other answers and I've tried multiple of them, yet it doesn't seem to work, this is my code:
muteSchema.findOne(
                {
                    guildId: message.guild.id
                }, async (err, data) => {
                    if(err) console.log(err)
                    if(data)
                    {
                        muteSchema.findOneAndUpdate(
                            {
                                guildId: data.guildId
                            },
                            {
                                guildId: message.guild.id,
                                roleId: role.id
                            }
                        )
                    }
                    else
                    {
                        data = new muteSchema(
                            {
                                guildId: message.guild.id,
                                roleId: role.id
                            }
                        )

                        data.save().catch((err) => console.log(err) )
                    }
                }
            )

I do have the muteSchema import on top and this is my muteSchema file:
const mongoose = require("mongoose")

let MuteroleSchema = mongoose.Schema(
    {
        guildId: String,
        roleId: String
    },
    {
        strict: false
    }
)

module.exports = mongoose.model("muterole", MuteroleSchema)

The values are registered the first time it is used, but they don't update once they are there.

A: You are making things too complex for yourself. Why do you first find then again find and then update?
Simply go with the following flow
Update using filter

Code Sample:
exports.updateToken = async (id, forgotToken) => {//function
return User.updateOne({ _id: id }, { resetPasswordToken: forgotToken });//_id:id is a filter while the reset is code to update
}


Q: sound sequence on iphone - best practice? I'd like to make a sound sequencer on iPhone, almost like "dropphone" LINK
So I would need to

*

*play multiple samples (1~6seconds) at the same time

*keeping them synchronized with an NSTimer.

*being able to stop them / change the global volume

I've tried 2 approaches but I'm not that convinced :

*

*AVAudioPlayer
Downside: I get half a second lag when I want to play a sound

*AudioServices
Downside: I can't control/stop the sounds once they're launched
Is there another method to handle sounds that would be optimized to play overlapping sounds?


Q: Uncaught TypeError: Cannot read property 'tcp' of undefined in chrome extension I am trying to develop an extension in chrome which can snoop browser history and send it to a remote machine. I need to establish socket connection for transporting data.
But I am getting the above error. Read a lot of posts online which say there must be errors in the manifest file in context with socket permissions. Can anyone find out the error? Please check the code beneath.
Manifest File:
{
    "manifest_version": 2,
    "name": "Browser History Snooping",
    "description": "This extension snoops browser history and sends it to a remote machine",
    "version": "1.0",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "permissions": [
        "history"
    ],
    "sockets": {
        "tcp": {
            "connect": ""
        }
    }
}

JavaScript
var histories = [];
var visits = [];

chrome.history.search({
    text: '',
    maxResults: 0
}, function (historyItems) {
    var historiesProcessed = 0;
    for (var i = 0; i < historyItems.length; i++) {
        //histories.push(historyItems[i]);
        console.log(historyItems[i]);

        chrome.history.getVisits({
            url: historyItems[i].url
        }, function (visitItems) {
            for (var i = 0; i < visitItems.length; i++) {
                visits.push(visitItems[i]);
            }
            historiesProcessed++;
            if (historiesProcessed === historyItems.length) {
                console.log(visits.length + ' visits');
            }
        });
    }

    console.log(histories);
});

chrome.sockets.tcp.create({}, function (createInfo) {
    chrome.sockets.tcp.connect(createInfo.socketId, '127.0.0.1', 8888,
        function (result) {
            if (result >= 0) {
                console.log('Successfully connected');
            }
        });
});

A: The error is self-explanatory: chrome.sockets is undefined.
There's no sockets API in the extension documentation, but it is defined for the chrome apps.


Q: SAME70 read external interrupt polarity in ISR I'm currently working on a SAME70 board made by Atmel. I plugged on it an extention OLED1 board  (Atmel too) on EXT1 port. My goal is to recover the information about interrupt type (falling or raising) when I'm pressing the button 3 on OLED1 board. I have a function which allows me to set the different registers related to an interrupts. But unfortunately the register which indicates the polarity (FLHSR) stay always at 0 whatever the state of the button.
Below my code.
#include <asf.h>

void set_Interupt_Pin()
{
    uint32_t mask = 1 << 19;  /*bitmasking*/
    PIOA->PIO_IER = mask;    /*enable interruptions*/
    PIOA->PIO_AIMER = mask;  /*add new interruption*/
    PIOA->PIO_ESR = mask;     /*set interrupt source on edge*/
    PIOA->PIO_REHLSR = mask; /* set interrupt to rising edge*/
    PIOA->PIO_FELLSR= mask; /* set interrupt to falling edge*/
    NVIC_DisableIRQ(ID_PIOA);
    NVIC_ClearPendingIRQ(ID_PIOA);
    NVIC_EnableIRQ(ID_PIOA);   /*set NVIC to get interruptions from PIOA*/
    NVIC_SetPriority(ID_PIOA, 4); /*priority 4*/

}

void PIOA_Handler(void)
{
    printf("FRLHSR: %x\n",PIOA->PIO_FRLHSR); /*state of polarity event */
    printf("ISR: %x\n",PIOA->PIO_ISR);
    printf("ELSR: %x\n",PIOA->PIO_ELSR);
    printf("AIMMR: %x\n",PIOA->PIO_AIMMR);
}

int main(void)
{
    const usart_serial_options_t usart_serial_options = {
        .baudrate     = CONF_UART_BAUDRATE,
        .charlength   = CONF_UART_CHAR_LENGTH,
        .paritytype   = CONF_UART_PARITY,
        .stopbits     = CONF_UART_STOP_BITS
    };
    sysclk_init();
    board_init();
    stdio_serial_init(CONF_UART, &usart_serial_options);
    set_Interupt_Pin();
    while(1){}
}

You can see here the result of print when I press button (first part) and I release button (second part).

Best regards


Q: Write MDS business rules directly in SQL I'm using Master Data Services to check business rules in SQL. The use of MDS makes it easy for any (non-coder) to add business rules. However, I initially need to add a large amount of business rules and this is a very tedious procedure in MDS.
Is there a way to write the MDS business rules directly in code and add them to the MDS database?

A: There are quite a couple of stored procedures used for updating the MDS, but is is quite difficult to figure out how to use them. (And you can mess up the model if used incorrectly)
Easier would be to try the Business Rules Create method.
This is where you can get started with webservices:
http://sqlblog.com/blogs/mds_team/archive/2010/01/12/getting-started-with-the-web-services-api-in-sql-server-2008-r2-master-data-services.aspx
This is where the method is defined:
https://msdn.microsoft.com/en-us/library/microsoft.masterdataservices.services.servicecontracts.iservice.businessrulescreate(v=sql.120).aspx
You will need to weigh your options whether it would be faster to figure out how to do one of the above, or just knuckle down and create the business rules. MDS 2016 is much more user friendly than the previous versions when creating business rules(fyi)


Q: The ~ prefix in Objective C I've been learning core audio on the iPhone, and when looking through Apple's sample code I found this:
#include <AudioToolbox/AudioToolbox.h>

#include "CAStreamBasicDescription.h"
#include "CAXException.h"

#define kNumberBuffers 3

class AQPlayer
    {
    public:
        AQPlayer();
        ~AQPlayer();

        OSStatus                        StartQueue(BOOL inResume);
        OSStatus                        StopQueue();
        OSStatus                        PauseQueue();

        AudioQueueRef                   Queue()                 { return mQueue;}
        CAStreamBasicDescription        DataFormat() const      { return mDataFormat; }
        Boolean                         IsRunning() const       { return (mIsRunning) ? true : false; }
        Boolean                         IsInitialized() const   { return mIsInitialized; }
        CFStringRef                     GetFilePath() const     { return (mFilePath) ? mFilePath : CFSTR(""); }
        Boolean                         IsLooping() const       { return mIsLooping; }

        void SetLooping(Boolean inIsLooping)    { mIsLooping = inIsLooping; }
        void CreateQueueForFile(CFStringRef inFilePath);
        void DisposeQueue(Boolean inDisposeFile);

    private:
        UInt32                          GetNumPacketsToRead()               { return mNumPacketsToRead; }
        SInt64                          GetCurrentPacket()                  { return mCurrentPacket; }
        AudioFileID                     GetAudioFileID()                    { return mAudioFile; }
        void                            SetCurrentPacket(SInt64 inPacket)   { mCurrentPacket = inPacket; }

        void                            SetupNewQueue();

        AudioQueueRef                   mQueue;
        AudioQueueBufferRef             mBuffers[kNumberBuffers];
        AudioFileID                     mAudioFile;
        CFStringRef                     mFilePath;
        CAStreamBasicDescription        mDataFormat;
        Boolean                         mIsInitialized;
        UInt32                          mNumPacketsToRead;
        SInt64                          mCurrentPacket;
        UInt32                          mIsRunning;
        Boolean                         mIsDone;
        Boolean                         mIsLooping;

        static void isRunningProc(      void *              inUserData,
                                        AudioQueueRef           inAQ,
                                        AudioQueuePropertyID    inID);

        static void AQBufferCallback(   void *                  inUserData,
                                        AudioQueueRef           inAQ,
                                        AudioQueueBufferRef     inCompleteAQBuffer);

        void CalculateBytesForTime(     CAStreamBasicDescription & inDesc,
                                        UInt32 inMaxPacketSize,
                                        Float64 inSeconds,
                                        UInt32 *outBufferSize,
                                        UInt32 *outNumPackets);
    };

Does anyone know what this line does: ~AQPlayer();
I haven't seen the symbol ~ used before.

A: This is not a c related. It looks like c++ in which case the ~ is the desctructor for the class. You might want to read about destructors in the C++ FAQ

A: This is a C++ class, not an Objective-C class. The ~ symbol is used to declare or define a destructor method, a method that is automatically called when an instance's lifetime ends. The destructor method of a C++ class is used in the same way that a dealloc method is used in Objective-C classes (to clean up resources, and so on). The difference is that in Objective-C, dealloc is not invoked until it has no owners (i.e. all owners have relinquished their ownership by sending release).
If you wish to know what this code does, perhaps ask a C++ crowd, although, from a quick glance, it looks like an audio player utilising Apple's AudioToolbox framework.

A: That looks like C++ to me. It is supported on iOS, so that's why you’re seeing it.

A: That is c++ code, to develop with these from Objective-C you'd use Objective-C++.  Files with .mm are Obj-c++ and .m are just standard obj-c.

A: thats the destructor. in C++ the destructors are as this, while this code looks more like C++, in objective C you can write the destructor with "~"


Q: dragonruby-game-toolkit Excerpt from their website:
DragonRuby Game Toolkit is a professional grade (yet beginner-friendly) 2D game engine. It's tiny (~3MB), fast as hell, and cross-platform (including consoles).
So what's so great about DragonRuby Game Toolkit?

*

*Dirt simple APIs capable of creating complex 2D games.

*Fast as hell. Powered by highly-optimized C code written by Ryan C. Gordon, one of the core contributors of SDL (a library that powers every commercial game engine in the world).

*Battle-tested by Amir Rajan, a critically acclaimed indie game dev.
Tiny. Like really tiny. The entire engine is a few megabytes.
Hot loaded, realtime coding, optimized to provide constant feedback to the dev. Productive and an absolute joy to use.

*Turnkey builds for Windows, MacOS, and Linux with seamless publishing to Itch.io.

*Cross platform: PC, Mac, Linux, iOS, Android, Nintendo Switch, XBOX One, and PS4 (mobile and console compilation requires a business entity, NDA verification, and a Professional GTK License, contact us).


Q: Property of Maximal function Hardy littlewood Maximal function is defined for for a locally integrable function on $\mathbb{R}^n$ by $$Mf(x) =\sup \frac{1}{|Q|} \int_Q |f(y)|dy$$
where supremum is taken over all cubes Q in $\mathbb{R}^n$ containing x (Book "interpolation of operators"). The book says that it is easy to see that $$Mf(x) \geq c/|x|^n, ~ (|x| \geq 1).$$  I don't see how to see the fact. While searching online, I got one clue that there exists a cube Q such that $\int_Q |f|dy>0$. But still I can't see how to prove. May be i am missing some trivial thing. Please help to figure it out

A: Denote by $Q_a(x)$ the cube centered at $x$ with side $a$.
Assume, without loss of generality, that $f\geq0$. Suppose that $f$ is not zero a.e. Then there exists some cube $Q_r(x_0)$ with $c_0=\int_{Q_r(x_0)}f>0$. Any point in $Q_r(x_0)$ is at most at distance $s=\sqrt n\,(\|x_0\|+r)$ from the origin.
For any $|x|\geq1$ we have  $|sx|\geq s$, which implies $Q_r(x_0)\subset Q_{s\|x\|}(x)$. Then
$$
Mf(x)\geq\frac1{m(Q_{s\|x\|})}\,\int_{Q_{s\|x\|}(x)}f
\geq\frac1{m(Q_{s\|x\|})}\,\int_{Q_{r}(x_0)}f
\geq\frac {c_0}{m(Q_{s\|x\|})}=\frac{c_0/s^n}{\|x\|^n}.
$$


Q: How can I use a multiline footer in TCPDF? // Page footer
public function Footer() {
    // Position at 15 mm from bottom
    $this->SetY(-15);
    // Set font
    $this->SetFont('helvetica', 'I', 8);
    // Page number
    $this->Cell(0, 10, 'Seite '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}

Right now my footer looks like this:
]
But I need a more komplex footer with multiple lines:
]
How can I achieve this?
I tried to solve it with this stack overflow suggestion:
TCPDF Multiple Footers
But I had no success.

A: Try using MultiCell with some cell width combination, like this:
public function Footer() {
    // Make more space in footer for additional text
    $this->SetY(-25);

    $this->SetFont('helvetica', 'I', 8);

    // Page number
    $this->Cell(0, 10, 'Seite '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');

    // New line in footer
    $this->Ln(8);

    // First line of 3x "sometext"
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');

    // New line for next 3 elements
    $this->Ln(4);

    // Second line of 3x "sometext"
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');

    // and so on...
}

You can see more examples of how to use MultiCell function in TCPDF official examples: https://tcpdf.org/examples/example_005/


Q: Overriding parameterized methods in Scala Note: I apologise for altering this question, previously I wan't able to express the exact issue I am facing.
Let's say we have an abstract parameterized class abs,
abstract class abs[T] {
    def getA(): T
}

class ABS[Int] extends abs[T] {
    override def getA(): Int = 4
}

gives the following incomprehensible error:
<console>:28: error: type mismatch;
 found   : scala.Int(4)
 required: Int
       override def getA(): Int = 4
                              ^

I want to override the method getA.
Also an explanation or some helpful link would be really appreciated.

A: With the current base method signature this is impossible since generics are erased.
Take a type tag (I also renamed the method's T to U to prevent confusion because of shadowing):
abstract class abs[T] {
    def getA[U: TypeTag](): U
}

class ABS[T] extends abs[T] {
    override def getA[U]()(implicit tag: TypeTag[U]): U = {
        if (tag == typeTag[Int]) new Integer(1)
        else if (tag == typeTag[Char]) new Character('1')
        else throw new Exception("bad type")
    }.asInstanceOf[U]
}

A: Maybe you want something like this

 abstract class Abs[T] {
    def getA: T
    def getA(i: T): T
  }

class Absz extends Abs[Int]{
    override def getA = 4
    override def getA(i: Int) = i
  }

(new Absz()).getA                               //> res0: Int = 4
  (new Absz()).getA(3)                            //> res1: Int = 3

A: You can do it with Shapeless polymorphic functions: https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0
import shapeless._

object Abs extends Poly0{
  implicit def caseInt = at[Int](4)
  implicit def caseChar = at[Char]('4')
}

println(Abs.apply[Int])
println(Abs.apply[Char])


Q: In Javascript While loop repeats last number when counting from 1 to 5 when run on console When running following code on console:
var counter=0; while(counter<5){ console.log(counter); counter++; }
console o\p:
0
1
2
3
4
4
whereas for following code works fine, without repeating last value:
for(var i=0; i<5; i++){ console.log(i); }
console o\p:
0
1
2
3
4
Now, if I place above for loop after above mentioned while loop , output is perfectly fine:
var counter=0; while(counter<5){ console.log(counter); counter++; }
for(var i=0; i<5; i++){ console.log(i); }
console o\p:
0
1
2
3
4
0
1
2
3
4
whereas, if I place while loop after for loop , repetition of last number found.
for(var i=0; i<5; i++){ console.log(i); }
var counter=0;while(counter<5){ console.log(counter); counter++; }
console o\p:
0
1
2
3
4
0
1
2
3
4
4
Request all to provide a reason on this unexpected behavior of while loop.
Thanks.

A: When performing operations in the console, the return value of the last executed line is always output.
That means that simply writing
var counter = 0; ++counter;

will log 1 to the console.
The same is happening in your loop, the return value of the last counter++ is output to the console as the value of the last executed expression.

A: The output of the log method depends on the javascript engine of the browser. The last value printed is not output of the loop itself.
Try: var counter=0; while(counter<5){ console.log(counter++); }


Q: Are these numbers irrational and/or transcendental? I am curious to know if the following number is irrational or transcendental:
$$\displaystyle A = \sum_p 2^{-p},$$
where the sum is over all positive primes. A similar question can be asked for any number $k$ other than 2.
Edit: In retrospect and as pointed out by some comments below that it is trivial that $A$ is irrational. The transcendence question seems still relevant.
If we define a random number
$$\displaystyle b = \sum_n 2^{\rho(n)},$$
where $\rho(n)$ is a Bernoulli random variable defined to be $\rho(n) = -n$ with probability $1/\log n$ and $-\infty$ with probability $1 - 1/\log n$ (so that $2^{\rho(n)} = 0$), for say $n \geq 2$ and define $\rho(1) = -1$.
Can it be proved that say $n$ is transcendental with probability 1?

A: The number $A$ is irrational, since the characteristic function of the set of prime numbers is not eventually periodic.
It definitely should be transcendental as it is not a base $2$ normal number, ie the asymptotic frequency of digits is not the same (and algebraic numbers are conjectured to be normal). But this should be open (as also in the link mentioned by Theo Buhler, while I was composing this).
This conjecture would also answer the question on $b$, but Pietro Majer gave a direct argument already; it might however be good to keep this in mind for variations of the question.
Now, since the above is a bit terse some information around this. There is an interesting rather recent paper on more or less precisely this type of problem by Bailey, Borwein, Crandall, Pomerance
"On the binary expansions of algebraic numbers"
Among others they show that the binary distribution of a real algebraic number cannot be too extremely biased more precisely both digit have to occur (up to $N$) at least order of $N^{1/d}$ times where $d$ is the degree of the number. They also mention that thus the degree of
$$\sum_p \frac{1}{2^{p^k}}$$ is at least $k+1$ (with the convention that the degree of a transcendental is infinite).
There is more recent work on this by Adamczewski and Faverjon on this, too.
Finally, a good overview on this type of problem is given in this paper of Adamczewski and Bugeaud (see in particular Chapter 6 on lacunary numbers, that is precisley those of the form considered here, ie the digits are the characteristic function of some set).


Q: R convert nested values to new columns and rows With a dataframe like the following:
currencyDetails = c("Dollar:40, Euro:80, valid",
               "Yen:400, Pound:50",
               "Dollar:40, Pound:50, currency",
               NA)

Can someone recommend a method to append to that dataframe new columns and rows that correspond to the pairs and values in the each row please?  The number of pairs or values in each string is not fixed, and not ordered.
For sample output:
Dollar = c(40,NA,NA,NA)
Pound = c(NA,50,50,NA)
Euro = c(80,NA,NA,NA)
Yen = c(NA,400,NA,NA)
valid = c(1,0,0,0)
currency = c(0,0,1,0)
df = data.frame(Dollar, Pound, Euro,Yen,valid, currency)
cbind(currencyDetails, df)

                currencyDetails Dollar Pound Euro Yen valid currency
1     Dollar:40, Euro:80, valid     40    NA   80  NA     1        0
2             Yen:400, Pound:50     NA    50   NA 400     0        0
3 Dollar:40, Pound:50, currency     NA    50   NA  NA     0        1
4                          <NA>     NA    NA   NA  NA     0        0

I think it's different to the supplied previous answers as there's the extra complexity of splitting out the key:value pair, it's not that each element is turned into a column name as is.  For example, Pound:50 is not the column, Pound is, with 50 as it's value.

A: Try this solution:
splitted<-trimws(unlist(strsplit(aDataFrame,",")))

t(bind_rows(sapply(splitted[grep(":",splitted)],strsplit,split=":")))
          [,1]     [,2]
Dollar:40 "Dollar" "40"
Euro:80   "Euro"   "80"
Yen:400   "Yen"    "400"
Pound:50  "Pound"  "50"

Update
df<-data.frame(t(bind_rows(sapply(splitted[grep(":",splitted)],strsplit,split=":"))))
> library(reshape2)
> acast(df, X2 ~ X1)
Using X2 as value column: use value.var to override.
    Dollar Euro Pound Yen
40  40     <NA> <NA>  <NA>
400 <NA>   <NA> <NA>  400
50  <NA>   <NA> 50    <NA>
80  <NA>   80   <NA>  <NA>
Levels: 40 400 50 80


Q: Проблема в чрезмерном размере корневого каталога lib Недавно начало выдавать предупреждение, что в корневом каталоге не хватает место. Выделено 16 гб, большинство места жрёт папка lib. Что из неё можно удалить "ненужное" и как жт


Q: Dynamic Custom Permalinks I have a scenario in which the intention is to make custom permalink that can be changed dynamically, for example:

*

*If a country information is showing up then the URL should be http://example.com/country-information

*If the city information of that specific country is showing up then the URL should be like http://example.com/country/city-information.
How can I achieve that?

A: It depends on what you mean by "changed dynamically", but the simplest way to achieve what you're talking about is to use pages (or a hierarchical custom post type), and make the "city-information" pages into children of the "country-information" page they are associated with. Then set permalinks to "Post Name", and you'll get the urls you're looking for.

A: Did you try add_rewrite_rule()? For example:
add_action( 'init',  function() {
    add_rewrite_rule( 'country-information/([a-z0-9-]+)[/]?$', 'index.php?country-information=$matches[1]', 'top' );
} );

After adding the new rule, you have to flush the permalink, Admin > Permalinks > Save
Then add a new query var via add_filter, needed to allow custom rewrite rules using your own arguments to work, or any other custom query variables you want to be publicly available.
add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'country-information';
    return $query_vars;
} );

You can also use a custom particular template for that permalink using template_include hook.
function conutry_information_template( $template ) {
    if ( get_query_var( 'country-information' ) === false || get_query_var( 'country-information' ) == '' ) {
        return $template;
    }

    return get_template_directory() . '/country-information.php';
}
add_action( 'template_include', 'conutry_information_template' );


Q: How can I evaluate a math equation, one per line in a file? I have a file with the following:
37 * 60 + 55.52
34 * 60 + 51.75
36 * 60 + 2.88
36 * 60 + 14.94
36 * 60 + 18.82
36 * 60 + 8.37
37 * 60 + 48.71
36 * 60 + 34.17
37 * 60 + 42.52
37 * 60 + 51.55
35 * 60 + 34.76
34 * 60 + 18.90
33 * 60 + 49.63
34 * 60 + 37.73
36 * 60 + 4.49

I need to write a shell command or Bash script that, for each line in this file, evaluates the equation and prints the result. For example, for line one I expect to see 2275.52 printed. Each result should print once per line.
I've tried cat math.txt | xargs -n1 expr, but this doesn't work. It also seems like awk might be able to do this, but I'm unfamiliar with that command's syntax, so I don't know what it would be.

A: here is what I whould do not sure it is the best method
bc < toto

depending what you want to do with datas
francois@zaphod:~$ cat > toto
37 * 60 + 55.52
34 * 60 + 51.75
36 * 60 + 2.88
36 * 60 + 14.94
36 * 60 + 18.82
36 * 60 + 8.37
37 * 60 + 48.71
36 * 60 + 34.17
37 * 60 + 42.52
37 * 60 + 51.55
35 * 60 + 34.76
34 * 60 + 18.90
33 * 60 + 49.63
34 * 60 + 37.73
36 * 60 + 4.49
francois@zaphod:~$ while read ; do echo " $REPLY" | bc  ; done < toto
2275.52
2091.75
2162.88
2174.94
2178.82
2168.37
2268.71
2194.17
2262.52
2271.55
2134.76
2058.90
2029.63
2077.73
2164.49
francois@zaphod:~$

without BC command you cannot use decimal values :
francois@zaphod:~$ while read ; do echo $(( "REPLY" )) ; done < toto
-bash: 37 * 60 + 55.52: syntax error: invalid arithmetic operator (error token is ".52")
francois@zaphod:~$

A: If you have perl:
perl -ne 'print eval $_,"\n"' math.txt

(I get 50000 lines per second on my laptop using this).

A: With old-good Python:
$ python -c $'import sys;\nfor line in sys.stdin:print(eval(line))' <math.txt
2275.52
2091.75
2162.88
2174.94
2178.82
2168.37
2268.71
2194.17
2262.52
2271.55
2134.76
2058.9
2029.63
2077.73
2164.49

A: directly in bash/ksh (Edit: As it turns out, bash can't do this, only ksh - thanks for pointing this out):
$ while read l
> do
> echo $(($l))
> done <<!
> 37 * 60 + 55.52
> 34 * 60 + 51.75
> 36 * 60 + 2.88
> 36 * 60 + 14.94
> 36 * 60 + 18.82
> 36 * 60 + 8.37
> 37 * 60 + 48.71
> 36 * 60 + 34.17
> 37 * 60 + 42.52
> 37 * 60 + 51.55
> 35 * 60 + 34.76
> 34 * 60 + 18.90
> 33 * 60 + 49.63
> 34 * 60 + 37.73
> 36 * 60 + 4.49
> !
2275.52
2091.75
2162.88
2174.94
2178.82
2168.37
2268.71
2194.17
2262.52
2271.55
2134.76
2058.9
2029.63
2077.73
2164.49

This may require a fairly recent version of your shell - $((...)) used to only do integer arithmetics.

A: If you only need the results, I'd got with the answer provided by @francois-p
For fun and games, add paste and sed:
$ paste <(sed 's/\($\)/\1\t=/g' somefile) <(bc < somefile)
37 * 60 + 55.52 =   2275.52
34 * 60 + 51.75 =   2091.75
36 * 60 + 2.88  =   2162.88
36 * 60 + 14.94 =   2174.94
36 * 60 + 18.82 =   2178.82
36 * 60 + 8.37  =   2168.37
37 * 60 + 48.71 =   2268.71
36 * 60 + 34.17 =   2194.17
37 * 60 + 42.52 =   2262.52
37 * 60 + 51.55 =   2271.55
35 * 60 + 34.76 =   2134.76
34 * 60 + 18.90 =   2058.90
33 * 60 + 49.63 =   2029.63
34 * 60 + 37.73 =   2077.73
36 * 60 + 4.49  =   2164.49

A: With Perl:
perl -ple '$_=eval' ex
perl -nE 'say eval' ex

with Python:
python3 -qi < ex
python3 -qic 'import sys; sys.ps1=""' < ex

With Haskell:
ghci < ex
ghci < ex | grep -Po '> \S+$'

With calc:
calc -f ex      # apt install apcalc if necessary

A: Using awk/python:
python -c "$(awk '{printf "print %s;", $0}' math.txt)"

awk is being used here to format your file into an input that python will accept, then python is doing the work.
Alternatively perl can be used in pretty much the same way:
perl -le "$(awk '{printf "print %s;", $0}' math.txt)"

A: Directly with awk:
awk '{ printf "%f\n", $0 }' math.txt

The $0 represents the entire line that is read line by line from the file.
Additionally, it is not susceptible to nasty injections. It will only evaluate a line as a floating point number.

A: This awk seems to do the trick:
while IFS= read i; do
  awk "BEGIN { print ($i) }"
done < math.txt

From here
Note that we're using ($i) instead of $i to avoid problems with arithmetic expressions like 1 > 2 (print 1 > 2 would print 1 into a file called 2, while print (1 > 2) prints 0, the result of that arithmetic expression).
Note that since the expansion of the $i shell variable ends up being interpreted as code by awk, that's essentially a code injection vulnerability. If you can't guarantee the file only contains valid arithmetic expressions, you'd want to put some input validation in place. For instance, if the file had a system("rm -rf ~") line, that could have dramatic consequences.

A: Just feed the mess to bc -l, it will return one line result for each line of expression.
(The -l loads the math library, it also sets scale to a higher value and so gives fractional results.)


Q: Dell Soundbar scratchy sound after some time on Ubuntu 18.04 I've installed Ubuntu 18.04
Sound presents. Still on my Dell AC511 USB Soundbar is scratchy from time to time.
How to reproduce:

*

*make active Dell AC511 (Digital or Analog doesn't matter) active
device for output in Settings=>Sound

*start playing sound (tried with Rhythmbox and Youtube inside
browser)

*sound is playing nice for about 30 seconds, after that it becomes
scratchy and much more loud. After some time (about 15 seconds) it
becomes again normal, after that again scratchy and repeat again.
Switch time is not constant, it changes.

*if I Digital Output was selected and sound became scratchy then
switching to analog output helps for about 30 seconds and circle
starts again

It looks like the problem is with the output volume - when sound becomes loud and scratchy I can decrease volume in sound settings and that helps, but in several seconds it becomes silent so I need to increase it. If don't change the sound level then after been silent it will be restored and after that again silent in circle.
On Xonar DS which is installed on the same machine with headphones plugged in there is no such effect and sound is perfect. Haven't try built-in audio.
please help
Thank you in advance

A: Check the connection between the soundbar and device
Check for damaged the wiring, (damage may be internal so if you have a spare cable then test it out and see if the spare works)


Q: Finding objects between two dates Okay so I have a parse database with two keys (startedAt) and (endedAt) basically I would like to return all the objects between these two given times. However, I store the times as strings, not dates. I would really like to not have to change them to dates as that would force me to rework code in a lot of other parts of my program. So is it possible to do the following
    NSDate *leftDate = leftClassRoomAfterDatePicker.date;
    NSDate *arrivedDate = arrivedBeforeDatePicker.date;

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM-dd hh:mm"];

    NSString *leftDateString = [dateFormat stringFromDate:leftDate];
    NSString *arrivedDateString = [dateFormat stringFromDate:arrivedDate];

    NSLog(leftDateString);
    NSLog(arrivedDateString);

    PFQuery *query = [PFQuery queryWithClassName:@"PassData"];
    [query whereKey:@"startTime" greaterThan:leftDate];
    [query whereKey:@"timeArrived" lessThan:arrivedDate];

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       NSLog(@"Successfully retrieved %d objects.", objects.count);
    }];

When I run this code I get the following error
The problem is that the strings are not returning the correct value. In my parse database I have a value of startTime:    Dec 08, 18:28
and             endTime:      Dec 08, 18:28
But it still does not work (no objects are returned). I think this is because the greaterthan/lessthan functions will not work on strings like this.

A:
Error: startTime contains string values but got a date (Code: 102,
  Version: 1.2.21)

The error clearly indicates that you are comparing two different objects one is string and second one is date. So there are two things you can either convert any one into date or string. So to implement the same in a easy way, you can write one category with function which will convert either into date or string and use that method to perform the comparison.

A: You've converted leftDate and arrivedDate to leftDateString and arrivedDateString, but you're still using leftDate and arrivedDate in your query. I think you meant to write:
PFQuery *query = [PFQuery queryWithClassName:@"PassData"];
[query whereKey:@"startTime" greaterThan:leftDateString];
[query whereKey:@"timeArrived" lessThan:arrivedDateString];

in which case you'd no longer get the error since you'd be comparing string to string.
Although I generally recommend that you store and sort your dates with NSDate objects, in this case where your format is in the same descending order of importance as a typical NSDate sort of month, day, hour, then minute, i.e. "MM-dd hh:mm", as long as year or seconds don't matter to you and as long as the queried time format matches the database time format, this query should work since greaterThan and lessThan will compare the string objects alphabetically/numerically.

A: I guess for that to work you have to have Date fields in database, then you pass NSDate to whereKey: on iOS.


Q: Set max time a user can be logged in, regardless of their activity I'm working on a blue green pattern for a system with continuous delivery. I would like to force the users to switch server after 30 min. I'm developing my application in JSF 2. Is there an easy way to make the sessions end after a certain time no matter if the user is active or not?

A: Implement a filter which does basically the following job:
HttpSession session = request.getSession();

if (session.isNew()) {
    session.setAttribute("start", System.currentTimeMillis());
}
else {
    long start = (Long) session.getAttribute("start");

    if (System.currentTimeMillis() - start > (30 * 60 * 1000)) {
        session.invalidate();
        response.sendRedirect("expired.xhtml");
        return;
    }
}

chain.doFilter(request, response);

Map this on the servlet name or URL pattern of interest.
This is only sensitive to changes in system clock, make sure that your server runs UTC all the time. Otherwise better grab System#nanoTime() instead.


Q: Optimizing a set 20 webrequests with threads This is for ASP.NET. I want to improve the time it takes run my function, today it takes around 20-30 seconds, more towards 30secs than 20secs though. That's running on one thread making 20 webrequests.
I'm thinking threads that do all the 20 webreqeusts, in order to quickly find the result or just go through the data (IE do all the 20 requests not finding anything).

Here's how it works.
1. I'm using html agility pack to fetch htmldocuments. 2. Then I parse them for information 3. Lastly I add that information to a dictionary OR I move on to the next webrequest until I reach 20 requests made.
I make at most 20 webRequests, at minimum 1. I have set the function to end when the info I'm searching for is found. Sometimes the info isn't there hence the 20 webrequests(it goes through all the data).
Every webrequest adds between 5-20 entries to the dictionary. This is then compared with the information I sent to it, if it's in the list I get the Key back, otherwise it returns 201. If found it gets added to the database.
QUESTIONS
*A:*If I want to do this with threads, how many should I create? 20 One for each request and let them all loose to do the job? Or should i create like 4 of them making at most 5 requests each?B: What if two threads are finished at the same time and wants to add info to the directory, can it lock the whole site(I'm using ASP.NET), or will it try to add one from thread A and then one result from Thread B? I have a check already today that checks if the key exists before adding it.
C:What would be the fastest way to this?
This is my code, depicting the loop which just shows that 20 requests are being made?
public void FetchAndParseAllPages()
    {

        int _maxSearchDepth = 200;
        int _searchIncrement = 10;

        PageFetcher fetcher = new PageFetcher();
        for (int i = 0; i < _maxSearchDepth; i += _searchIncrement)
        {
            string keywordNsearch = _keyword + i;
            ParseHtmldocuments(fetcher.GetWebpage(keywordNsearch));

            if (GetPostion() != 201)
            {   //ADD DATA TO DATABASE
                InsertRankingData(DocParser.GetSearchResults(), _theSearchedKeyword);
                return;
            }
        }
    }

A: *

*.NET allows only 2 requests open at the same time. If you want more than that, you need to configure it in web.config. Look here: http://msdn.microsoft.com/en-us/library/aa480507.aspx

*You can the Parallel.For method which is very straightforward and handles the "how much threads" for you. Of course you can tweak it to set how much threads (or tasks) you want with ParallelOptions. Look here: http://msdn.microsoft.com/en-us/library/dd781401.aspx

*For making a thread-safe dictionary you can use the ConcurrentDictionary. Look here: http://msdn.microsoft.com/en-us/library/dd287191.aspx


Q: Extract a complex String from between two Strings I have a String which contains the following sub string:
[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]
I'd like to extract the part between [Text: and ] i.e. PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1.
How do I do this?

A: Pattern p = Pattern.compile("\\[Text:(.*?)\\]");
Matcher m = p.matcher("[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]");
m.find();
System.out.println(m.group(1));

Gives:
PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1

The \\[ and \\] are to escape the brackets, which are special characters in regexes. The .*? is a non-greedy quantifier, so it stops gobbling up characters when it reaches the closing bracket. This part of the regex is given inside a capturing group (), which you can access with m.group(1).

A: Use the following string as the regex:
"\\[Text:(.*?)\\]"

The first capture group will give you exactly the substring you want.
The non-greedy match (.*?) is required to make it stop at the first ] rather than also including [Elem:123].

A: String.substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.
You could use this to remove the start and end of the string,
or....
You could use
String.indexOf(String str)

To get the index of the start and end of the match and copy the contents to a new result string.
You could use
String.matches(String regex)

However writing regular expressions can get difficult,
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
I hope this helps.

A: Instead of using "\\[Text:(.*?)\\]", as others have suggested, I'd go one step further and use lookarounds to filter out the text you don't want:
(?<=\\[Text:).*?(?=\\])
This will match exactly the text you want without having to select a capturing group.


Q: How to design an installer so it can be used in automated acceptance tests Background:
We have a windows installer which simply installs and starts our custom WinForms installation program. This custom installer does the real installation: creating an IIS Web Application, copying dlls, installing database, etc...
We now want to write some automated acceptance tests, which will include installing the software using the same installation procedure as we use in production. We want to start by running the acceptance tests every night on a dedicated machine, and later as part of a continuous integration pipeline.
Problem:
It is proving difficult to automate the WinForms installation program. And we do not want special installation code for the acceptance tests.
Question:
What advice do you clever people have for integrating the deployment process into an automated test?
I suspect that the decision to use WinForms for the installer was a bad choice - particularly because the resulting application does not clearly separate the UI code from the real installation code.

A: My recommendation would be to use an MSI based installer instead of trying to roll your own using Windows Forms.  Look into using the Windows Installer XML (WiX) toolset which is a popular free open source toolset for creating installers.
Using MSI has many advantages, in particular it makes it fairly difficult to mix installer logic and UI (kind of like falling into the pit of success) and so making an unattended installer suitable for running on a remote machine is a piece of cake.
If you are already committed to your current installation method then you need to work on separating your UI and logic to the point where you can run an installation without showing any UI - its difficult to give any specific advice on how to do this without a more concrete example.