text:
Q: Re-size a rotated rectangle using mouse drag in c# It will seems to most of the guys here that it's a repeated question but it isn't.
I am having a very hard problem. I have a rectangle which can be re-sized when it's not rotated and all work fine. But when it's rotated the algorithm is not working. The code is below:
internal void resizeToPoint(int tmpX, int tmpY, Rectangle limits)
{
    Matrix m = new Matrix();
    m.Reset();

    m.Translate(mLayoutRectangle.X + mParent.getAbsXOffset(DEPTH_LEVEL.APA) + mLayoutRectangle.Width / 2, mLayoutRectangle.Y + mParent.getAbsYOffset(DEPTH_LEVEL.APA) + mLayoutRectangle.Height / 2);
    m.Rotate(-(int)mAngle);
    m.Translate(-(mLayoutRectangle.X + mParent.getAbsXOffset(DEPTH_LEVEL.APA) + mLayoutRectangle.Width / 2), -(mLayoutRectangle.Y + mParent.getAbsYOffset(DEPTH_LEVEL.APA) + mLayoutRectangle.Height / 2));

    Point pPrime = new Point();
    pPrime.X = (int)((m.Elements[0] * tmpX + m.Elements[2] * tmpY) + (int)m.Elements[4]);
    pPrime.Y = (int)((m.Elements[1] * tmpX + m.Elements[3] * tmpY) + (int)m.Elements[5]);

    Point BottomRight = new Point(mLayoutRectangle.Width + getAbsXOffset(), mLayoutRectangle.Height + getAbsYOffset());
    Point TopRight = new Point(mLayoutRectangle.Width + getAbsXOffset(), getAbsYOffset());
    Point TopLeft = new Point(getAbsXOffset(), getAbsYOffset());
    Point BottomLeft = new Point(getAbsXOffset(), mLayoutRectangle.Height + getAbsYOffset());

    Point TopMiddle = new Point((mLayoutRectangle.Width / 2) + getAbsXOffset(), getAbsYOffset());
    Point RightMiddle = new Point(mLayoutRectangle.Width + getAbsXOffset(), mLayoutRectangle.Height / 2 + getAbsYOffset());
    Point BottomMiddle = new Point(getAbsXOffset() + mLayoutRectangle.Width / 2, mLayoutRectangle.Height + getAbsYOffset());
    Point LeftMiddle = new Point(getAbsXOffset(), getAbsYOffset() + mLayoutRectangle.Width / 2);

    Rectangle newLocationRectangle = mLayoutRectangle;
    Double widthRatioHeight = 1;

    if (this is ImageDesignElement)
    {
        widthRatioHeight = (double)((ImageDesignElement)this).getMonochromeImage().Width / (double)((ImageDesignElement)this).getMonochromeImage().Height;
        //widthRatioHeight = (double)mLayoutRectangle.Width / (double)mLayoutRectangle.Height;
    }

    int rectangleOldWidth = newLocationRectangle.Width;
    int rectangleOldHeight = newLocationRectangle.Height;
    int rectangleOldX = newLocationRectangle.X;
    int rectangleOldY = newLocationRectangle.Y;

    switch (mSelectedHandleForScaling)
    {
        case HANDLE_TYPE.TOP_LEFT:
            if (newLocationRectangle.Height - (pPrime.Y - TopLeft.Y) > 0)
            {
                newLocationRectangle.Height -= (pPrime.Y - TopLeft.Y);
                newLocationRectangle.Y += (pPrime.Y - TopLeft.Y);
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            if (newLocationRectangle.Width - (pPrime.X - TopLeft.X) > 0)
            {
                newLocationRectangle.Width -= (pPrime.X - TopLeft.X);
                newLocationRectangle.X += (pPrime.X - TopLeft.X);
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            break;

        case HANDLE_TYPE.TOP_MIDDLE:
            if (newLocationRectangle.Height - (pPrime.Y - TopMiddle.Y) > 0)
            {
                newLocationRectangle.Height -= (pPrime.Y - TopMiddle.Y);
                newLocationRectangle.Y += (pPrime.Y - TopMiddle.Y);
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            break;

        case HANDLE_TYPE.TOP_RIGHT:
            if (newLocationRectangle.Height - (pPrime.Y - TopRight.Y) > 0)
            {
                newLocationRectangle.Height -= (pPrime.Y - TopRight.Y);
                newLocationRectangle.Y += (pPrime.Y - TopRight.Y);
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            if (newLocationRectangle.Width + pPrime.X - TopRight.X > 0)
            {
                newLocationRectangle.Width += pPrime.X - TopRight.X;
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            break;

        case HANDLE_TYPE.RIGHT_MIDDLE:

            if (newLocationRectangle.Width + pPrime.X - RightMiddle.X > 0)
            {
                newLocationRectangle.Width += pPrime.X - RightMiddle.X;
            }
            mInitialScalePoint.X = pPrime.X;
            mInitialScalePoint.Y = pPrime.Y;
            break;

        case HANDLE_TYPE.BOTTOM_RIGHT:
            if (newLocationRectangle.Height + pPrime.Y - BottomRight.Y > 0)
            {
                newLocationRectangle.Height += pPrime.Y - BottomRight.Y;
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            if (newLocationRectangle.Width + pPrime.X - BottomRight.X > 0)
            {
                newLocationRectangle.Width += pPrime.X - BottomRight.X;
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }

            break;

        case HANDLE_TYPE.BOTTOM_MIDDLE:
            if (newLocationRectangle.Height + pPrime.Y - BottomMiddle.Y > 0)
            {
                newLocationRectangle.Height += pPrime.Y - BottomMiddle.Y;
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            break;

        case HANDLE_TYPE.BOTTOM_LEFT:
            if (newLocationRectangle.Height + pPrime.Y - BottomLeft.Y > 0)
            {
                newLocationRectangle.Height += pPrime.Y - BottomLeft.Y;
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            if (newLocationRectangle.Width - (pPrime.X - BottomLeft.X) > 0)
            {
                newLocationRectangle.Width -= (pPrime.X - BottomLeft.X);
                newLocationRectangle.X += (pPrime.X - BottomLeft.X);
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            break;

        case HANDLE_TYPE.LEFT_MIDDLE:
            if (newLocationRectangle.Width - (pPrime.X - BottomLeft.X) > 0)
            {
                newLocationRectangle.Width -= (pPrime.X - BottomLeft.X);
                newLocationRectangle.X += (pPrime.X - BottomLeft.X);
                mInitialScalePoint.X = pPrime.X;
                mInitialScalePoint.Y = pPrime.Y;
            }
            break;
    }

    if (((Control.ModifierKeys & Keys.Shift) != Keys.Shift) && this is ImageDesignElement)
    {

        int hightChange = newLocationRectangle.Height - rectangleOldHeight;
        int widthChange = newLocationRectangle.Width - rectangleOldWidth;

        newLocationRectangle.Width = rectangleOldWidth;//reset to the old Width before the call of this method
        newLocationRectangle.Width += (int)(((double)hightChange) * widthRatioHeight); //use the difference is width to adjust Width

        if (mSelectedHandleForScaling == HANDLE_TYPE.TOP_LEFT || mSelectedHandleForScaling == HANDLE_TYPE.BOTTOM_LEFT)
        {
            newLocationRectangle.X = rectangleOldX + (rectangleOldWidth - newLocationRectangle.Width);
        }

    }

    if (this is ImageDesignElement)
    {
        mLayoutRectangle = newLocationRectangle;
        //Console.WriteLine("* mLayoutRectangle.Width =" + mLayoutRectangle.Width + " mLayoutRectangle.Height =" + mLayoutRectangle.Height);

    }
    else
    {
        mLayoutRectangle = newLocationRectangle;
    }
}

Now, here we have a mLayoutRectangle a rectangle object in which some corners can be dragged with new position tmpX and tmpY through mouse. mAngle is the angle in degree rotated.
The problem is when angle is between 0 and 80 it works fine but when the angle is greater than this its behavior is changed totally. I don't get what I am doing wrong here.
I have used the following rectangle datatype: Rectangle Structure from MSDN. I want to set the left, right, top and bottom values for this rectangle. Can i somehow extend it, so that i can set values for left, right, top and bottom???
The problem is well explained here: but i have to do that in window form not WPF.
Exact explanation of the problem

A: 1: Add a blank Windows Form
2: Add Mouse handlers for Paint, MouseDown, MouseUp, MouseMove
3: Add AnchorPoint.cs:
public enum AnchorPoint
{
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
    Rotation,
    Center
}

4: add MatrixExtension.cs
public static class MatrixExtension
{
    public static PointF TransformPoint(this Matrix @this, PointF point)
    {
        var points = new[] { point };

        @this.TransformPoints(points);

        return points[0];
    }
}

5: Edit Form1.cs:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private bool _drag;

        private SizeF _dragSize;
        private PointF _dragStart;
        private PointF _dragStartOffset;
        private RectangleF _dragRect;
        private AnchorPoint _dragAnchor;
        private Single _dragRot;

        private RectangleF _rect;
        private PointF _rectPos;
        private Single _rectRotation;

        public Form1()
        {
            InitializeComponent();

            //Center location of our item
            _rectPos = new PointF(200, 200);

            //The rectangle dimensions in _rectPos space
            _rect = new RectangleF(-40, -30, 80, 60);

            _rectRotation = 0;
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            var gc = e.Graphics;

            // Move Graphics handler to Rectangle's space
            var mat = new Matrix();
            mat.Translate(_rectPos.X, _rectPos.Y);
            mat.Rotate(_rectRotation);
            gc.Transform = mat;

            // All out gizmo rectangles are defined in Rectangle Space
            var rectTopLeft = new RectangleF(_rect.Left - 5f, _rect.Top - 5f, 10f, 10f);
            var rectTopRight = new RectangleF(_rect.Left + _rect.Width - 5f, _rect.Top - 5f, 10f, 10f);
            var rectBottomLeft = new RectangleF(_rect.Left - 5f, _rect.Top + _rect.Height - 5f, 10f, 10f);
            var rectBottomRight = new RectangleF(_rect.Left + _rect.Width - 5f, _rect.Top + _rect.Height - 5f, 10f, 10f);
            var rectRotate = new RectangleF(-5, _rect.Top + -30, 10f, 10f);
            var rectCenter = new RectangleF(-5, -5, 10f, 10f);

            var backBrush = new SolidBrush(Color.CadetBlue);
            var cornerBrush = new SolidBrush(Color.OrangeRed);

            // Looks rotated because we've transformed the graphics context
            gc.FillRectangle(backBrush, _rect);
            gc.FillRectangle(cornerBrush, rectTopLeft);
            gc.FillRectangle(cornerBrush, rectTopRight);
            gc.FillRectangle(cornerBrush, rectBottomLeft);
            gc.FillRectangle(cornerBrush, rectBottomRight);
            gc.FillRectangle(cornerBrush, rectRotate);
            gc.FillRectangle(cornerBrush, rectCenter);

            // Reset Graphics state
            gc.ResetTransform();
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            // Compute a Screen to Rectangle transform

            var mat = new Matrix();
            mat.Translate(_rectPos.X, _rectPos.Y);
            mat.Rotate(_rectRotation);
            mat.Invert();

            // Mouse point in Rectangle's space.
            var point = mat.TransformPoint(new PointF(e.X, e.Y));

            var rect = _rect;
            var rectTopLeft = new RectangleF(_rect.Left - 5f, _rect.Top - 5f, 10f, 10f);
            var rectTopRight = new RectangleF(_rect.Left + _rect.Width - 5f, _rect.Top - 5f, 10f, 10f);
            var rectBottomLeft = new RectangleF(_rect.Left - 5f, _rect.Top + _rect.Height - 5f, 10f, 10f);
            var rectBottomRight = new RectangleF(_rect.Left + _rect.Width - 5f, _rect.Top + _rect.Height - 5f, 10f, 10f);
            var rectRotate = new RectangleF(-5, _rect.Top + -30, 10f, 10f);

            if (!_drag)
            {
                //We're in Rectangle space now, so its simple box-point intersection test
                if (rectTopLeft.Contains(point))
                {
                    _drag = true;
                    _dragStart = new PointF(point.X, point.Y);
                    _dragAnchor = AnchorPoint.TopLeft;
                    _dragRect = new RectangleF(_rect.Left, _rect.Top, _rect.Width, _rect.Height);
                }
                else if (rectTopRight.Contains(point))
                {
                    _drag = true;
                    _dragStart = new PointF(point.X, point.Y);
                    _dragAnchor = AnchorPoint.TopRight;
                    _dragRect = new RectangleF(_rect.Left, _rect.Top, _rect.Width, _rect.Height);
                }
                else if (rectBottomLeft.Contains(point))
                {
                    _drag = true;
                    _dragStart = new PointF(point.X, point.Y);
                    _dragAnchor = AnchorPoint.BottomLeft;
                    _dragRect = new RectangleF(_rect.Left, _rect.Top, _rect.Width, _rect.Height);
                }
                else if (rectBottomRight.Contains(point))
                {
                    _drag = true;
                    _dragStart = new PointF(point.X, point.Y);
                    _dragAnchor = AnchorPoint.BottomRight;
                    _dragRect = new RectangleF(_rect.Left, _rect.Top, _rect.Width, _rect.Height);
                }
                else if (rectRotate.Contains(point))
                {
                    _drag = true;
                    _dragStart = new PointF(point.X, point.Y);
                    _dragAnchor = AnchorPoint.Rotation;
                    _dragRect = new RectangleF(_rect.Left, _rect.Top, _rect.Width, _rect.Height);
                    _dragRot = _rectRotation;
                }
                else if (rect.Contains(point))
                {
                    _drag = true;
                    _dragStart = new PointF(point.X, point.Y);
                    _dragAnchor = AnchorPoint.Center;
                    _dragRect = new RectangleF(_rect.Left, _rect.Top, _rect.Width, _rect.Height);
                    _dragStartOffset = new PointF(e.X - _rectPos.X, e.Y - _rectPos.Y);
                }
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            _drag = false;
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (_drag)
            {
                var mat = new Matrix();

                mat.Translate(_rectPos.X, _rectPos.Y);
                mat.Rotate(_rectRotation);
                mat.Invert();

                var point = mat.TransformPoint(new PointF(e.X, e.Y));

                SizeF deltaSize;
                PointF clamped;

                switch (_dragAnchor)
                {
                    case AnchorPoint.TopLeft:

                        clamped = new PointF(Math.Min(0, point.X), Math.Min(0, point.Y));
                        deltaSize = new SizeF(clamped.X - _dragStart.X, clamped.Y - _dragStart.Y);
                        _rect = new RectangleF(
                            _dragRect.Left + deltaSize.Width,
                            _dragRect.Top + deltaSize.Height,
                            _dragRect.Width - deltaSize.Width,
                            _dragRect.Height - deltaSize.Height);
                        break;

                    case AnchorPoint.TopRight:
                        clamped = new PointF(Math.Max(0, point.X), Math.Min(0, point.Y));
                        deltaSize = new SizeF(clamped.X - _dragStart.X, clamped.Y - _dragStart.Y);
                        _rect = new RectangleF(
                            _dragRect.Left,
                            _dragRect.Top + deltaSize.Height,
                            _dragRect.Width + deltaSize.Width,
                            _dragRect.Height - deltaSize.Height);
                        break;

                    case AnchorPoint.BottomLeft:
                        clamped = new PointF(Math.Min(0, point.X), Math.Max(0, point.Y));
                        deltaSize = new SizeF(clamped.X - _dragStart.X, clamped.Y - _dragStart.Y);
                        _rect = new RectangleF(
                            _dragRect.Left + deltaSize.Width,
                            _dragRect.Top,
                            _dragRect.Width - deltaSize.Width,
                            _dragRect.Height + deltaSize.Height);
                        break;

                    case AnchorPoint.BottomRight:
                        clamped = new PointF(Math.Max(0, point.X), Math.Max(0, point.Y));
                        deltaSize = new SizeF(clamped.X - _dragStart.X, clamped.Y - _dragStart.Y);
                        _rect = new RectangleF(
                            _dragRect.Left,
                            _dragRect.Top,
                            _dragRect.Width + deltaSize.Width,
                            _dragRect.Height + deltaSize.Height);
                        break;

                    case AnchorPoint.Rotation:
                        var vecX = point.X;
                        var vecY = -point.Y;

                        var len = Math.Sqrt(vecX*vecX + vecY*vecY);

                        var normX = vecX / len;
                        var normY = vecY / len;

                        //In rectangles's space,
                        //compute dot product between,
                        //Up and mouse-position vector
                        var dotProduct = (0*normX + 1*normY);
                        var angle = Math.Acos(dotProduct);

                        if (point.X < 0)
                            angle = -angle;

                        // Add (delta-radians) to rotation as degrees
                        _rectRotation += (float) ((180/Math.PI)*angle);

                        break;

                    case AnchorPoint.Center:
                        //move this in screen-space
                        _rectPos = new PointF(e.X - _dragStartOffset.X, e.Y - _dragStartOffset.Y);
                        break;
                }

                Invalidate();
            }
        }
    }
}

Explanation
The trick is to move your mouse points into the rectangle's space. This is done by making a matrix with the rectangles point of origin, its rotation and inverting it:
var mat = new Matrix();
mat.Translate(_rectPos.X, _rectPos.Y);
mat.Rotate(_rectRotation);
mat.Invert();

then you multiply your screen-space points with the inverted matrix to get you a point in the rectangle's space.
var point = mat.TransformPoint(new PointF(e.X, e.Y));

From there is very simple to do all your operations. i.e. all intersections are point-box tests, and all transformations and scaling are done on an axis-aligned box.
Example

Todo

*

*separate the code and make reusable

*when you stop dragging, reset the _rectPos to the center of the rectangle

Enjoy. :)


text:
Q: Can't access JQuery through CSS I am trying to write a menu for a front page that when an item is hovered over, the background image of the background div changes.
I have three main documents creating this effect, menuFunction.php, which is included in the header file, so it is not a link problem, then there is index.php, and finally my stylesheet.
Here is an example of one of the menu items functions from my menuFunction.php file:

Now here is where it is mentioned in index.php:

Resume

About

Gallery

Contact

Notice that the classes mentioned in the menuFunctions.php are also mentioned in the corresponding li.
Now, I am able through my stylesheet to define that the background have the following attributes for #photoBackground
#photoBackground{
height:450px;
width:100%;
background-image:url(http://www.vhawley.com/wp-content/themes/vhawleycomtheme/css/style/images/menuDefault.jpg);
background-repeat:no-repeat;
background-position:center;
}

Lastly, what I am now trying to accomplish is to get the rest to work, but even when I use the class .resume in my CSS, it does not work, even when I use the div #menuResume, no luck. I have been trying forever and have tried putting off asking for help on this one, but I really am stuck. I have really no JQuery experience, just CSS, HTML 5, and some PHP, which usually if you can master them, they can make a decent site alone. Until you want to get fancy like this.
Any ideas?
EDIT:
It is an issue with linking the JQuery variables to CSS, it has nothing to do with getting the background to change, because as Popnoodles proved on JSFiddle, nothing is wrong with that.

A: Best way to do this would be plain css
.resume #photoBackground {
  ...
}

.resume:hover #photoBackground {
  ... new image
}

A: You could do this with the css :hover selector. However, if you want to use jQuery, you need to change .css('background'... to .css('background-image'...
It is the small mistakes that trip us up the most.
Edit to clarify your mistake:
The background style overrides everything, including background-repeat and background-position so those are all gone. If you used background-image it wouldn't override those other css options.

A: I would research spriting to save some image loads, but that would requeire a fixed or known hight for the background image container. I would also use the following instead of wiring up a handler for each menu item:
HTML

Resume

About

Gallery

Contact

Script
//Save looking up background container each time
var background = $("#photoBackground");

$("#menu li").hover(
//Hanldes Mouse Enter
function () {
    var cssClass = $(this).attr('class');
    $(background).addClass(cssClass);
},
//Handles Mouse Exit
function () {
    var cssClass = $(this).attr('class');
    $(background).removeClass(cssClass);
})

CSS
.backgroundImage {
    background-image:url(http://www.vhawley.com/wp-content/themes/vhawleycomtheme/css/style/images/menuResume.jpg);
}
.backgroundImage.resume {
    background-position:left -100px;
}
.backgroundImage.about {
    background-position:left -200px;
}
.backgroundImage.gallery {
    background-position:left -300px;
}
.backgroundImage.contact {
    background-position:left -400px;
}

This also kind of demonstrates the principle of spriting by just changing the offset of the background image. OF course you could always just change the background image itself.
Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to list all of the running processes inside the /proc directory? I have been trying to retrieve all of the running processes inside of the /proc directory on Linux (kali Linux). I was curious to know if there was a certain command such as ps or top that allowed me to search inside a specific directory.
I have been using a shell script (.sh) to try and retrieve all of the running processes inside of the /proc directory.
I managed to create some code that would check for PIDS inside of the /proc directory and then check their /status file.
Once the file has been opened (with cat) it then checks for the 'status' of the process and finally I check if the process is set to 'R' (running) and return the pid.
for ProcessNum in $(ls /proc/ | grep -E '^[0-9]+$'); do
  if [ "$(cat /proc/$ProcessNum/status | grep '^State' | awk '{print $2}')" = "R" ]; then
    echo $ProcessNum
  fi
done

This currently returns nothing, but if I change the check of status to 'S' it returns all of the sleeping processes


text:
Q: Incluir en una consulta SQL un campo de otra tabla con una condición estoy trabajando con SQLServer. Tengo la siguiente consulta sencilla:
SELECT fec_emis,a.art_des, a.co_art FROM demo.dbo.art a
    INNER JOIN demo.dbo.reng_com r ON a.co_art=r.co_art
    INNER JOIN demo.dbo.compras c ON r.fact_num=c.fact_num

Pero ahora necesito añadir un campo que está en otra tabla, este campo lo obtengo individualmente con la siguiente consulta:
SELECT TOP 1 tasa_v,fecha FROM tasas WHERE co_mone='$'
AND fecha<=GETDATE() ORDER BY fecha DESC

Esta ultima consulta lo que hace es darme la tasa más reciente según una fecham que en este caso es la actual (GETDATE()), pero ahora necesito que me de esa tasa pero con la fecha que tengo en la otra consulta (fec_emis), o sea, que me haga la primera consulta pero qu me incluya estos campos del registro cuya fecha sea más cercana a la fecha de amisión.
Edito:
Estructura de las tablas:
Tabla TASAS:
tasa_v
fecha
co_mone

Tabla compras
fec_emis
fact_num

Tabla reng_com
fact_num
co_art

Tabla art
co_art

A: En este caso, como tu subconsulta devuelve un solo registro, alcanza con que la trates como si fuera un campo mas, pasandole a la misma el campo por el cual queres filtrar:
SELECT fec_emis,
       a.art_des,
       a.co_art,
       (SELECT TOP 1 tasa_v FROM tasas WHERE co_mone='$'
           AND fecha<=fec_emis ORDER BY fecha DESC) as tasa
FROM demo.dbo.art a
INNER JOIN demo.dbo.reng_com r ON a.co_art=r.co_art
INNER JOIN demo.dbo.compras c ON r.fact_num=c.fact_num

Fijate que de la subconsulta saque el campo fecha, porque una subconsulta no puede devolver dos campos. Si necesitas que devuelva dos campos, la cosa es un poco mas complicada. Se pueden hacer dos selects (algo que seria poco performarte) o usar un with (si fuera una vista para no tener que recorrer todo lo mismo dos veces).

A: Pese a que la respuesta de gbianchi es correcta, quiero ofrecer una que puede ser mas optimizada, especialmente si vas a requerir más de una columna de "tasas", y es la siguiente:
SELECT fec_emis,a.art_des, a.co_art, t.fecha, t.tasa_v FROM demo.dbo.art a
INNER JOIN demo.dbo.reng_com r ON a.co_art=r.co_art
INNER JOIN demo.dbo.compras c ON r.fact_num=c.fact_num
INNER JOIN tasas t ON NOT EXISTS (SELECT * FROM tasas t2 where t.fecha <
t2.fecha and t2.fecha < c.fec_emis) And t.fecha < c.fec_emis


text:
Q: Magento : Add text fields to selected multiselect options I have a multiselect attribute, say Marks.
Now I have added subjects as
Sub1
Sub2
Sub3
Sub4

as Options for it.
The problem is, in the Admin panel, when the user select Sub 1, Sub 2 options for a particular product, I need another field nearby to enter % of marks.
Marks are different for different products, so I can't set them in labels of Marks attribute
Consider I have a huge number of subjects
What I require in backend, when Sub 1, Sub 2 is selected
Sub1 -> 87%
Sub2 -> 52%

If Ajax, I am happy,
adjustable even it comes in a button click...
Please help me...
Thanks in advance :)

A: Magento does not support this out of the box.
You may need to create a custom template for your attribute where you can add you javascript that adds a new text field each time you select a value for the multiselect and save those values serialized in the database.
Here is an example of how you can create an attribute with a custom template.
It's kind of long to replicate in here.
The main idea is to create a custom backend model for you attribute that will serialize the values on save and unserialize them on load, and a custom rendered that will display the multiselect and the fields for each value in the admin UI.


text:
Q: Displaying a variable in a Discord bot after adding to its value I'm trying to display a variable "money" for my discord bot.
I add 10 thousand to money (previously defined as 0) and when I do the command "add" it says "added 10K balance. total balance is 10000" (as it should) but after that, whenever I do "bal" (balance) it still displays 0.
Here is my code:
if(message.content.startsWith(prefix)){
        var money = 0
        let args = message.content.slice(prefix.length).split(" ");
        let commandName = args.shift().toLowerCase();

        if(commandName == "bal"){
          message.channel.send(money)
        }

        if(commandName == "add"){
          money = money + 10000
          message.channel.send("added 10K balance. total balance is " + money)
        }
       }

A: You will need a database for this. I recommend using MongoDB
It has a great free-plan (No CC Required and Lifetime) is very user-friendly and has good performance.
I recommend you watching this video.
The Video will guide you through the whole setup.
But for viewing the Database, I recommend using this Application instead of the Application (Robo3T) shown in the Video, Robo3T crashed a lot for me and doesn't have good reviews in general. If you have any questions, make sure to ask as much as possible! :D


text:
Q: NodeMCU JSON POST data issue I am using the below code for sending POST json requests.
I am receiving the request, but the body parameter is coming as null. ("body": null)
// Example of the different modes of the X.509 validation options
// in the WiFiClientBearSSL object
//
// Mar 2018 by Earle F. Philhower, III
// Released to the public domain

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <time.h>
#include <ArduinoJson.h>

#ifndef STASSID
#define STASSID "biranchi@xxx"
#define STAPSK  "0xxxxx4"
#endif

const char *ssid = STASSID;
const char *pass = STAPSK;

const uint16_t port = 443;

const char *   host = "xxxxxx.execute-api.ap-southeast-1.amazonaws.com";
const char *   path = "/dev/";

// Set time via NTP, as required for x.509 validation
void setClock() {
  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  Serial.print("Waiting for NTP time sync: ");
  time_t now = time(nullptr);
  while (now < 8 * 3600 * 2) {
    delay(500);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println("");
  struct tm timeinfo;
  gmtime_r(&now, &timeinfo);
  Serial.print("Current time: ");
  Serial.print(asctime(&timeinfo));
}

// Try and connect using a WiFiClientBearSSL to specified host:port and dump HTTP response
void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) {
  if (!path) {
    path = "/";
  }

  StaticJsonDocument<300> doc;
  doc["key11"] = "Value11";
  doc["time"] = 1232323;

  // serializeJson(doc, Serial);

  char buffer[100];
  serializeJson(doc, buffer);
  Serial.println(buffer);

//  String result = "{\"Action\":\"hi\",\"DeviceID\":\"1234567890\"}";
//  int len1 = len(result);
  size_t len = strlen(buffer);

  ESP.resetFreeContStack();
  uint32_t freeStackStart = ESP.getFreeContStack();
  Serial.printf("Trying: %s:443...", host);
  client->connect(host, port);
  if (!client->connected()) {
    Serial.printf("*** Can't connect. ***\n-------\n");
    return;
  }
  Serial.printf("Connected!\n-------\n");
  //client->write("GET ");
  client->write("POST ");
  client->write(path);
  client->write(" HTTP/1.0\r\nHost: ");
  client->write(host);
//  client->write("\r\nUser-Agent: ESP8266\r\n");
  client->write("\r\nAccept: */*");
  client->write("\r\nContent-Type: application/x-www-form-urlencoded");
//  client->write("\r\nContent-Length: " + len);
  client->write("\r\n");
  client->write("\r\n");
  client->write(buffer);

  uint32_t to = millis() + 5000;
  if (client->connected()) {
    do {
      char tmp[32];
      memset(tmp, 0, 32);
      int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1);
      yield();
      if (rlen < 0) {
        break;
      }
      // Only print out first line up to \r, then abort connection
      char *nl = strchr(tmp, '\r');
      if (nl) {
        *nl = 0;
        Serial.print(tmp);
        break;
      }
      Serial.print(tmp);
    } while (millis() < to);
  }
  client->stop();
  uint32_t freeStackEnd = ESP.getFreeContStack();
  Serial.printf("\nCONT stack used: %d\n-------\n\n", freeStackStart - freeStackEnd);
}

void fetchNoConfig() {
  Serial.printf(R"EOF(
If there are no CAs or insecure options specified, BearSSL will not connect.
Expect the following call to fail as none have been configured.
)EOF");
  BearSSL::WiFiClientSecure client;
  fetchURL(&client, host, port, path);
}

void fetchInsecure() {
  Serial.printf(R"EOF(
This is absolutely *insecure*, but you can tell BearSSL not to check the
certificate of the server.  In this mode it will accept ANY certificate,
which is subject to man-in-the-middle (MITM) attacks.
)EOF");
  BearSSL::WiFiClientSecure client;
  client.setInsecure();
  fetchURL(&client, host, port, path);
}

void fetchFingerprint() {
  Serial.printf(R"EOF(
The SHA-1 fingerprint of an X.509 certificate can be used to validate it
instead of the while certificate.  This is not nearly as secure as real
X.509 validation, but is better than nothing.
)EOF");
  BearSSL::WiFiClientSecure client;
  static const char fp[] PROGMEM = "5F:F1:60:31:09:04:3E:F2:90:D2:B0:8A:50:38:04:E8:37:9F:BC:76";
  client.setFingerprint(fp);
  fetchURL(&client, host, port, path);
}

void fetchSelfSigned() {
  Serial.printf(R"EOF(
It is also possible to accept *any* self-signed certificate.  This is
absolutely insecure as anyone can make a self-signed certificate.
)EOF");
  BearSSL::WiFiClientSecure client;
  Serial.printf("First, try and connect to a badssl.com self-signed website (will fail):\n");
  fetchURL(&client, "self-signed.badssl.com", 443, "/");
  Serial.printf("Now we'll enable self-signed certs (will pass)\n");
  client.allowSelfSignedCerts();
  fetchURL(&client, "self-signed.badssl.com", 443, "/");
}

void fetchKnownKey() {
  Serial.printf(R"EOF(
The server certificate can be completely ignored and its public key
hardcoded in your application. This should be secure as the public key
needs to be paired with the private key of the site, which is obviously
private and not shared.  A MITM without the private key would not be
able to establish communications.
)EOF");
  // Extracted by: openssl x509 -pubkey -noout -in servercert.pem
  static const char pubkey[] PROGMEM = R"KEY(
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy+3Up8qBkIn/7S9AfWlH
Od8SdXmnWx+JCIHvnWzjFcLeLvQb2rMqqCDL5XDlvkyC5SZ8ZyLITemej5aJYuBv
zcKPzyZ0QfYZiskU9nzL2qBQj8alzJJ/Cc32AWuuWrPrzVxBmOEW9gRCGFCD3m0z
53y6GjcmBS2wcX7RagqbD7g2frEGko4G7kmW96H6dyh2j9Rou8TwAK6CnbiXPAM/
5Q6dyfdYlHOCgP75F7hhdKB5gpprm9A/OnQsmZjUPzy4u0EKCxE8MfhBerZrZdod
88ZdDG3CvTgm050bc+lGlbsT+s09lp0dgxSZIeI8+syV2Owt4YF/PdjeeymtzQdI
wQIDAQAB
-----END PUBLIC KEY-----
)KEY";
  BearSSL::WiFiClientSecure client;
  BearSSL::PublicKey key(pubkey);
  client.setKnownKey(&key);
  fetchURL(&client, host, port, path);
}

void fetchCertAuthority() {
  static const char digicert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j
ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL
MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3
LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug
RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm
+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW
PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM
xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB
Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3
hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg
EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF
MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA
FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec
nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z
eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF
hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2
Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe
vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep
+OkuE6N36B9K
-----END CERTIFICATE-----
)EOF";

  Serial.printf(R"EOF(
A specific certification authority can be passed in and used to validate
a chain of certificates from a given server.  These will be validated
using BearSSL's rules, which do NOT include certificate revocation lists.
A specific server's certificate, or your own self-signed root certificate
can also be used.  ESP8266 time needs to be valid for checks to pass as
BearSSL does verify the notValidBefore/After fields.
)EOF");

  BearSSL::WiFiClientSecure client;
  BearSSL::X509List cert(digicert);
  client.setTrustAnchors(&cert);
  Serial.printf("Try validating without setting the time (should fail)\n");
  fetchURL(&client, host, port, path);

  Serial.printf("Try again after setting NTP time (should pass)\n");
  setClock();
  fetchURL(&client, host, port, path);
}

void fetchFaster() {
  Serial.printf(R"EOF(
The ciphers used to set up the SSL connection can be configured to
only support faster but less secure ciphers.  If you care about security
you won't want to do this.  If you need to maximize battery life, these
may make sense
)EOF");
  BearSSL::WiFiClientSecure client;
  client.setInsecure();
  uint32_t now = millis();
  fetchURL(&client, host, port, path);
  uint32_t delta = millis() - now;
  client.setInsecure();
  client.setCiphersLessSecure();
  now = millis();
  fetchURL(&client, host, port, path);
  uint32_t delta2 = millis() - now;
  std::vector<uint16_t> myCustomList = { BR_TLS_RSA_WITH_AES_256_CBC_SHA256, BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA };
  client.setInsecure();
  client.setCiphers(myCustomList);
  now = millis();
  fetchURL(&client, host, port, path);
  uint32_t delta3 = millis() - now;
  Serial.printf("Using more secure: %dms\nUsing less secure ciphers: %dms\nUsing custom cipher list: %dms\n", delta, delta2, delta3);
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();

  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");

  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  fetchNoConfig();
  fetchInsecure();
  fetchFingerprint();
  fetchSelfSigned();
  fetchKnownKey();
  fetchCertAuthority();
  fetchFaster();
}

void loop() {
  // Nothing to do here
}

Am I missing something ?

A: you've set your content-type header to x-www-form-urlencoded and then you're sending JSON data. you should change that to application/json.


text:
Q: why do inputs created by javascript appear outside their divs? Why are the inputs created by JavaScript in this very simple code appearing below the div instead of inside it?
HTML:

I am filler text

JavaScript:
function makeButton() //Activated when a button in another part of the page is pressed
{
    var text = "";
    text += "
What is your gender?
";
    text += "<input type='button' class='genderButton' value='male' onClick='maleFunction'/>";
    text += "<input type='button' class='genderButton' value='female' onClick='femaleFunction'/>";
    document.getElementById("magicButtonDiv").innerHTML=text;
}

CSS:
#magicButtonDiv
{
    box-sizing         : border-box;
    -moz-box-sizing    : border-box;
    -webkit-box-sizing : border-box;
    border             : 1px solid #000000;
}

input.genderButton
{
    float.      : left;
    margin-left : 2%;
    width       : 47%;
}

There's more code, but I think the error is somewhere in this part of the code.

A: Add style rule of float:left to your #magicbuttondiv. It will solve the problem

A: See this fiddle
You have many errors in your Javascript. Please replace your Javascript with the below given one
function makeButton() {
    var text = "";
    text += "
What is your gender?
";
    text += "<input type='button' class='genderButton' value='male' onClick='maleFunction()'>";
    text += "<input type='button' class='genderButton' value='female' onClick='femaleFunction()'>";
    document.getElementById("magicButtonDiv").innerHTML = text;
}

UPDATE
I just found that you have errors in your CSS too..
Notice float.: left; specified for input.genderButton. Realised just now that the float was not actually applied.
So here is the updated fiddle with floats applied.


text:
Q: Qpython3, sqlite3 can't connect to database I'm beginner and I just try qpython for android.
I try to connect database at qpython3 by using sqlite3:
My code
import sqlite3
conn=sqlite3.connect('mydatabase.db')

But it raises error and unable to open database file.
Any solution for this??
If I try at pc, it automatically create a database if not exists

A: The reason it doesn't work is that QPython programs are run from '/' directory which of course is not writable to non-root users.  You can check this with the following code run from the console.
import os
print(os.getcwd())

If you go to the ftp utility in the About menu, you will find a directory path that is being used by QPython3. On my HTC mobile it is:
/storage/emulated/0/com.hipipal.qpyplus

So I changed your example code to:
import os
import sqlite3
RootPath='/storage/emulated/0/com.hipipal.qpyplus'
conn=sqlite3.connect(os.path.join(RootPath,'mydatabase.db'))

and it works fine for me.
I also found that it is necessary to commit changes or they won't be written to the file. That is, end programs with:
conn.commit()
conn.close()


text:
Q: Python: Plotting map in netCDF file using Basemap I'm working with netCDF file for plotting the map. However, I'm new to it and there is very little progress and all I did is learning some tutorials. I have some difficulties when overlaying color onto the map. Here is my code (with the downloaded file):
from mpl_toolkits.basemap import Basemap, cm
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt

data = Dataset('filename','r')

lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
time = data.variables['time'][:]
lwe_thickness = data.variables['lwe_thickness'][:]
data.close()

mp = Basemap(projection = 'mill',
         llcrnrlon=lon.min(),
         urcrnrlon=lon.max(),
         llcrnrlat=lat.min(),
         urcrnrlat=lat.max(),
         resolution = 'c')

x, y = np.meshgrid(lon, lat)
x, y = mp(lon, lat)

mp.drawcoastlines()
mp.drawstates()
mp.drawcountries()
mp.drawmapboundary()

parallels = np.arange(0.,90,30.)
mp.drawparallels(parallels,labels=[1,0,0,0])

meridians = np.arange(-180.,180.,30.)
mp.drawmeridians(meridians,labels=[0,0,0,1])

cmesh = mp.pcolormesh(x,y,lwe_thickness,shading='flat',cmap=plt.cm.jet,latlon=True)
cbar = mp.colorbar(cmesh, location='right')

plt.show()


text:
Q: Cron job python Google App Engine I want to add a scheduled task to fetch a URL via cron job using google app engine. I am continuously getting a failure. I am just fetching www.google.com. Why is the url fetch failing? Am I missing something?

A: "fetch" your OWN url (on appspot.com probably, but, who cares -- use a relative url anywau1-), not google.com, the homepage of the search engine -- what's that got to do w/your app anyway?!-)...


text:
Q: Can ForkingMixIn reuse a process, like ThreadingMixIn reuses a thread? EDIT: Probably this question is wrong. I was getting the thread id with threading.current_thread().ident and I got the same value for subsequent calls, which led me to think threads were being reused, but that does not seem to be the real thread id. With threading.current_thread().name I get different names for each request, so probably threads are not being reused. Besides the documentation I am attaching in the question refers to xmlrpc-c library, not python's. The thing is that I need to comunicate with a xmlrpc-c server from another xmlrpc-python server. My tests suggest that xmlrpc-c does reuse threads when requests come from the same connection (as I can take advantage of thread caches), but I am not totally sure.

Sorry if the title is a bit strange, but I didn't know how to make it clearer.
The thing is, when using a XMLRPC server with ThreadingMixIn it spawns a new thread to serve each request, but it leaves that connection open for some time, so it is always the same thread which serves all the requests that uses that connection. This has a limit, the default is 30 requests using the same connection. This can be read in the "Parameters" section of the documentation of ServerAbyss:
http://xmlrpc-c.sourceforge.net/doc/libxmlrpc_server_abyss.html#server_abyss_run_server
The way to reuse a connection is to send the request to the XMLRPC server using the same ServerProxy object, and not creating a new one inmediately before the call, that I think it is the usual way of making a RPC call.
Well, this behaviour is very useful for me, as it permits me to take advantage of some thread caches. But the real improvement would be to have this kind of behaviour using ForkingMixIn instead of ThreadingMixIn. The problem is that it seems that ForkingMixIn always spawns a new process to handle the request, without taking in consideration if the request comes from a connection already opened or not.
So, is there a way in which ForkingMixIn could "reuse" a process in the same way that ThreadingMixIn reuses a thread to handle a request arriving from an already opened connection?

A: socketserver.ForkingMixIn cannot do this.
But then neither can socketserver.ThreadingMixIn, so your premise is wrong. So the first question is… you thought you have connection pooling on threads, you didn't have it, and you didn't notice a problem, so are you sure you actually need it?

If you do, you will have to write your own mixin. Fortunately, you can subclass ForkingMixIn to do the heavy lifting for launching and managing processes, and just add your own code on top of it, which should be able to sit comfortably within the only usefully-documented method, process_request.
Also, not that, like many libraries in the stdlib, socketserver is meant to be readable and useful sample code as well as being a useful library, which is why the docs link to the source right at the top, which makes things a lot easier.

Unfortunately, while plugging your code into ForkingMixIn will be easy, designing and writing that code will not.
The basic concept is simple: you have a cache of child processes, keyed off the connection. For each request, you look up the connection in the cache, create a new child if needed, then pass the request to the appropriate child.
Unfortunately, every one of those steps is easier said than done.
Well, not the first. That's just a WeakValueDictionary. But beyond that:

*

*What is a "connection"? XMLRPC is a pure stateless request-response protocol. If you assume every address is a connection you get false positives (running two clients at once, or just two users inside the same NAT); if you assume every socket is a connection you get false negatives (clients can, and will, close the socket and open a new one for any reason they want). The usual answer is to use an application-level session stored in an HTTP cookie (or an HTTP header or an XML element), so now you have to write or use an HTTP session manager (including handling reap-on-timeout).

*How do you "pass the request" to the child? ForkingMixIn relies on the fact that the request is a local variable pre-fork and therefore still available as a local variable post-fork. That's not true for some object you pull out of a cache. So, you need to use a multiprocessing.Queue or Pipe, or some other IPC mechanism. And, while Queue makes things trivial for anything that can be pickled, a request object almost certainly can't be pickled, because it includes things like the socket files. So, you need to write code that bundles everything up into something that can be passed—which includes either doing fd migration (which Python doesn't handle for you) or reading all the request data to pass that instead (so the other side can then wrap it in, e.g., a BytesIO to stick in self.rfile).

*How does the child respond? Again, ForkingMixIn relies on the fact that it's inherited the wfile file from its parent, but again, that obviously isn't going to work here. If you haven't done fd migration, then you need to pass the response back over IPC (e.g., another Queue). In which case your parent has to block on that IPC. So, you're going to need to use a ThreadingMixIn to create a thread per request just so they can wait on your child processes (or some alternative mechanism, like a child-service thread that loops over all the IPCs as composable futures or as select-able pipes or whatever).

None of this is particularly hard conceptually (except the session-timeout issue), but it's all a whole lot of code.

A: I think the problem here is to pass the data to the process. You can give the process the connection (so it can handle everything by itself) but then you'll never know when the connection is closed or not needed anymore. Also the child process can't easily create a new connection after N requests.
Or you can keep the connection in the parent process and just pipe the data to the child (for example via stdout -> stdin pipe). But that means you have to copy each byte many times (take it out of the receiving buffer of the parent process, but it into the sending buffer of the parent's pipe, probably copy it a couple of times while the pipe does its magic, copy it into the child's input buffer, ...) and then everything again for each byte of result. Not an issue for small requests that take some time to process but probably something I'd keep an eye on.


text:
Q: Get instance of main window controller in app delegate I know that, for iOS, you can reference the root view controller from the app delegate like so:
var rootViewController = self.window!.rootViewController
How does one reference the main window controller from the app delegate when targeting OS X? I would like to pass a variable (the managed object context) this way, as I have read that it is a good solution for referencing the moc.

A: You can access the NSWindowController instance of the main NSWindow like this:
NSApplication.sharedApplication().mainWindow?.windowController

A: The ! in earlier answers will cause a crash if the window is hidden, so I recommend caching the window either like this or using a computed property:
var mWindow: NSWindow? = nil
func mainWindowCached() -> NSWindow? {
    if let window = NSApplication.shared.mainWindow {
        self.mWindow = window
    }
    return self.mWindow
}

A: You can access like this:
NSApplication.shared().mainWindow?.contentViewController as! YourViewController;


text: Q: Characters of simple $\mathfrak{sl}_n$-modules in positive characteristic with subregular nilpotent central character Consider representations of $\mathfrak{sl}_n$ in positive characteristic with a subregular nilpotent central character $\chi$ (i.e. $\chi$ is a nilpotent matrix whose Jordan normal form has two blocks of size $n-1$ and $1$). For every regular weight $\lambda$ of $\mathfrak{sl}_n$, we have the simple module $L_{\chi}(\lambda)$. My question is, how to compute the character of $L_{\chi}(\lambda)$?


text:
Q: Suppose A and B are sets. Prove that $A \subseteq B \implies (B - A) \cup A = B$. Prove that:
$$A \subseteq B \implies (B - A) \cup A = B$$
Assume $A \subseteq B$.
($\implies$)Let $x\in (B - A) \cup A$.
$(x\in B \land x\notin A) \lor x\in A$
$\implies$ $(x\in A \lor x\in B) \land (x\in A \lor x\notin A)$
$\implies$ $(x\in A \lor x\in B) \land (T)$
$\implies$ $(x\in A \lor x\in B)$
$\implies$ $(x\in B \lor x\in B)$ [because $A \subseteq B$]
$\implies$ $x\in B$.
($\impliedby$)Let $x\in B$.
I am having trouble at this part of the problem. I'm not sure how to get from B to $(B - A) \cup A$.
Thanks.

A:
. I'm not sure how to get from B to (B−A)∪A.

Recall $(x\in A\lor x\notin A)$ is $\top$.
Let $x\in B$.   Well also $(x\in A)$ or $(x\notin A)$, and so ...yadda yadda yadda... in either case $x\in(B\smallsetminus A)\cup A$.


text:
Q: Powershell Get-Module -ListAvailable not showing my module after import My powershell module has versioning i.e. it's installed in:
c:\program files\WindowsPowerShell\Modules\MyModule\4.0\MyModule.dll
When I open powershell ISE I can use it normally and when I run:
Get-Module -ListAvailable I can see it.
After using one cmdlet from my module, I can't see it anymore in the output of: Get-Module -ListAvailable
It's worth mentioning that when I move my module to:
c:\program files\WindowsPowerShell\Modules\MyModule\MyModule.dll
it's working.


text:
Q: Dynamically change x and y of a button I would like to know if there is any possible way through which I can dynamically change the position of a UIButton depending on screen size of the phone(4s, 5-series and 6)
Thanks in advance.

A: There are multiple ways to solve this issue:
1) With AutoLayout you can specify rules which describe how views relate to each other. This will allow the app to intelligently adapt to any screen size, if thoughtfully implemented.
2) You can check the device version at runtime and programmatically layout your view appropriately.
1 is the preferred solution, and is best practice on iOS.

A: As Woodstock as suggested you can use Autolayout. But if you are familiar with it and have a simple use-case, you can use the [UIScreen mainScreen] bounds].size.height property to get height of the screen and compare it with the sizes of the different devices using the if/switch and then accordingly call the following in each of the cases to adjust its position accordingly.
[button setCenter:<CGPoint calculated goes here>];

For the Autolayout approach you can checkout this answer.


text:
Q: inline functions link error C++ Consider the following code:
In header.h
#pragma once

class someClass
{
public:
    void foo();
};

In header.cpp
#include "header.h"

inline void someClass::foo(){}

In main.cpp
#include <iostream>
#include "header.h"
using namespace std;

int main()
{
    someClass obj;
    obj.foo();
}

Here I get a link error because foo function is defined as inline in header.cpp, if I remove the 'inline' keyword, the compile and run will proceed without errors.
Please tell me why I get link error on this 'inline' function?

A: The way you wrote it, inline applies to the current file scope. When an inline function is in a header, that header is included in a cpp file, and then the function is inlined where it is used in that file's scope, so there is no problem. In this case, your function is available as inline only where it is defined, and no other cpp file sees it, except as a regular member declaration in its class, hence the link error.
If you want it to be inline, add the code and the inline keyword in the header.


text:
Q: Android bound service not destroyed after all clients unbind I have 2 services A and B.
A creates B and binds to B via the Context#bindService() with the CONTEXT_AUTO_CREATE flag. Normally when A unbinds from B, B is destroyed. Under this approach, A and B are running in the same process with A's package name.
I need B running in a separate process, so I added a android:process flag to B's AndroidManifest.xml. This way, when A binds & auto-creates B, B will run a separate process from A.
However, I noticed that when A unbinds from B, B continues to be up. This is against the Android Developer guide on bound processes - that a service is not considered "started" if Service#onStartCommand() is not called. As a matter of fact, onStartCommand() is never called. But when all clients unbind from B, B continues to run. Why is that? Is there a way to resolve this issue?
Any help is appreciated


text:
Q: Failed at the phantomjs-prebuilt@2.1.13 install script 'node install.js' I am trying to install phantomjs on a windows 7 machine and am getting this error .
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files (x86)\\nodist\\v\\nodev5.5.0\\node.exe"   "C:\\Program Files (x86)\\nodist\\bin\\node_mod
ules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v5.5.0
npm ERR! npm  v3.10.9
npm ERR! code ELIFECYCLE

npm ERR! phantomjs-prebuilt@2.1.13 install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the phantomjs-prebuilt@2.1.13 install script 'node   install.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.

There are many issues logged  in the phantomjs github repo for the same  or this SO questionbut none of it is helping in my case.
This is what is the state of my machine

*

*I have phantomjs installed locally at C:\npm\phantomjs-2.1.1-windows\bin\phantomjs.exe but when I run the npm install,it will always try to install by downloading which is where the problem for me.My corporate proxy is blocking the direct downloads .I also cannot use the  --phantomjs_cdnurl switch mentioned here https://www.npmjs.com/package/phantomjs#deciding-where-to-get-phantomjs

*I can run the command and it works fine
    phantomjs -v
     2.1.1
But when I run npm install on my project it is trying to install the phantomjs and will run into the above error.Another thing I observed from the npm log
Considering PhantomJS found at C:\Program Files (x86)\nodist\bin\phantomjs.CMD
Found PhantomJS at C:\Program Files (x86)\nodist\bin\phantomjs.CMD ...verifying
Error verifying phantomjs, continuing { [Error: Command failed: C:\Program Files (x86)\nodist\bin\phantomjs.CMD --version
it is trying to run the phantomjs.CMD --version which also failing
Error verifying phantomjs, continuing { [Error: Command failed: C:\Program Files (x86)\nodist\bin\phantomjs.CMD --versio
n
internal/child_process.js:274
  var err = this._handle.spawn(options);
                         ^

TypeError: Bad argument
    at TypeError (native)
    at ChildProcess.spawn (internal/child_process.js:274:26)
    at exports.spawn (child_process.js:362:9)
    at Object.<anonymous> (C:\Program Files (x86)\nodist\bin\node_modules\phantomjs-prebuilt\bin\phantomjs:22:10)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:139:18)
]
  killed: false,
  code: 1,
  signal: null,
  cmd: 'C:\\Program Files (x86)\\nodist\\bin\\phantomjs.CMD --version' }

A: As a temporary work around I am able to get it installed by using --ignore-scripts
npm install phantomjs-prebuilt@2.1.13 --ignore-scripts
I also logged an issue in the github repo for the same
https://github.com/Medium/phantomjs/issues/649
edited
This issue was part of the build process script I was using and it does a npm clean and install everytime with a bunch of other things .So this issue appears many times in the same machine where we automated tests using phantomjs. I got some time to look into this issue and it seems my corporate proxy is blocking the download from https://github.com/Medium/phantomjs/releases/download/v2.1.1/phantomjs-2.1.1-windows.zip. I knew this before and had manually installed phantomjs binary and added to system path but the npm install still trying to download locally as showing in the log below.
Considering PhantomJS found at C:\npm\phantomjs-2.1.1-windows\bin\phantomjs.EXE
Looks like an `npm install -g` on windows; skipping installed version.

My corporate proxy was blocking all the phantomjs CDN urls as well (https://www.npmjs.com/package/phantomjs)
The work around I used was to get the phantomjs-2.1.1-windows.zip and copy it to the  C:\Users\<username>\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip and that resolved the issue with the build script.If someone cleans the temp directory,issue will come back. Even this is a work around but the corporate proxy cannot be unblocked for obvious reasons :)
Hope this helps someone!

A: I came across same error , It will solved by following changes, Hope it will help you .
sudo npm install phantomjs-prebuilt@2.1.13 --unsafe-perm

A: Sometimes when we try to install phantomjs locally, it will work. But for global, I suggest you to type
sudo npm install -g phantomjs-prebuilt --unsafe-perm

A: Please remove any vpn connected in your system. I removed office vpn and then hit npm install it worked fine for me.

A: All those solutions didn't help me
--ignore-scripts helped but finally installed phantomjs is unworkable and my karma tests were not able to use phantomjs browser.
However I found solution for my Win machine. I downloaded distribute with .exe file from https://phantomjs.org/download.html and then unpacked locally (it can be any folder):
then added to:
set Path=;C:\Users\admin\AppData\Roaming\phantomjs-2.1.1-windows\bin;$Path
After that 'npm install' was able to re-use it:
 [exec] > node install.js

 [exec]

 [exec] Considering PhantomJS found at C:\Users\admin\AppData\Roaming\phantomjs-2.1.1-windows\bin\phantomjs.EXE

 [exec] Found PhantomJS at C:\Users\admin\AppData\Roaming\phantomjs-2.1.1-windows\bin\phantomjs.EXE ...verifying

 [exec] Writing location.js file

 [exec] PhantomJS is already installed on PATH at C:\Users\admin\AppData\Roaming\phantomjs-2.1.1-windows\bin\phantomjs.EXE

 [exec]

 [exec] > phantomjs@2.1.7 install C:\xxx\client\ui\src\main\web\build\node_modules\phantomjs
 [exec] > node install.js


text:
Q: What's the right way to embed PHP code in my CSS and JavaScript files? Like everyone else I'm storing my site`s display information in style sheet files. And I want to create back-end cms so users will be able to, for example, change < h1 > color, size etc.
So, what's the right way to embed PHP code in my CSS file(s)?
Is adding this header:
<?php header("Content-type: text/css"); ?>

And changing file extension in link:
<link rel="stylesheet" type="text/css" media="screen" href="style.php">

Valid?
And what about JavaScript? At this moment I'm echoing <script type="text/javascript"> tags, but maybe there's also a way to embed everything in the .js files?
Thanks!

A: Yes, this is perfectly valid.
The same can be done for Javascript too by sending
<?php header("Content-type: application/javascript"); ?>

However, this is not optimal from a performance point of view because a PHP process has to be started for serving those resources.
If you have only very few dynamically changing CSS properties or JS variables, I would consider putting them into the document's head and continuing to serve the external files statically.
Remember that usually, there are no caching headers sent for PHP files. You'll have to take care of sending the correct headers inside your PHP script! Cheers @oracle certified professional for the reminder.

A: What you're doing is absolutely valid.
However if you're running a bigger site with many visitors, you should concern to just let PHP "build" a "real" CSS file when your user updates his or her design to save your servers performance to better needed things:
<?php

header("Content-type: text/css");

// Your database magic here to fetch the user-specific designs

// open the cached css
$cachefile = "cachedCSS/mycss.css";

if (file_exists($cachefile)) {
    // the page has been cached from an earlier request
    // output the contents of the cache file
    include($cachefile);
    // exit the script, so that the rest isnt executed
    exit;
}

$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();

Read more about it here: http://www.theukwebdesigncompany.com/articles/php-caching.php

A: Make sure you are parsing the php in those files.
In .htaccess :
AddType application/x-httpd-php .php .css .js

This will ensure that any <?php ?> tags in file types other than .php will be parsed by the server and the php code isn't readable by users.


text:
Q: How to validate and close a new tab which appeared after clicking a link using Karate UI? Steps to reproduce:

*

*Click on a link which opens a new tab

*Validate something on the page opened on and

*Close it.

How to focus on the new tab ,validate something, focus back on main page and close the other tab using Karate UI?
I went wrong somewhere. Please assist
Karate version : 0.9.6


text:
Q: Why are my desktop files and folders duplicated or showing 2 times? Files on my Desktop are showing 2 times.
Whenever I'm adding a new file or folder, it's showing 2 times, OR copying file from any SSD or HDD to desktop, it's automatically showing double.
Please refer to the screenshot to check the original issue,

I'm running Ubuntu 20.04 LTS

A: Check your Gnome Shell extensions. First install gnome-shell-extension-prefs if you do not have it already. Find and launch it by typing Extensions in the Applications overview. Disable your extensions one by one to check which one is causing the issue.
I suspect you may have two extensions active that manage the desktop, e.g. the default Desktop icons and Desktop Icons NG.


text:
Q: How does JavaScript engine compute arithmetic expression? Quick summary - I was running a piece of code(in React application) where I am summing up decimal values entered by a user. One of the conditions to move to next page is if the sum equals 100
Problem - In one case, the sum of all values (a+b+c+d+e+f) is being computed to 99.99999999999997 even though the summation(over a calculator) is 100. But when I change the summation order to a+d+e+f+b+c, the sum is correctly computed to 100.
Please find below code samples -
Wrong summation -
const result = [15+10.4+1.9+1.9+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //99.99999999999997

Correct summation -
const result = [15+10.4+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15+1.9+1.9].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //100

Questions -

*

*How does JavaScript engine compute?

*How to compute to 100 always (without using ceil, floor or round methods because Math.round(99.6) is also equal to 100.


text:
Q: Find the values of h for which the following set of vectors is linearly independent Find the values of h for which the following set of vectors is linearly independent
    1   h   1
    0   1   h
    0   h   1

A: solve the system $$\alpha+\beta h+\gamma=0$$
$$\beta+\gamma h=0$$
$$\beta h+\gamma=0$$

A: Find the values of $h$ for which the determinant of the matrix $$\begin{pmatrix} 1 & h & 1 \\ 0 & 1 & h\\ 0&h&1\end{pmatrix}$$ is nonzero. This determinant is $1-h^{2}$, hence all values of $h$ are allowed except $h=1$ and $h=-1$.


text:
Q: C how to use the function uname I should write a function to get some information about the system (the most important information is the the architecture). I found the function uname which can be used including sys/utsname.h. Well, though I googled and I read the documentation, I couldn't find any example of the function and I don't understand how to use uname. Anyone can explain me how to use it? it would be great if you can write an example, too. Thanks in advance.

A: From the documentation, it looks like you'd use it like so:
struct utsname my_uname;
if(uname(&my_uname) == -1)
   printf("uname call failed!");
else
   printf("System name: %s\nNodename:%s\nRelease:%s\nVersion:%s\nMachine:%s\n",
       my_uname.sysname, my_uname.nodename, my_uname.release,my_uname.version,my_uname.machine);

A: The uname() function takes a pointer to the utsname structure that will store the result as input. Therefore, just make a temporary utsname instance, pass the address of it to uname, and read the content of this struct after the function succeed.
struct utsname retval;
if(uname(&retval) < 0) {     // <----
  perror("Failed to uname");
  // error handling...
} else {
  printf("System name = %s\n", retval.sysname);
  // print other info....
  // see http://www.opengroup.org/onlinepubs/009695399/basedefs/sys/utsname.h.html
  //   for other members...
}

A: First, include the header:
#include <sys/utsname.h>

Then, define a utsname structure:
struct utsname unameData;

Then, call uname() with a pointer to the struct:
uname(&unameData); // Might check return value here (non-0 = failure)

After this, the struct will contain the info you want:
printf("%s", unameData.sysname);

http://opengroup.org/onlinepubs/007908775/xsh/sysutsname.h.html

A: A fully working example is worth a thousand words. ;-)
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/utsname.h>

int main(void) {

   struct utsname buffer;

   errno = 0;
   if (uname(&buffer) < 0) {
      perror("uname");
      exit(EXIT_FAILURE);
   }

   printf("system name = %s\n", buffer.sysname);
   printf("node name   = %s\n", buffer.nodename);
   printf("release     = %s\n", buffer.release);
   printf("version     = %s\n", buffer.version);
   printf("machine     = %s\n", buffer.machine);

   #ifdef _GNU_SOURCE
      printf("domain name = %s\n", buffer.domainname);
   #endif

   return EXIT_SUCCESS;
}


text:
Q: function won't display block Im getting into javascript and im doing a little "IQ" test to practice, im using radiobuttons and check buttons. The problem is when i select a radio button that has to call a function in an onclick event to display a DIV and when i select the other option in the same question it has to hidde the DIV shown in the first selection.
Here is the function:
function show(x){
            if(x==1){
                document.getElementById("teams").style.display ="block";
                document.getElementById("activity").style.display ="none";

            }else{
                if(x==2){

                document.getElementById("teams").style.display ="none";
                document.getElementById("activity").style.display ="block";
            }

            }
        }

Here is where call the function:

&#191Do you like Futball&#63

<input type="radio" name="like" value="Ly" id="yes" onclick="show(1); "  checked>
Yes

<input type="radio" name="like" value="Ln" id="no" onclick="show(2); " >
No

And i show this Divs depending wich one is selected:

Here i display 5 checkboxes

Here i display 5 Radio buttons

A: I'm using this exact code and your javascript seems to be working.  If you have an error please post.
<!DOCTYPE html>

            &#191Do you like Futball&#63

            <input type="radio" name="like" value="Ly" id="yes" onclick="show(1);"  checked>
            Yes

            <input type="radio" name="like" value="Ln" id="no" onclick="show(2); " >
            No

            teams

            activity

A: I got an extra bracket in other function, that was the problem. It seems i was coding the function, got distracted and forgott to close it correctly.


text:
Q: Convert .tiff to png in latex The journal I'm going to submit a paper requires .tiff format for images. I'm trying to add .tiff in latex, and I've found a thread: Add tif image to LaTeX.
However, I cannot add image from .tiff, and I don't know how to resolve it.
I just added
\usepackage{epstopdf}
\epstopdfDeclareGraphicsRule{.tif}{png}{.png}{convert #1 \OutputFile}
\epstopdfDeclareGraphicsRule{.tiff}{png}{.png}{convert #1 \OutputFile}
\AppendGraphicsExtensions{.tif,.tiff}

but I got a message
'convert' is not recognized as an internal or external command, operable program or batch file.

and error
'filename-tiff-to-png' not found

The epstopdf works well for .eps file, and my guess is that I miss something about the convert in the line \epstopdfDeclareGraphicsRule{.tif}{png}{.png}{convert #1 \OutputFile}.
Any help would be appreciated.


text:
Q: Symbology with Arcade Expression using ArcGIS Pro I am using ArcGIS Pro 2.6.
I have a line feature class, in the attributes of which there is a field "Type", and "Thickness", I need to make a complex Symbology that unites these 2 fields.
It would seem an easy task, but the lines are constantly updated and the values in the "Thickness" field as well.
I need to make sure that the "Thickness" field is graded, such as from 0 - 2, 2.5-4, etc. and at the same time it was merged with the "Type" field as in the picture
Script:
var w = $feature.Thickness
var width_str

// Here we define the width classification ranges
if(w < 0.8){
    width_str = ' up to 0.8'
} else if (w < 2) {
    width_str = ' between 0.8 and 2'}
} else if (w = Null) {
    width_str = ' '}

return $feature.Type + width_str

I have error:

General parsing error

What causes that?

A: I'm not too familiar with Arcade but you appear to be missing the end of line character ";" that is in many of the script samples.
To test for null the help file suggest IsEmpty(). So I would rewrite your Arcade script as:
var w = $feature.Thickness;
var width_str;

// Here we define the width classification ranges
if (w < 0.8)
    {width_str = ' up to 0.8';}
else if (w < 2)
    {width_str = ' between 0.8 and 2';}
else if (isempty(w))
   {width_str = ' ';}

return $feature.Type + width_str

A: Beyond the parsing error, there is a larger issue with the handling of null values.  Arcade, similar to JavaScript and some other languages, will cast null to 0 when casting to numeric for use with comparison operators.  Under the current logic of the code, a null value will result in the first conditional check as being true, and hence null will get a label of ' up to 0.8' instead of an empty string.
Before getting into ways of addressing null values, I want to point out that many languages have specific functions for evaluating series of conditional expressions so that long if/else statements are not needed.  In the case of Arcade the function is When | ArcGIS Arcade | ArcGIS Developers, and I will rewrite the code using it.
Getting back to null values, there are at least a couple different ways to handle them.  One approach is to use Default Value | ArcGIS Arcade | ArcGIS Developers to check for null (or empty string) and set it to infinity, which will allow the current code logic to work.
var w = DefaultValue($feature.Thickness, Infinity);
var width_str;

// Here we define the width classification ranges
When(
    w < 0.8, width_str = ' up to 0.8',
    w < 2, width_str = ' between 0.8 and 2',
    ' '
);

return $feature.Type + width_str;

Another approach is to put the IsEmpty | ArcGIS Arcade | ArcGIS Developers check first to handle null.
var w = $feature.Thickness;
var width_str;

// Here we define the width classification ranges
When(
    IsEmpty(w), ' ',
    w < 0.8, width_str = ' up to 0.8',
    w < 2, width_str = ' between 0.8 and 2',
    ' '
);

return $feature.Type + width_str


text:
Q: Remove string space, carriage return, line breaks, and tabs using JavaScript The question is fairly self-explanatory. I found a nice Java code block that does this:
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
strReplaced = m.replaceAll("");

Basically removes string space, carriage return, line breaks, and tabs.
How can do the same thing using JavaScript? Thanks for any help.

A: str = str.replace(/\s*|\t|\r|\n/gm, "")

A: Here you go:
const test = "this\n is \t atest ";
const clean = test.replace(/[\n\r\t\s]+/g, "");
console.log(clean); // thisisatest

A: Use String#replaceAll:

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

var str = 'Hello World!';
const replaced = str.replaceAll(new RegExp('\\s*|\t|\r|\n', 'g'), '');
console.log(replaced);

Or simply:

var str = 'Hello World!';
const replaced = str.replaceAll(/\s*|\t|\r|\n/gm, '');
console.log(replaced);


text:
Q: Why the result of simple CUDA program differs every time? I want to make a simple tiling convolution code. It is from the lecture of Coursera :Heterogeneous Parallel Programming. The lecture provides a simple convolution code with tiling method, but the code was not complete. Thus, I fill out the blanks in the code and below is the result.
The goal of this code is to calculate convolution.
Input dimension : (24 by 24),
Kernel size : (9 by 9),
Output dimension : (16 by 16).
Also, in the main, I put computation time checking code to compare with the CPU version.
The problem is, whenever I run this code, the result is different. I tried to find the problem for several day, but every trial did not work. I also found similar code in the Internet blog but it has same problem as mine. I do not know why the result is different every time. Some say it is due to the race condition, but I don't find anything about that.
Here is example result of convolution (16 by 16 size).
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
0   0   0   0   0   0   0   0   0   0   81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  81  81  81  81  81  81
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
81  81  81  81  81  81  81  81  81  81  0   0   0   0   0   0
My device is CUDA Driver = CUDART, CUDA Driver Version = 7.5, CUDA Runtime Version = 7.5, NumDevs = 1, Device0 = GeForce GT 630.
I use Ubuntu 14.04.
Thanks in advance!
#include<stdio.h>
#include<cuda.h>
#include<time.h>

#define O_TILE_WIDTH 10
#define MASK_WIDTH 9
#define I_TILE_WIDTH (O_TILE_WIDTH+MASK_WIDTH-1)

__global__ void Convolution2DBasicKernel(float *out, float *in, int in_height, int in_width, const float *__restrict__ mask, int output_dim)
{

    int tx=threadIdx.x;
    int ty=threadIdx.y;

    int row_o=blockIdx.y*O_TILE_WIDTH+ty;
    int col_o=blockIdx.x*O_TILE_WIDTH+tx;

    int row_i=row_o;
    int col_i=col_o;
    __syncthreads();

    __shared__ float Ns[I_TILE_WIDTH][I_TILE_WIDTH];

///////////////////////////////////////////////////////////
//////////////////// reading input data ///////////////////
    if( (row_i>=0)&&(row_i<in_height)&&(col_i>=0)&&(col_i<in_width) )
    {
        Ns[ty][tx]=in[row_i*in_width + col_i];
    }
    else
    {
        Ns[ty][tx]=0.0f;
    }
    __syncthreads();

///////////////////////////////////////////////////////////
//////////////////// calculating convol ///////////////////
    float output=0.0f;
    if( (tx<O_TILE_WIDTH)&&(ty<O_TILE_WIDTH) )
    {
        for(int i=0; i<MASK_WIDTH; i++)
        {
            for(int j=0; j<MASK_WIDTH; j++)
            {
                output += Ns[ty+i][tx+j]*mask[i*MASK_WIDTH+j];

            }
        }

    }
    __syncthreads();

    if( (row_o<output_dim)&&(col_o<output_dim) )
    {
        out[row_o*output_dim+col_o]=output;//in_width
    }
    __syncthreads();
}

int main() {

int input_dim=24;
    int kernel_dim=9;
    int output_dim=16;

float *input = new float[input_dim*input_dim];
float *kernel = new float[kernel_dim*kernel_dim];
float *output = new float[output_dim*output_dim];

float *d_input;
float *d_kernel;
float *d_output;
cudaMalloc(&d_input, sizeof(float)*input_dim*input_dim);
cudaMalloc(&d_kernel, sizeof(float)*kernel_dim*kernel_dim);
cudaMalloc(&d_output, sizeof(float)*output_dim*output_dim);

for(int i=0; i<input_dim*input_dim; i++)
{
    input[i]=1.0;
}
for(int i=0; i<kernel_dim*kernel_dim; i++)
{
    kernel[i]=1.0;
}

cudaMemcpy(d_input, input, sizeof(float)*input_dim*input_dim, cudaMemcpyHostToDevice);
cudaMemcpy(d_kernel, kernel, sizeof(float)*kernel_dim*kernel_dim, cudaMemcpyHostToDevice);

dim3 dimBlock (I_TILE_WIDTH, I_TILE_WIDTH, 1);
dim3 dimGrid ((output_dim-1)/O_TILE_WIDTH+1, (output_dim-1)/O_TILE_WIDTH+1, 1);

clock_t begin, end;
double time_spent;
begin = clock();

for(int iteration=0; iteration<1; iteration++)//100000
{
    Convolution2DBasicKernel<<<dimGrid, dimBlock>>>(d_output, d_input, input_dim, input_dim, d_kernel, output_dim);
}

end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("time: %f\n", time_spent);

cudaMemcpy(output, d_output, sizeof(float)*output_dim*output_dim, cudaMemcpyDeviceToHost);

for(int y=0; y<output_dim; y++)
{
    for(int x=0; x<output_dim; x++)
        printf("%d\t", int(output[y*16+x]));
    printf("\n");
}

}

A: It is a race condition.
Here is one example.
You are launching 18x18 threads per block and 2x2 blocks.
Example:
ThreadA
threadIdx.x = 10
threadIdx.y = 0
blockIdx.x  = 0
blockIdx.y  = 0
ThreadB
threadIdx.x = 0
threadIdx.y = 0
blockIdx.x  = 1
blockIdx.y  = 0

Inside the kernel when you calculate:
int tx=threadIdx.x
int ty=threadIdx.y
int row_o=blockIdx.y*O_TILE_WIDTH+ty
int col_o=blockIdx.x*O_TILE_WIDTH+tx
using O_TILE_WIDTH = 10

ThreadA
row_o = 0*10+10 = 10
col_o = 0
ThreadB
row_o = 1*10+0 = 10
col_o = 0

Which means that two thread will output the result at the same position in the memory but calculate it differently.

A: You are going out of bounds in your shared memory access.
Assuming you are confident your program is more or less correct, you would need to make sure you don't go out of bounds:
if( (tx<O_TILE_WIDTH)&&(ty<O_TILE_WIDTH) ) {
    for(int i=0; i<MASK_WIDTH; i++) {
        if(ty +i < O_TILE_WIDTH) { // Changed here
            for(int j=0; j<MASK_WIDTH; j++) {
                if(tx +j < O_TILE_WIDTH) { // Changed here
                    output += Ns[ty+i][tx+j]*mask[i*MASK_WIDTH+j];
                }
            }
        }
    }
}


text:
Q: How to see the settings of a Windows computer when the taskbar is inaccessible From my PC, there is a remote connection to a PC in another country. That PC has access towards a virtual computer, which is connected to via VMWare software. As that virtual machine is part of the remote network, I can't open it at my PC.
The problem is that the taskbar of that remote virtual PC is not visible in the VMWare window, and there seem to be problems with that virtual PC. So, I'd like to open the "settings viewer" application on that virtual PC, in order to start up the event viewer or to run some diagnostic tools.
I only have access to a command prompt and scheduled tasks (the latter is not important, I guess).
Does anybody know how I can open the settings on that PC, just using the command prompt?

A: I'd like to open the "settings viewer" application from a cmd prompt
You can open almost all of the control panel settings and other interesting programs from the command line.
Function                                    Command
Open Documents Folder                       documents
Open Videos folder                          videos
Open Downloads Folder                       downloads
Open Favorites Folder                       favorites
Open Recent Folder                          recent
Open Recent Folder                          logoff
Open Pictures Folder                        pictures
Windows Sideshow                            control.exe /name Microsoft.WindowsSideshow
Windows CardSpace                           control.exe /name Microsoft.cardspace
Windows Anytime Upgrade                     WindowsAnytimeUpgradeui
Taskbar and Start Menu                      control.exe /name Microsoft.TaskbarandStartMenu
Troubleshooting                             control.exe /name Microsoft.Troubleshooting
User Accounts                               control.exe /name Microsoft.UserAccounts
Adding a new Device                         devicepairingwizard
Add Hardware Wizard                         hdwwiz
Advanced User Accounts                      netplwiz
Advanced User Accounts                      azman.msc
Backup and Restore                          sdclt
Bluetooth File Transfer                     fsquirt
Calculator                                  calc
Certificates                                certmgr.msc
Change Computer Performance Settings        systempropertiesperformance
Change Data Execution Prevention Settings   systempropertiesdataexecutionprevention
Change Data Execution Prevention Settings   printui
Character Map                               charmap
ClearType Tuner                             cttune
Color Management                            colorcpl
Command Prompt                              cmd
Component Services                          comexp.msc
Component Services                          dcomcnfg
Computer Management                         compmgmt.msc
Computer Management                         compmgmtlauncher
Connect to a Projector                      displayswitch
Control Panel                               control
Create A Shared Folder Wizard               shrpubw
Create a System Repair Disc                 recdisc
Credential Backup and Restore Wizard        credwiz
Data Execution Prevention                   systempropertiesdataexecutionprevention
Date and Time                               timedate.cpl
Default Location                            locationnotifications
Device Manager                              devmgmt.msc
Device Manager                              hdwwiz.cpl
Device Pairing Wizard                       devicepairingwizard
Diagnostics Troubleshooting Wizard          msdt
Digitizer Calibration Tool                  tabcal
DirectX Diagnostic Tool                     dxdiag
Disk Cleanup                                cleanmgr
Disk Defragmenter                           dfrgui
Disk Management                             diskmgmt.msc
Display                                     dpiscaling
Display Color Calibration                   dccw
Display Switch                              displayswitch
DPAPI Key Migration Wizard                  dpapimig
Driver Verifier Manager                     verifier
Ease of Access Center                       utilman
EFS Wizard                                  rekeywiz
Event Viewer                                eventvwr.msc
Fax Cover Page Editor                       fxscover
File Signature Verification                 sigverif
Font Viewer                                 fontview
Game Controllers                            joy.cpl
Getting Started                             gettingstarted
IExpress Wizard                             iexpress
Getting Started                             irprops.cpl
Install or Uninstall Display Languages      lusrmgr
Internet Explorer                           iexplore
Internet Options                            inetcpl.cpl
iSCSI Initiator Configuration Tool          iscsicpl
Language Pack Installer                     lpksetup
Local Group Policy Editor                   gpedit.msc
Local Security Policy                       secpol.msc
Local Users and Groups                      lusrmgr.msc
Location Activity                           locationnotifications
Magnifier                                   magnify
Malicious Software Removal Tool             mrt
Manage Your File Encryption Certificates    rekeywiz
Math Input Panel                            mip
Microsoft Management Console                mmc
Microsoft Support Diagnostic Tool           msdt
Mouse                                       main.cpl
NAP Client Configuration                    napclcfg.msc
Narrator                                    narrator
Network Connections                         ncpa.cpl
New Scan Wizard                             wiaacmgr
Notepad                                     notepad
ODBC Data Source Administrator              odbcad32
ODBC Driver Configuration                   odbcconf
On-Screen Keyboard                          osk
Paint                                       mspaint
Pen and Touch                               tabletpc.cpl
People Near Me                              collab.cpl
Performance Monitor                         perfmon.msc
Performance Options                         systempropertiesperformance
Phone and Modem                             telephon.cpl
Phone Dialer                                dialer
Power Options                               powercfg.cpl
Presentation Settings                       presentationsettings
Print Management                            printmanagement.msc
Printer Migration                           printbrmui
Printer User Interface                      printui
Private Character Editor                    eudcedit
Problem Steps Recorder                      psr
Programs and Features                       appwiz.cpl
Protected Content Migration                 dpapimig
Region and Language                         intl.cpl
Registry Editor                             regedit
Registry Editor 32                          regedt32
Remote Access Phonebook                     rasphone
Remote Desktop Connection                   mstsc
Resource Monitor                            resmon
Resultant Set of Policy                     rsop.msc
SAM Lock Tool                               syskey
Screen Resolution                           desk.cpl
Securing the Windows Account Database       syskey
Services                                    services.msc
Set Program Access and Computer Defaults    computerdefaults
Share Creation Wizard                       shrpubw
Shared Folders                              fsmgmt.msc
Snipping Tool                               snippingtool
Sound                                       mmsys.cpl
Sound recorder                              soundrecorder
SQL Server Client Network Utility           cliconfg
Sticky Notes                                stikynot
Stored User Names and Passwords             credwiz
Sync Center                                 mobsync
System Configuration                        msconfig
System Configuration Editor                 sysedit
System Information                          msinfo32
System Properties                           sysdm.cpl
System Properties   (Advanced Tab)          systempropertiesadvanced
System Properties (Computer Name Tab)       systempropertiescomputername
System Properties (Hardware Tab)            systempropertieshardware
System Properties (Remote Tab)              systempropertiesremote
System Properties (System Protection Tab)   systempropertiesprotection
System Restore                              rstrui
Task Manager                                taskmgr
Task Scheduler                              taskschd.msc
Trusted Platform Module (TPM) Management    tpm.msc
User Account Control Settings               useraccountcontrolsettings
Utility Manager                             utilman
Version Reporter Applet                     winver
Volume Mixer                                sndvol
Windows Action Center                       wscui.cpl
Windows Activation Client                   slui
Windows Anytime Upgrade Results             windowsanytimeupgraderesults
Windows CardSpace                           infocardcpl.cpl
Windows Disc Image Burning Tool             isoburn
Windows DVD Maker                           dvdmaker
Windows Easy Transfer                       migwiz
Windows Explorer                            explorer
Windows Fax and Scan                        wfs
Windows Features                            optionalfeatures
Windows Firewall                            firewall.cpl
Windows Firewall with Advanced Security     wf.msc
Windows Journal                             journal
Windows Media Player                        wmplayer
Windows Memory Diagnostic Scheduler         mdsched
Windows Mobility Center                     mblctr
Windows Picture Acquisition Wizard          wiaacmgr
Windows PowerShell                          powershell
Windows PowerShell ISE                      powershell_ise
Windows Remote Assistance                   msra
Windows Repair Disc                         recdisc
Windows Script Host                         wscript
Windows Update                              wuapp
Windows Update Standalone Installer         wusa
Windows Vesrion                             winver
WMI Management                              wmimgmt.msc
WordPad                                     write
XPS Viewer                                  xpsrchvw

Source List of Run Commands in Windows 7 and 8


text:
Q: Snapping issue in QGIS I had drafted a polyline with QGIS, I want to continue that line with snapping from it's end, but snapping is not working in starting, after starting I am getting snapping.
Using windowsXp and Q gis 1.8.0
My issue is I had drafted a line and finished entering all attributes then i wan't to start a new line from the end point of first one there i didn't getting snapping.If i had started drafting with out snapping, second pic i can get snapping where i first wish to snap.


text:
Q: Clojure Loop Function Only Returns Nil The function below splits the text variable into a sequence of characters that is steps long. The only problem is I can't figure out how to return the resulting list, which I need to compute its Shannon entropy for several values of step.
(defn split-text [text step]

  (loop [i 0 result []]
    (when (<= (+ i step) (count text))
      (recur (+ i step)
             (conj result (subs text i (+ i step)))))))

A: You need to return the result from the loop:
(defn split-text [text step]
  (loop [i 0 result []]
    (if (> (+ i step) (count text))
      result  ;; <== here
      (recur (+ i step)
             (conj result (subs text i (+ i step)))))))

Also, the last chunk will be lost if it's less than step characters long. If you want to keep it:
(defn split-text [text step]
  (loop [tail text result []]
    (if (empty? tail)
      result
      (let [len (min step (count tail))]
        (recur (subs tail len)
               (conj result (subs tail 0 len)))))))


text:
Q: Visual Studio : Generate VB.Net code from Class Diagram Is it possible to generate VB.Net code from class diagrams in Visual Studio ?
I'm trying to do it but I could generate only C# code and I didn't find where this can possibly be configured.
Is that possible please ?
Here is a video of what's happening actually.
Video
Thanks.


text:
Q: Populating Navigation Properties Collection Lazy I have two related classes in a one-to-many relationship. I can access the Class property in one of the classes, but not the other.
Here are my classes:
 public  class Seccion
    {

        public int Id { get; set; }
        public string  Nombre { get; set; }
       public  ICollection<TipoCaracteristica> TiposCaracteristicas;

    }

    public class TipoCaracteristica
    {
        public int Id { get; set; }
        public int SeccionId { get; set; }
        [ForeignKey("SeccionId")]
        public Seccion Seccion { get; set; }
        public List<CaracteristicaAdicional> Caracteristicas;
    }

With this code i can include the Seccion properties
 public IQueryable<TipoCaracteristica> GetTipoCaracteristicas
        {
            get { return db.TipoCaracteristicas.Include("Seccion"); }

        }

I haven't been able to get a list of Seccion that includs the list of TipoCaracteristicas. I also need to get the list of Caracteristicas for each TipoCaracteristicas.
This is what I'm trying
public IQueryable<Seccion> GetSecciones
        {
            get { return db.Secciones.Include("TiposCaracteristicas"); }
        }

But I get this error:

A specified Include path is not valid. The EntityType
  'Seccion' does not declare a navigation property
  with the name 'TiposCaracteristicas'.

How can I do this? Can I include the other level too?
Thanks in advance for your time.

A: What you need to do is inform Entity Framework that your properties are Navigation Properties by using the virtual keyword. You also need to provide the access modifiers:
public virtual ICollection<TipoCaracteristica> TiposCaracteristicas { get; set; }


text:
Q: Swift SKShapeNode not accepting initialiser I can't get the a sub class of SKShapeNode to accept an initialiser. To work around this I've tried to go by the example posted here Adding Convenience Initializers in Swift Subclass. The code i'm using is below.
class Ground1 : SKShapeNode {

override init() {
    super.init()
    print("Hello1")
}

convenience init(width: CGFloat, point: CGPoint) {
    var points = [CGPoint(x: -900, y: -300),
                  CGPoint(x: -600, y: -100),
                  CGPoint(x: -100, y: -300),
                  CGPoint(x: 2, y: 150),
                  CGPoint(x: 100, y: -300),
                  CGPoint(x: 600, y: -100),
                  CGPoint(x: 900, y: -300)]
    self.init(splinePoints: &points, count: points.count)
    lineWidth = 5
    strokeColor = UIColor.orange
    physicsBody = SKPhysicsBody(edgeChainFrom: path!)
    physicsBody?.restitution = 0.75
    physicsBody?.isDynamic = false
    print("Hello2")
}

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

}
When initialised the convenience init() is ignored and not used. Resulting in no shape being added to the scene. What am I doing wrong ?

A: Thanks to 0x141E, who roundabout pointed me in the right direction. I found this worked but the code looks messy. The reasons for going about the initialisation this way is explained in detail here Adding Convenience Initializers in Swift Subclass. Although I was thrown out of finding a solution because of the use of splinePoints and assigning to a path.
class Ground1 : SKShapeNode {

    override init() {
        super.init()
    }

    convenience init(name: String) {
        var points = [CGPoint(x: -900, y: -300),
                      CGPoint(x: -600, y: -100),
                      CGPoint(x: -100, y: -300),
                      CGPoint(x: 2, y: 150),
                      CGPoint(x: 100, y: -300),
                      CGPoint(x: 600, y: -100),
                      CGPoint(x: 900, y: -300)]
        self.init(splinePoints: &points, count: points.count)
        lineWidth = 5
        strokeColor = UIColor.orange
        physicsBody = SKPhysicsBody(edgeChainFrom: self.path!)
        physicsBody?.restitution = 0.75
        physicsBody?.isDynamic = false
    }

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