答:
On Python 2 and 3 you could use a multiprocessing.ThreadPool. This is like a multiprocessing.Pool, but using threads instead of processes.

```<code>import multiprocessing

datasets = [(1,2,3), (4,5,6)]  # Iterable of datasets.

def insertfn(data):
    pass # shove data to SQL server

pool = multiprocessing.ThreadPool()

p.map(insertfn, datasets)
</code>```

By default, a Pool will create as many worker threads as your CPU has cores. Using more threads will probably not help, because they will be fighting for CPU time.

Note that I've grouped data into tuples. That is one way to get around the one argument restriction for pool workers.

On Python 3 you can also use a ThreadPoolExecutor.

Note however that on Python implementations (like the "standard" CPython) that have a Global Interpreter Lock, only one thread at a time can be executing Python bytecode. So using large numbers of threads will not automatically increase performance. Threads might help with operations that are I/O bound. If one thread is waiting for I/O, another thread can run.

Title: Execute Python threads in small groups

Body:
On Python 2 and 3 you could use a multiprocessing.ThreadPool. This is like a multiprocessing.Pool, but using threads instead of processes.

import multiprocessing

datasets = [(1,2,3), (4,5,6)]  # Iterable of datasets.

def insertfn(data):
    pass # shove data to SQL server

pool = multiprocessing.ThreadPool()

p.map(insertfn, datasets)

By default, a Pool will create as many worker threads as your CPU has cores. Using more threads will probably not help, because they will be fighting for CPU time.

Note that I've grouped data into tuples. That is one way to get around the one argument restriction for pool workers.

On Python 3 you can also use a ThreadPoolExecutor.

Note however that on Python implementations (like the "standard" CPython) that have a Global Interpreter Lock, only one thread at a time can be executing Python bytecode. So using large numbers of threads will not automatically increase performance. Threads might help with operations that are I/O bound. If one thread is waiting for I/O, another thread can run.


来源: stackexchange

问:
Custom view being drawn sometimes
I have a custom view, that is sometimes being drawn and sometimes not .. this is reproduce-able across multiple phone.

Don't know why this is happening .. setDimensions() is being called during the onMeasure call of a GalleryGridElement (relative layout) which I use as gallery elements in my recyclerview.

One example would be .. going into the recycler view gallery activity, the circular progress view is there .. when you leave the activity and come back .. onResume creates a new adapter and gives it to the recycler view .. however the circular progress views don't show this time:

```<code>public class CircularProgressView extends View {

private Paint mIndicatorColour;
private RectF mIndicatorRect;
private Paint mBackCircleColour;

private static final float START_ANGLE = -90;
private volatile float mStopAngle = 0;

private float mOutterCircleStrokeWidth = 20;
private float mInnerCircleStrokeWidth = 16;

private float mViewWidth = 0, mViewHeight = 0;
private volatile int mCurrentProgress = 0;

private ExecutorService mExecutorService;

public CircularProgressView(Context context) {
    super(context);
    setUp();
}

public CircularProgressView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setUp();
}

public CircularProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    setUp();
}

private void setUp(){

    mIndicatorRect = new RectF(0,0,300,300);

    mIndicatorColour = new Paint();
    mIndicatorColour.setColor(Color.parseColor("#D62F85"));
    mIndicatorColour.setStyle(Paint.Style.STROKE);
    mIndicatorColour.setStrokeWidth(mInnerCircleStrokeWidth);
    mIndicatorColour.setAntiAlias(true);
    mIndicatorColour.setDither(true);
    mIndicatorColour.setStrokeJoin(Paint.Join.ROUND);
    mIndicatorColour.setStrokeCap(Paint.Cap.ROUND);

    mBackCircleColour = new Paint();
    mBackCircleColour.setColor(Color.WHITE);
    mBackCircleColour.setStyle(Paint.Style.STROKE);
    mBackCircleColour.setStrokeWidth(mOutterCircleStrokeWidth);
    mBackCircleColour.setAntiAlias(true);
    mBackCircleColour.setDither(true);
    mBackCircleColour.setStrokeJoin(Paint.Join.ROUND);
    mBackCircleColour.setStrokeCap(Paint.Cap.ROUND);

    mExecutorService = Executors.newSingleThreadExecutor();

}

public void setDimensions(float width, int scaleCircleThicknessValue){
    mViewHeight = width;
    mViewWidth = width;
    mIndicatorRect.left = mIndicatorRect.top = mOutterCircleStrokeWidth;
    mIndicatorRect.right = mIndicatorRect.bottom = width - mOutterCircleStrokeWidth;
    mIndicatorColour.setStrokeWidth(mInnerCircleStrokeWidth);
    mBackCircleColour.setStrokeWidth(mOutterCircleStrokeWidth);

    mInnerCircleStrokeWidth = (0.1f * scaleCircleThicknessValue) * width;
    mOutterCircleStrokeWidth = mInnerCircleStrokeWidth + 5;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int desiredWidth = Math.round(mViewWidth);
    int desiredHeight = Math.round(mViewHeight);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //Set values
    setMeasuredDimension(width, height);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawArc(mIndicatorRect, 0, 360, false, mBackCircleColour);
    canvas.drawArc(mIndicatorRect, START_ANGLE, mStopAngle, false, mIndicatorColour);
}

public synchronized void setProgress(final int progress) {

    if ((mCurrentProgress != progress) && (progress > 0)) {

        mCurrentProgress = progress;

        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {

                final float currentAngle = mStopAngle;

                float newAngle = (360f * ((float) progress / 100f));

                float step = (Math.round(newAngle) - Math.round(currentAngle)) <= 1 ? 1 : (newAngle - currentAngle)/5f;

                if (step < 0.01) {
                    newAngle = 359;
                }

                for (float i = currentAngle; i < newAngle; i += step) {
                    try {
                        mStopAngle = i;
                        postInvalidate();
                        Thread.sleep(1000 / 60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        });

    }
}

public float getProgress(){
    return (360f-mStopAngle) < 1f ? 1 : mStopAngle / 360f;
}

}
</code>```

答:
Just following up on this incase someone runs into this issue:

Since I am using a custom view inside a custom view with the recycler view.
When I bind the view-holder to model, I make sure to completely re-render the view ... ie :

```<code>    mCircularProgressView.setVisibility(VISIBLE);
    mCircularProgressView.setDimensions(getWidth() * 0.82f, 1);
    mCircularProgressView.requestLayout();
    mCircularProgressView.postInvalidate();
</code>```

This makes sure the view is drawn no matter what.

ContentLicense: CC BY-SA 3.0

Title: Custom view being drawn sometimes

Body:
I have a custom view, that is sometimes being drawn and sometimes not .. this is reproduce-able across multiple phone.

Don't know why this is happening .. setDimensions() is being called during the onMeasure call of a GalleryGridElement (relative layout) which I use as gallery elements in my recyclerview.

One example would be .. going into the recycler view gallery activity, the circular progress view is there .. when you leave the activity and come back .. onResume creates a new adapter and gives it to the recycler view .. however the circular progress views don't show this time:

public class CircularProgressView extends View {

private Paint mIndicatorColour;
private RectF mIndicatorRect;
private Paint mBackCircleColour;

private static final float START_ANGLE = -90;
private volatile float mStopAngle = 0;

private float mOutterCircleStrokeWidth = 20;
private float mInnerCircleStrokeWidth = 16;

private float mViewWidth = 0, mViewHeight = 0;
private volatile int mCurrentProgress = 0;

private ExecutorService mExecutorService;

public CircularProgressView(Context context) {
    super(context);
    setUp();
}

public CircularProgressView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setUp();
}

public CircularProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    setUp();
}

private void setUp(){

    mIndicatorRect = new RectF(0,0,300,300);

    mIndicatorColour = new Paint();
    mIndicatorColour.setColor(Color.parseColor("#D62F85"));
    mIndicatorColour.setStyle(Paint.Style.STROKE);
    mIndicatorColour.setStrokeWidth(mInnerCircleStrokeWidth);
    mIndicatorColour.setAntiAlias(true);
    mIndicatorColour.setDither(true);
    mIndicatorColour.setStrokeJoin(Paint.Join.ROUND);
    mIndicatorColour.setStrokeCap(Paint.Cap.ROUND);

    mBackCircleColour = new Paint();
    mBackCircleColour.setColor(Color.WHITE);
    mBackCircleColour.setStyle(Paint.Style.STROKE);
    mBackCircleColour.setStrokeWidth(mOutterCircleStrokeWidth);
    mBackCircleColour.setAntiAlias(true);
    mBackCircleColour.setDither(true);
    mBackCircleColour.setStrokeJoin(Paint.Join.ROUND);
    mBackCircleColour.setStrokeCap(Paint.Cap.ROUND);

    mExecutorService = Executors.newSingleThreadExecutor();

}

public void setDimensions(float width, int scaleCircleThicknessValue){
    mViewHeight = width;
    mViewWidth = width;
    mIndicatorRect.left = mIndicatorRect.top = mOutterCircleStrokeWidth;
    mIndicatorRect.right = mIndicatorRect.bottom = width - mOutterCircleStrokeWidth;
    mIndicatorColour.setStrokeWidth(mInnerCircleStrokeWidth);
    mBackCircleColour.setStrokeWidth(mOutterCircleStrokeWidth);

    mInnerCircleStrokeWidth = (0.1f * scaleCircleThicknessValue) * width;
    mOutterCircleStrokeWidth = mInnerCircleStrokeWidth + 5;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int desiredWidth = Math.round(mViewWidth);
    int desiredHeight = Math.round(mViewHeight);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //Set values
    setMeasuredDimension(width, height);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawArc(mIndicatorRect, 0, 360, false, mBackCircleColour);
    canvas.drawArc(mIndicatorRect, START_ANGLE, mStopAngle, false, mIndicatorColour);
}

public synchronized void setProgress(final int progress) {

    if ((mCurrentProgress != progress) && (progress > 0)) {

        mCurrentProgress = progress;

        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {

                final float currentAngle = mStopAngle;

                float newAngle = (360f * ((float) progress / 100f));

                float step = (Math.round(newAngle) - Math.round(currentAngle)) <= 1 ? 1 : (newAngle - currentAngle)/5f;

                if (step < 0.01) {
                    newAngle = 359;
                }

                for (float i = currentAngle; i < newAngle; i += step) {
                    try {
                        mStopAngle = i;
                        postInvalidate();
                        Thread.sleep(1000 / 60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        });

    }
}

public float getProgress(){
    return (360f-mStopAngle) < 1f ? 1 : mStopAngle / 360f;
}

}

Body:
Just following up on this incase someone runs into this issue:

Since I am using a custom view inside a custom view with the recycler view.
When I bind the view-holder to model, I make sure to completely re-render the view ... ie :

    mCircularProgressView.setVisibility(VISIBLE);
    mCircularProgressView.setDimensions(getWidth() * 0.82f, 1);
    mCircularProgressView.requestLayout();
    mCircularProgressView.postInvalidate();

This makes sure the view is drawn no matter what.


问:
Implement INotifyPropertyChanged on generated Entity Framework classes
I have an SQL DB and am implementing a WPF UI to update it. If I use EF5 to generate the classes from the DB, how can I implement INotifyPropertyChanged on the generated classes and properties so I can easily bind to them with the UI? Is there an easy way to achieve this?

Thanks

答: Make all your EF generated classes inherit from a class which implements the INotifyPropertyChanged interface (using the non-generated partial classes you probably already defined). Add a method to this base class, which raises the PropertyChanged event with an empty string as PropertyName. Then, every time you call this method on an EF generated class instance, all its modified properties will be refreshed in your WPF UI.


问:
CakePHP3: how to pass parameter to join()?
I have a DefaultPermissions table, so with a  default permissions set, and I want to compare this set with a permissions set affected to a specific site to see if additionnal default permissions exist.

So I wrote the following query:

```<code>$defaultPermissions = $this->DefaultPermissions
->find()
->select([
    'user_id' => $selUser->id,
    'role',
    'sequence',
    'product',
    'module',
    'item',
    'value',
    'visible',
    'editable'
])
->join([
    'p' => [
        'table' => 'permissions',
        'type' => 'LEFT',
        'conditions' => [
            'p.product = DefaultPermissions.product',
            'p.module = DefaultPermissions.module',
            'p.item = DefaultPermissions.item',
            'p.site_id' => $selSite->id   // My problem is here!
        ]
    ]
],
[
    'p.product' => 'varchar',
    'p.module' => 'varchar',
    'p.item' => 'varchar',
    'p.site_id' => 'integer'
])
->where([
    'DefaultPermissions.role' => $selUser->role,
    'p.item IS' => NULL, // item doit toujours être présent donc si null, la ligne est absente.
    'OR' => [['DefaultPermissions.product' => $agplan->product->code], ['DefaultPermissions.product' => '']]
])
->all();
</code>```

But despite all defaultPermissions can be found for siteselSite->id, the query gives the complete list existing in DefaultPermissions table.
If I remove the line 'p.site_id' => $selSite->id the list is empty as expected so I conclude that the passed parameter is not well interpreted.

How to do it?

答:
There was just a syntax error in the join:</p>

```<code>->join([
    'p' => [
        'table' => 'permissions',
        'type' => 'LEFT',
        'conditions' => [
            'p.product = DefaultPermissions.product',
            'p.module = DefaultPermissions.module',
            'p.item = DefaultPermissions.item',
            'p.site_id = ' => $selSite->id   // '=' was missing
        ]
    ]
],
....
</code>```

Body:
I have a DefaultPermissions table, so with a  default permissions set, and I want to compare this set with a permissions set affected to a specific site to see if additionnal default permissions exist.

So I wrote the following query:

$defaultPermissions = $this->DefaultPermissions
->find()
->select([
    'user_id' => $selUser->id,
    'role',
    'sequence',
    'product',
    'module',
    'item',
    'value',
    'visible',
    'editable'
])
->join([
    'p' => [
        'table' => 'permissions',
        'type' => 'LEFT',
        'conditions' => [
            'p.product = DefaultPermissions.product',
            'p.module = DefaultPermissions.module',
            'p.item = DefaultPermissions.item',
            'p.site_id' => $selSite->id   // My problem is here!
        ]
    ]
],
[
    'p.product' => 'varchar',
    'p.module' => 'varchar',
    'p.item' => 'varchar',
    'p.site_id' => 'integer'
])
->where([
    'DefaultPermissions.role' => $selUser->role,
    'p.item IS' => NULL, // item doit toujours être présent donc si null, la ligne est absente.
    'OR' => [['DefaultPermissions.product' => $agplan->product->code], ['DefaultPermissions.product' => '']]
])
->all();

But despite all defaultPermissions can be found for siteselSite->id, the query gives the complete list existing in DefaultPermissions table.
If I remove the line 'p.site_id' => $selSite->id the list is empty as expected so I conclude that the passed parameter is not well interpreted.

How to do it?

Body:
There was just a syntax error in the join:

->join([
    'p' => [
        'table' => 'permissions',
        'type' => 'LEFT',
        'conditions' => [
            'p.product = DefaultPermissions.product',
            'p.module = DefaultPermissions.module',
            'p.item = DefaultPermissions.item',
            'p.site_id = ' => $selSite->id   // '=' was missing
        ]
    ]
],
....


问:
How to import KML with osmdroid?
I have project that need show KML in maps, i already done it in google maps, but it seem too slow and sometimes it force close.
I have searched it, they need convert the KML to GPX, isn't it same like KML or different?

Now i try osmdroid for other solution, but there is few references about importing KML with osmdroid.
Do you know how i can import KML with osmdroid?

答: osmbonuspack can handle KML files. See Tutorial 4 for an example on how to show a KML file on your map.</p>

Title: How to import KML with osmdroid?


问:
My Tomcat is not running it just open and close when I click on tomcat7.exe
I am installing Tomcat 7 in my PC it works in Eclipse but when I try to open in bin/ tomcat7.exe  it just open and closes, (I am stopping the server in Eclipse). Also, in Eclipse I'am trying to open admin console like URL:(localhost:1234/admin) it shows 404 error. Can anyone who knows this problem explain a solution?

答: the JAVA_HOME and JRE_HOME environment variables set should not have semicolon or ; at the end...I was facing similar problem...removed semi-colon or ; from the end and tomcat server started from cmd screen after running startup command(of tomcat..bin folder).</p>

ContentLicense: CC BY-SA 4.0


问:
C#: Is it necessary to dispose of a graphics element inside a custom control?
I've created a custom control, overridden it's paint event. When I try to dispose of the graphics I create they just disappear from the screen. Don't I need to use dispose in custom controls?

EDIT: I've included a code snippet. Why can't i dispose the dc graphics object, created from the PaintEventArgs? Do i need to dispose it?

```<code>class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        Graphics _dc;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
            this.Paint += new PaintEventHandler(ctrl_Paint);
        }

        private void ctrl_Paint(object sender, PaintEventArgs e)
        {

            Graphics dc = e.Graphics;
            _dc = dc;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}
</code>```

答: You should be disposing any controls within your custom control that implement the IDisposable interface. Ensure that your custom control implements this interface as well (add an implementation of the Dispose() method) so that you dispose of the controls within it properly (calling their Dispose() methods).

Body:
I've created a custom control, overridden it's paint event. When I try to dispose of the graphics I create they just disappear from the screen. Don't I need to use dispose in custom controls?

EDIT: I've included a code snippet. Why can't i dispose the dc graphics object, created from the PaintEventArgs? Do i need to dispose it?

class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        Graphics _dc;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
            this.Paint += new PaintEventHandler(ctrl_Paint);
        }

        private void ctrl_Paint(object sender, PaintEventArgs e)
        {

            Graphics dc = e.Graphics;
            _dc = dc;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}

ContentLicense: CC BY-SA 2.5


问:
Segmentation Fault - Difficulty with assigning a class
I am trying to assign my class DictObj to create a new instance of the class. What it wants to do, is to have a pointer to the class created, rather than the actual Object.

If I am to do what it likes, and have:
DictObj * d;, and then say something like, "d->load();", it gives me difficulty when assigning a string to a string. Such as with, assuming word is of type string, word = a;, where a is also a string passed as a parameter of the same type (no pointers or references). It gives me a segmentation fault when I do this.

Any suggestions as to how to fix this problem? Below, I will show a sample of the code:

P.S. I know I am  adding "Dicts.cpp", even though I am not supposed to. It is giving me an error of

/tmp/ccEFPwDS.o: In function 'main':
  /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW/main.cpp:60: undefined reference to DictObj::load()

ACTUAL CODE:

```<code>#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<thread>
#include<cassert>
#include<exception>
#include"Directory.hpp"
#include"Dicts.cpp"
#include"Tests.hpp"

int main() {
  cout << "Hello\n\n";
  DictObj * d;
  d->load();
  return 0;
}
</code>```

Here is Dicts.cpp

```<code>void DictObj::setW(string a)
{
    word = a;
}
</code>```

This gives me a segmentation fault when it runs the method:

```<code>void DictObj::load()
{
    string temp;
    cout <<"Type New Word: ";
    getline(cin, temp);
    cin >> temp;

    setW(temp);
</code>```

the code goes on, but the error is at "setW(temp)"

IF I try to make a new DictObj in the main class, as expected, then it gives me an error

Code:

```<code>int main() {
    cout << "Hello\n\n";
    DictObj d = new DictObj();
    d.load();
    return 0;
}
</code>```

Error:

```<code>g++ -std=c++14 -Wall -c "main.cpp" (in directory:         /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW)
main.cpp: In function ‘int main()’:
main.cpp:59:26: error: conversion from ‘DictObj*’ to non-scalar type     ‘DictObj’ requested
  DictObj d = new DictObj();
                      ^
Compilation failed.
</code>```

ALSO: My compilation code is as follows (I am using Geany)

g++ -std=c++14 -Wall -c "%f"

My Build code is as follows:

g++ -g -std=c++14 -Wall -Wextra -pedantic -lpthread  -o "%e"  "%f"

DEFINITION of DictObj class:

```<code>class DictObj
{
    public:
       DictObj();
       DictObj(const DictObj&);
       void load();
       void setW(string);
   private:
       string word;
};
</code>```

答:
Your first version DictObj * d; d->load(); crashes since you dereference non-initialized pointer d. Hence, since d does not point to a valid object, d->load() will result in undefined behaviour (and most likely in a crash).

Your second version simply does not compile because you assign a pointer value to an object value. Write either DictObj* d = new DictObj(); d->load() or DictObj d; d.load().

See the following code, which compiles and does not crash:

```<code>#include <iostream>

using std::string;

class DictObj
{
public:
    DictObj() {};
    DictObj(const DictObj&);
    void load() {
        string temp;
        std::cout <<"Type New Word: ";
        getline(std::cin, temp);
        std::cin >> temp;
        setW(temp);
    };
    void setW(string a)
        {
            word = a;
        };

private:
    string word;
};

int main(int argc, char* argv[]) {

    DictObj d;
    d.load();
    return 0;
}
</code>```

Body:
I am trying to assign my class DictObj to create a new instance of the class. What it wants to do, is to have a pointer to the class created, rather than the actual Object.

If I am to do what it likes, and have:
DictObj * d;, and then say something like, "d->load();", it gives me difficulty when assigning a string to a string. Such as with, assuming word is of type string, word = a;, where a is also a string passed as a parameter of the same type (no pointers or references). It gives me a segmentation fault when I do this.

Any suggestions as to how to fix this problem? Below, I will show a sample of the code:

P.S. I know I am  adding "Dicts.cpp", even though I am not supposed to. It is giving me an error of

/tmp/ccEFPwDS.o: In function 'main':
  /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW/main.cpp:60: undefined reference to DictObj::load()

ACTUAL CODE:

#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<thread>
#include<cassert>
#include<exception>
#include"Directory.hpp"
#include"Dicts.cpp"
#include"Tests.hpp"

int main() {
  cout << "Hello\n\n";
  DictObj * d;
  d->load();
  return 0;
}

Here is Dicts.cpp

void DictObj::setW(string a)
{
    word = a;
}

This gives me a segmentation fault when it runs the method:

void DictObj::load()
{
    string temp;
    cout <<"Type New Word: ";
    getline(cin, temp);
    cin >> temp;

    setW(temp);

the code goes on, but the error is at "setW(temp)"

IF I try to make a new DictObj in the main class, as expected, then it gives me an error

Code:

int main() {
    cout << "Hello\n\n";
    DictObj d = new DictObj();
    d.load();
    return 0;
}

Error:

g++ -std=c++14 -Wall -c "main.cpp" (in directory:         /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW)
main.cpp: In function ‘int main()’:
main.cpp:59:26: error: conversion from ‘DictObj*’ to non-scalar type     ‘DictObj’ requested
  DictObj d = new DictObj();
                      ^
Compilation failed.

ALSO: My compilation code is as follows (I am using Geany)

g++ -std=c++14 -Wall -c "%f"

My Build code is as follows:

g++ -g -std=c++14 -Wall -Wextra -pedantic -lpthread  -o "%e"  "%f"

DEFINITION of DictObj class:

class DictObj
{
    public:
       DictObj();
       DictObj(const DictObj&);
       void load();
       void setW(string);
   private:
       string word;
};

Body:
Your first version DictObj * d; d->load(); crashes since you dereference non-initialized pointer d. Hence, since d does not point to a valid object, d->load() will result in undefined behaviour (and most likely in a crash).

Your second version simply does not compile because you assign a pointer value to an object value. Write either DictObj* d = new DictObj(); d->load() or DictObj d; d.load().

See the following code, which compiles and does not crash:

#include <iostream>

using std::string;

class DictObj
{
public:
    DictObj() {};
    DictObj(const DictObj&);
    void load() {
        string temp;
        std::cout <<"Type New Word: ";
        getline(std::cin, temp);
        std::cin >> temp;
        setW(temp);
    };
    void setW(string a)
        {
            word = a;
        };

private:
    string word;
};

int main(int argc, char* argv[]) {

    DictObj d;
    d.load();
    return 0;
}


问:
Bootstrap Carousel Indicators Color change for 1 slide
I am using the default bootstrap carousel. But one of my slides has a white background so the carousel indicators disappear on that slide. I have Javascript/jQuery solution that works, but it seems a tiny bit slow/clunky. Any help either to improve the script or an alternative solution, would be appreciated.</p>

```<code>$('#carousel-generic').on('slid.bs.carousel', function (evt) {
    var elem = $(this).find('.carousel-indicators li');
    var active = $(this).find('.carousel-indicators .active');
    if(active.index() == 2) {
        elem.css('border-color', 'grey');
        elem.css('background-color', 'rgba(0,0,0,0)');
        active.css('background-color', 'grey');
    } else {
        elem.css('border-color', 'white');
        elem.css('background-color', 'rgba(0,0,0,0)');
        active.css('background-color', 'white');
    }
})
</code>```

答:
A simple solution </p>

```<code>.carousel-indicators li {
    background-color: #669966;
}

.carousel-indicators .active {
    background-color: #FF7600;
}
</code>```

Body:
I am using the default bootstrap carousel. But one of my slides has a white background so the carousel indicators disappear on that slide. I have Javascript/jQuery solution that works, but it seems a tiny bit slow/clunky. Any help either to improve the script or an alternative solution, would be appreciated.

$('#carousel-generic').on('slid.bs.carousel', function (evt) {
    var elem = $(this).find('.carousel-indicators li');
    var active = $(this).find('.carousel-indicators .active');
    if(active.index() == 2) {
        elem.css('border-color', 'grey');
        elem.css('background-color', 'rgba(0,0,0,0)');
        active.css('background-color', 'grey');
    } else {
        elem.css('border-color', 'white');
        elem.css('background-color', 'rgba(0,0,0,0)');
        active.css('background-color', 'white');
    }
})

Body:
A simple solution

.carousel-indicators li {
    background-color: #669966;
}

.carousel-indicators .active {
    background-color: #FF7600;
}


问:
Finding Multiple Values in Google Spread-Sheets
I have a list of roughly 800 VIN numbers that are each in a separate cell. I can and have already created a partial list of these so that they are separated by a comma thinking the find function would be able to highlight multiple cells if comma delineated, but this did not work. Instead of going one by one and using copy/paste plus find to locate each VIN in the second spreadsheet (which is understandably quite tedious and time consuming) I have been trying to find a way so that I can find multiple cells at once. Ex: 123456789, 234567891, 345678912, etc. so that each cell that contains those values will be located. I have tried the power tools improved search function by Adlebits, but it does not have this capability, which leads me to believe the only possible way to achieve this would be through the script editor, if at all. Any recommendations?</p>

答:
Try breaking the comma separated list into separate cells and then use conditional formatting to highlight the values. Have a look at my example.

https://docs.google.com/spreadsheets/d/1YBsUz96yN7rxYFjnYI94lAGPMOUS2ScHD2SW417VEeY/copy?usp=sharing


问:
remove all elements from a linked list without .clear() java
I want to remove all of the elements in my linked list without using the clear method.

This is my code currently

```<code>//-----inner class-----
private static class Node <T> {
  private T data;
  //next just points
  private Node<T> next;

  //constructs a node
  public Node(T data, Node<T> next){
     this.data = data;
     this.next = next;
  }

  public T getData(){ return data;}

  public Node<T> getNext(){ return next;}
</code>```

}

```<code> private LinkedList<T> theList = new LinkedList<T>();
 private Node<T> head;
 private Node<T> tail = null;
 private int size=0;

public ListNoOrder() {
   this.head = null;
   size = 0;
}

//an add method
public void add(T newElt) {
  //if the new element equals null
  //catch the exception
  try{ if (newElt==(null));}
  catch (Exception illegalArgumentException){
     throw new IllegalArgumentException();}

  //if it doesn't catch an exception it adds the element to the list
  //and increment the size by one

  //what does the head = new Node<T>(newElt, head) mean???
  head = new Node<T>(newElt, head);
  size++;
}
</code>```

The reset method that I want to implement
If my current list has four objects after calling this method I want that list to have 0 objects

```<code>public void reset() {
     head = null;
 }
</code>```

It should work but everytime I test it says nothing's been deleted. This is just bits and pieces of the complete code.

答:
```<code>public void reset() {
     head = null;
 }
</code>```

(You)

It should work but everytime I test it says nothing's been deleted. This is just bits and pieces of the complete code

(My comment)

You  remove the reference to the first element of the list so then if are no reference this list exist  only in memory of JVM and Garbage Colletor will remove it from memory, but you don't set the size to zero (size=0;) and when test or somthing else will check the list it stil informs that have for eg "size = 6". From the other side you have function that is reset your list

```<code>public ListNoOrder() {
   this.head = null;
   size = 0;
}
</code>```

All comments written in BrokenEnglish :)

Body:
I want to remove all of the elements in my linked list without using the clear method.

This is my code currently

//-----inner class-----
private static class Node <T> {
  private T data;
  //next just points
  private Node<T> next;

  //constructs a node
  public Node(T data, Node<T> next){
     this.data = data;
     this.next = next;
  }

  public T getData(){ return data;}

  public Node<T> getNext(){ return next;}

}

 private LinkedList<T> theList = new LinkedList<T>();
 private Node<T> head;
 private Node<T> tail = null;
 private int size=0;

public ListNoOrder() {
   this.head = null;
   size = 0;
}

//an add method
public void add(T newElt) {
  //if the new element equals null
  //catch the exception
  try{ if (newElt==(null));}
  catch (Exception illegalArgumentException){
     throw new IllegalArgumentException();}

  //if it doesn't catch an exception it adds the element to the list
  //and increment the size by one

  //what does the head = new Node<T>(newElt, head) mean???
  head = new Node<T>(newElt, head);
  size++;
}

The reset method that I want to implement
If my current list has four objects after calling this method I want that list to have 0 objects

public void reset() {
     head = null;
 }

It should work but everytime I test it says nothing's been deleted. This is just bits and pieces of the complete code.

Body:
public void reset() {
     head = null;
 }

(You)

It should work but everytime I test it says nothing's been deleted. This is just bits and pieces of the complete code

(My comment)

You  remove the reference to the first element of the list so then if are no reference this list exist  only in memory of JVM and Garbage Colletor will remove it from memory, but you don't set the size to zero (size=0;) and when test or somthing else will check the list it stil informs that have for eg "size = 6". From the other side you have function that is reset your list

public ListNoOrder() {
   this.head = null;
   size = 0;
}

All comments written in BrokenEnglish :)


问:
How can you read just the first word of every line of file using python?
What's the most efficient way to read just the first word of every line in a large text file? Should I use split? Is there a more efficient way? Can I just read one word and discard the line and go to the next line?
Right now I'm using this:

```<code>for line in f:
    dct[line.split(None, 1)[0]] = dct.get(line.split(None, 1)[0], 0) + 1
</code>```

答: In order to determine what a "line" is, you have to read until you find a newline. You correctly identified that split() is the way to go if you want to use only the first word.

Body:
What's the most efficient way to read just the first word of every line in a large text file? Should I use split? Is there a more efficient way? Can I just read one word and discard the line and go to the next line?
Right now I'm using this:

for line in f:
    dct[line.split(None, 1)[0]] = dct.get(line.split(None, 1)[0], 0) + 1


问:
Transform bidimensional array in a multidimensional depth array in Javascript
I have a Javascript array like this:

```<code>[
    "values": [
        "Gray",
        "Beige",
        "Black"
    ],
    "values": [
        "Large",
        "Small",
        "Medium"
    ]
]
</code>```

and, I need to transform it in the following:

```<code>[
    "Gray": [
        "Large": 0,
        "Small": 0,
        "Medium": 0
    ],
    "Beige": [
        "Large": 0,
        "Small": 0,
        "Medium": 0
    ],
    "Black": [
        "Large": 0,
        "Small": 0,
        "Medium": 0
    ]:
]
</code>```

The main complexity is that the first array can have many values arrays, and I need its values become to the indexes of the new array, depthly. I am sure this can be make using a loop structure, but I am tired of trying.

I accept any solution for this, using Javascript and/or jQuery code :).

答:
First of all both arrays are invalid. You cannot have keys in an array in JavaScript.

Youre looking for either an object or a Map

So your second invalid array would be valid with being an object within an object:

```<code>{
    Gray:{
        Large: 0,
        Small: 0,
        Medium: 0
    },
    Beige:{
        Large: 0,
        Small: 0,
        Medium: 0
    },
    Black: {
        Large: 0,
        Small: 0,
        Medium: 0
    }:
}
</code>```

Problem is that, iterating over a javascript object is not simple and is not prefered for that case.

So i would go for a Map inside your first level array like so

```<code>var myMap = new Map();

var keyString = 'Gray'

// setting the values
myMap.set(keyString, { Large:0, Small:0, Medium:0 });
</code>```

And then you can loop over your map with a for of

```<code>for (var [key, value] of myMap) {
  console.log(key + ' = ' + value);
}
</code>```

Please checkout the Map Docs from MDN for more info

Body:
I have a Javascript array like this:

[
    "values": [
        "Gray",
        "Beige",
        "Black"
    ],
    "values": [
        "Large",
        "Small",
        "Medium"
    ]
]

and, I need to transform it in the following:

[
    "Gray": [
        "Large": 0,
        "Small": 0,
        "Medium": 0
    ],
    "Beige": [
        "Large": 0,
        "Small": 0,
        "Medium": 0
    ],
    "Black": [
        "Large": 0,
        "Small": 0,
        "Medium": 0
    ]:
]

The main complexity is that the first array can have many values arrays, and I need its values become to the indexes of the new array, depthly. I am sure this can be make using a loop structure, but I am tired of trying.

I accept any solution for this, using Javascript and/or jQuery code :).

Body:
First of all both arrays are invalid. You cannot have keys in an array in JavaScript.

Youre looking for either an object or a Map

So your second invalid array would be valid with being an object within an object:

{
    Gray:{
        Large: 0,
        Small: 0,
        Medium: 0
    },
    Beige:{
        Large: 0,
        Small: 0,
        Medium: 0
    },
    Black: {
        Large: 0,
        Small: 0,
        Medium: 0
    }:
}

Problem is that, iterating over a javascript object is not simple and is not prefered for that case.

So i would go for a Map inside your first level array like so

var myMap = new Map();

var keyString = 'Gray'

// setting the values
myMap.set(keyString, { Large:0, Small:0, Medium:0 });

And then you can loop over your map with a for of

for (var [key, value] of myMap) {
  console.log(key + ' = ' + value);
}

Please checkout the Map Docs from MDN for more info


问:
How to add css style to the all children of element at the same time?
Such as:

```<code><div class="mostOut">
    <div class="a">
        <h3 class="b"></h3>
        <div class="d"></div>
    </div>
</div>
</code>```

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .

答:
a little less code

```<code>$('.mostOut').click(function()
{
   $(this).children("*").css('opacity', 1);
});
</code>```

and exclude ".b"

```<code>$('.mostOut').click(function()
{
   $(this).children("*").not(".b").css('opacity', 1);
});
</code>```

or alternatively if its not the opacity causing the hidden/none

```<code>$('.mostOut').click(function()
{
   $(this).children("*").show();
});
</code>```

Body:
Such as:

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .

Body:
a little less code

$('.mostOut').click(function()
{
   $(this).children("*").css('opacity', 1);
});

and exclude ".b"

$('.mostOut').click(function()
{
   $(this).children("*").not(".b").css('opacity', 1);
});

or alternatively if its not the opacity causing the hidden/none

$('.mostOut').click(function()
{
   $(this).children("*").show();
});


问:
Why shouldn't I use the 'float' property to position my blocks?
I know the float property is not recommended for placing blocks within a page, but couldn't find any good explanation for why I shouldn't use it. I know it wasn't designed for this in the first place, but as long as it works, why shouldn't I use float positionning to layout my blocks ?

答: float is a very hacky solution. It's original design is to wrap text around an image and when used for blocks presents issues by not having that block in the page flow and requiring a clearfix, removing all hope of semantic design for that block without using shadow dom, making display:inline-block; a much more elegant and useful solution.


问:
SyntaxError: Unexpected token: punc ())
I'm recieving:

SyntaxError: Unexpected token: punc ()) from UglifyJS

and it points to the first letter of global variable API_URL.
I have it implemented in this way:

```<code>export default reduxApi({
  campaigns: {
    url: `${API_URL}/api/v1/whatever`,
    transformer (response) {
      if (!response) return {}
      return response.data
    }
  }
}).use('fetch', adapterFetch(fetch)).use('options', {
  headers: getRequestHeaders()
})
</code>```

If I remove global variable under key url:

```<code>export default reduxApi({
  campaigns: {
    url: `/api/v1/whatever`,
    transformer (response) {
      if (!response) return {}
      return response.data
    }
  }
}).use('fetch', adapterFetch(fetch)).use('options', {
  headers: getRequestHeaders()
})
</code>```

then everything works fine. Any ideas? Why uglify throws that kind of error?

答:
Uglify doesn't fully support ES6, template literals included. You can track the conversation on Github. There's a harmony branch for ES6 support. You can use the branch by replacing your package.json entry for uglify to:

```<code>"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
</code>```

Alternatively, you might want to pass the code through a transpiler first before minification. That way, all the syntax will be ES5 which Uglify understands very well. You might want to tweak your transpiler config if you want some of the ES6 syntax to remain intact.

Title: SyntaxError: Unexpected token: punc ())

Body:
I'm recieving:

SyntaxError: Unexpected token: punc ()) from UglifyJS

and it points to the first letter of global variable API_URL.
I have it implemented in this way:

export default reduxApi({
  campaigns: {
    url: `${API_URL}/api/v1/whatever`,
    transformer (response) {
      if (!response) return {}
      return response.data
    }
  }
}).use('fetch', adapterFetch(fetch)).use('options', {
  headers: getRequestHeaders()
})

If I remove global variable under key url:

export default reduxApi({
  campaigns: {
    url: `/api/v1/whatever`,
    transformer (response) {
      if (!response) return {}
      return response.data
    }
  }
}).use('fetch', adapterFetch(fetch)).use('options', {
  headers: getRequestHeaders()
})

then everything works fine. Any ideas? Why uglify throws that kind of error?

Body:
Uglify doesn't fully support ES6, template literals included. You can track the conversation on Github. There's a harmony branch for ES6 support. You can use the branch by replacing your package.json entry for uglify to:

"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"

Alternatively, you might want to pass the code through a transpiler first before minification. That way, all the syntax will be ES5 which Uglify understands very well. You might want to tweak your transpiler config if you want some of the ES6 syntax to remain intact.


答: Just use somestring.split(" ")

Title: How can you read just the first word of every line of file using python?

Body: Just use somestring.split(" ")


问:
How to split an integer separate by tab/space into an array in map using java
This is a map function. I have some random integers in Integer Value(input).

```<code>value= 1
       3
       2
       7
       9
    Integer line=value.toInteger();
    Integer[] a= line.split(" ");
</code>```

but this is not correct I want to get the output like a[]={1 3 2 7 9 }.

答:
I am not sure if I get your question right, But I think that this might work:

```<code>Integer[] a= line.split(" ");
for (i = 0; i< a.length; i++)
    Integer[i] = Integer.parseInt(Integer[i])
</code>```

Best

Body:
This is a map function. I have some random integers in Integer Value(input).

value= 1
       3
       2
       7
       9
    Integer line=value.toInteger();
    Integer[] a= line.split(" ");

but this is not correct I want to get the output like a[]={1 3 2 7 9 }.

Body:
I am not sure if I get your question right, But I think that this might work:

Integer[] a= line.split(" ");
for (i = 0; i< a.length; i++)
    Integer[i] = Integer.parseInt(Integer[i])

Best


问:
JSON error when using Retrofit with HTML
My code works fine when I remove HTML code from index.php and just keep the php lines between . But when I use the as shown down with HTML lines - which I need for other parts of the application -, it gives error:

"Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $"

I have tried to use

```<code>Gson gson = new GsonBuilder()
            .setLenient()
            .create();

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
</code>```

But it gives me another error:

"java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $"

This is my Logcat output

How to fix that?!!!

FirstPOIPreference.java:

```<code>public class FirstPOIPreference extends DialogPreference {

private EditText et_alias, et_keyword, et_address;
private Spinner sp_city;
private ArrayAdapter<String> adapter;
private boolean deleted;
private Context context;
private SharedPreferences pref;
private POI poiDialog = new POI();

public FirstPOIPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    init();
}

private void init() {
    setPersistent(false);
    setDialogLayoutResource(R.layout.pref_poi_dialog);
    setPositiveButtonText(android.R.string.ok);
    setNegativeButtonText(android.R.string.cancel);
}

@Override
protected void onBindDialogView(View view) {
    super.onBindDialogView(view);
    pref = PreferenceManager.getDefaultSharedPreferences(this.context);
    load(getSharedPreferences());
    initViews(view);
    fillViews();
}

private void load(SharedPreferences prefs) {
    poiDialog.setAlias(prefs.getString(Constants.FIRST_POI_ALIAS, ""));
    poiDialog.setKeyword(prefs.getString(Constants.FIRST_POI_KEYWORD, ""));
    poiDialog.setAddress(prefs.getString(Constants.FIRST_POI_ADDRESS, ""));
    poiDialog.setCity((prefs.getString(Constants.FIRST_POI_CITY, "")));
}

private void initViews(View view) {
    deleted = false;
    TextView tv_delete = (TextView) view.findViewById(R.id.tv_poi_delete);
    et_alias = (EditText) view.findViewById(R.id.et_poi_alias);
    et_keyword = (EditText) view.findViewById(R.id.et_poi_keyword);
    et_address = (EditText) view.findViewById(R.id.et_poi_address);
    sp_city = (Spinner) view.findViewById(R.id.spinner_poi_city);
    sp_city.setPrompt("City");
    String[] arrayCity = new String[]{"Erie", "Pittsburgh", "Cleveland", "Buffalo", "Niagara Falls", "Jamestown"};
    adapter = new ArrayAdapter <> (this.getContext(),
            android.R.layout.simple_spinner_dropdown_item, arrayCity);
    sp_city.setAdapter(adapter);

    et_alias.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            poiDialog.setAlias(et_alias.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    et_keyword.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            poiDialog.setKeyword(et_keyword.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    et_address.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            poiDialog.setAddress(et_address.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    sp_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView <?> parentView, View selectedItemView,
                                   int position, long id) {
            poiDialog.setCity(sp_city.getSelectedItem().toString());
        }

        @Override
        public void onNothingSelected(AdapterView <?> parentView) {
        }
    });

    tv_delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder delete_builder = new AlertDialog.Builder(context);
            delete_builder.setMessage("Are you sure you want to delete this point of interest?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(context, "Deleting POI !", Toast.LENGTH_LONG).show();
                            deletePOI();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDelete = delete_builder.create();
            alertDelete.setTitle("Delete POI!");
            alertDelete.show();
        }
    });
}

private void fillViews() {
    et_alias.setText(poiDialog.getAlias());
    et_keyword.setText(poiDialog.getKeyword());
    et_address.setText(poiDialog.getAddress());
    sp_city.setSelection(adapter.getPosition(poiDialog.getCity()));
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    if (positiveResult) {
        String alias, keyword, address, city;
        if(deleted) {
            et_alias.setText("");
            et_keyword.setText("");
            et_address.setText("");
            sp_city.setPrompt("City");
        } else {
            alias = et_alias.getText().toString();
            keyword = et_keyword.getText().toString();
            address = et_address.getText().toString();
            city = sp_city.getSelectedItem().toString();
            if (!keyword.isEmpty() && !address.isEmpty() && !city.isEmpty()) {
                Toast.makeText(context, "Saving POI !", Toast.LENGTH_LONG).show();
                addPOI(alias, keyword, address, city);
            } else {
                Toast.makeText(context, "Required Fields are empty !", Toast.LENGTH_LONG).show();
            }
        }
    }
}

private void addPOI(String alias, String keyword, String address, String city) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .retryOnConnectionFailure(true)
            .connectTimeout(15, TimeUnit.SECONDS)
            .build();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setEmail(pref.getString(Constants.USER_EMAIL, ""));

    POI poi = new POI();
    poi.setAlias(alias);
    poi.setKeyword(keyword);
    poi.setAddress(address);
    poi.setCity(city);

    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.ADD_POI);
    request.setUser(user);
    request.setPoi(poi);

    Call <ServerResponse> response = requestInterface.operation(request);
    response.enqueue(new Callback <ServerResponse>() {
        @Override
        public void onResponse(Call <ServerResponse> call,
                               retrofit2.Response <ServerResponse> response) {
            ServerResponse resp = response.body();
            if(resp.getResult().equals(Constants.SUCCESS)) {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
                SharedPreferences.Editor editor = getEditor();
                save(editor);
            } else {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call <ServerResponse> call, Throwable t) {
            Log.d(Constants.TAG, "failed");
            Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    });
}

private void save(SharedPreferences.Editor editor) {
    editor.putString(Constants.FIRST_POI_ALIAS, poiDialog.getAlias());
    editor.putString(Constants.FIRST_POI_KEYWORD, poiDialog.getKeyword());
    editor.putString(Constants.FIRST_POI_ADDRESS, poiDialog.getAddress());
    editor.putString(Constants.FIRST_POI_CITY, poiDialog.getCity());
    editor.apply();
}

private void deletePOI() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setEmail(pref.getString(Constants.USER_EMAIL, ""));

    POI poi = new POI();
    poi.setKeyword(pref.getString(Constants.FIRST_POI_KEYWORD, ""));
    poi.setCity(pref.getString(Constants.FIRST_POI_CITY, ""));

    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.DELETE_POI);
    request.setUser(user);
    request.setPoi(poi);

    Call <ServerResponse> response = requestInterface.operation(request);
    response.enqueue(new Callback <ServerResponse>() {
        @Override
        public void onResponse(Call <ServerResponse> call,
                               retrofit2.Response <ServerResponse> response) {

            ServerResponse resp = response.body();
            if(resp.getResult().equals(Constants.SUCCESS)) {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
                SharedPreferences.Editor editor = getEditor();
                saveDelete(editor);
                deleted = true;
            } else {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call <ServerResponse> call, Throwable t) {
            Log.d(Constants.TAG, "failed");
            Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    });
}

private void saveDelete(SharedPreferences.Editor editor) {
    editor.putString(Constants.FIRST_POI_ALIAS, "");
    editor.putString(Constants.FIRST_POI_KEYWORD, "");
    editor.putString(Constants.FIRST_POI_ADDRESS, "");
    editor.putString(Constants.FIRST_POI_CITY, "");
    editor.apply();
}

}
</code>```

index.php:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    ```
        <?php

        // dispaly all errors except Warnings
        ini_set('display_errors',1);
        error_reporting(E_ALL & ~E_WARNING);

        include 'fetch_data.php';
        require_once 'users/login.php';
        require_once 'preferences/preferences.php';
        require_once 'include/functions_validation.php';

        $login = new Login();
        $pref = new Preferences();
        $fun = new FunctionsValidation();

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $data = json_decode(file_get_contents("php://input"));

            if(isset($data -> operation)) {
                $operation = $data -> operation;
                if(!empty($operation)) {
                    /*
                    * User registration and login operations
                    */
                    if($operation == 'register') {
                        echo $login -> register($data);
                    }
                    else if ($operation == 'regVerify') {
                        echo $login -> registerVerify($data);
                    }
                    else if ($operation == 'login') {
                        echo $login -> login($data);
                    }
                    else if ($operation == 'chgPass') {
                        echo $login -> changePassword($data);
                    }
                    else if ($operation == 'resPassReq') {
                        echo $login -> resetPasswordReq($data);
                    }
                    else if ($operation == 'resPass') {
                        echo $login -> resetPassword($data);
                    }
                    /*
                     * Point of Interest operations
                     */
                    else if($operation == 'addPOI') {
                        echo $pref -> addPOI($data);
                    }
                    else if($operation == 'deletePOI') {
                        echo $pref -> deletePOI($data);
                    }

                    /**
                     * Mileage Distance operations
                     */
                    else if($operation == 'addMileage') {
                        echo $pref -> addMileage($data);
                    }
                    else if($operation == 'deleteMileage') {
                        echo $pref -> deleteMileage($data);
                    }
                } else { // if operation is empty
                    echo $fun -> getMsgParamNotEmpty();
                }
            } else { // if operation is not set
                echo $fun -> getMsgInvalidParam();
            }
        } else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            echo "GeolocationNews API";
        }
        ?>
      ```
  </body>
</html>
</code>```

答:
Does Constants.BASE_URL point to your index.php page?

If so, you're trying to parse a HTML page as JSON, which is invalid. I suggest you send some kind of query parameter from your Android app that you can check for from PHP, so that the HTML portions aren't included in the output.

Let's say your Android app submits the request to index.php?output=json for example. Then in your index.php you can check for that:

```<code><?php
$jsonOnly = (isset($_GET['output']) && $_GET['output'] == 'json');

if (!$jsonOnly):
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    ```
<?php
endif;

// your existing PHP code here

if (!$jsonOnly):
?>
    ```
</body>
</html>
<?php
endif;
?>
</code>```

Edit However, I think it would be better to separate your logic from your presentation. What if you were to put all your PHP code in a separate file, e.g. handle_request.php? Then in your index.php, you can have all your HTML code and then include that file:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    ```
        <?php include('handle_request.php'); ?>
    ```
</body>
</html>
</code>```

For your app, you can then create a different file that you use as your Constants.BASE_URL, say app.php, which only sets up a proper JSON content-type header and includes the same file:

```<code><?php
header('Content-Type: application/json');
include('handle_request.php');
?>
</code>```

Body:
My code works fine when I remove HTML code from index.php and just keep the php lines between . But when I use the as shown down with HTML lines - which I need for other parts of the application -, it gives error:

"Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $"

I have tried to use

Gson gson = new GsonBuilder()
            .setLenient()
            .create();

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

But it gives me another error:

"java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $"

This is my Logcat output

How to fix that?!!!

FirstPOIPreference.java:

public class FirstPOIPreference extends DialogPreference {

private EditText et_alias, et_keyword, et_address;
private Spinner sp_city;
private ArrayAdapter<String> adapter;
private boolean deleted;
private Context context;
private SharedPreferences pref;
private POI poiDialog = new POI();

public FirstPOIPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    init();
}

private void init() {
    setPersistent(false);
    setDialogLayoutResource(R.layout.pref_poi_dialog);
    setPositiveButtonText(android.R.string.ok);
    setNegativeButtonText(android.R.string.cancel);
}

@Override
protected void onBindDialogView(View view) {
    super.onBindDialogView(view);
    pref = PreferenceManager.getDefaultSharedPreferences(this.context);
    load(getSharedPreferences());
    initViews(view);
    fillViews();
}

private void load(SharedPreferences prefs) {
    poiDialog.setAlias(prefs.getString(Constants.FIRST_POI_ALIAS, ""));
    poiDialog.setKeyword(prefs.getString(Constants.FIRST_POI_KEYWORD, ""));
    poiDialog.setAddress(prefs.getString(Constants.FIRST_POI_ADDRESS, ""));
    poiDialog.setCity((prefs.getString(Constants.FIRST_POI_CITY, "")));
}

private void initViews(View view) {
    deleted = false;
    TextView tv_delete = (TextView) view.findViewById(R.id.tv_poi_delete);
    et_alias = (EditText) view.findViewById(R.id.et_poi_alias);
    et_keyword = (EditText) view.findViewById(R.id.et_poi_keyword);
    et_address = (EditText) view.findViewById(R.id.et_poi_address);
    sp_city = (Spinner) view.findViewById(R.id.spinner_poi_city);
    sp_city.setPrompt("City");
    String[] arrayCity = new String[]{"Erie", "Pittsburgh", "Cleveland", "Buffalo", "Niagara Falls", "Jamestown"};
    adapter = new ArrayAdapter <> (this.getContext(),
            android.R.layout.simple_spinner_dropdown_item, arrayCity);
    sp_city.setAdapter(adapter);

    et_alias.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            poiDialog.setAlias(et_alias.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    et_keyword.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            poiDialog.setKeyword(et_keyword.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    et_address.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            poiDialog.setAddress(et_address.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    sp_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView <?> parentView, View selectedItemView,
                                   int position, long id) {
            poiDialog.setCity(sp_city.getSelectedItem().toString());
        }

        @Override
        public void onNothingSelected(AdapterView <?> parentView) {
        }
    });

    tv_delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder delete_builder = new AlertDialog.Builder(context);
            delete_builder.setMessage("Are you sure you want to delete this point of interest?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(context, "Deleting POI !", Toast.LENGTH_LONG).show();
                            deletePOI();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDelete = delete_builder.create();
            alertDelete.setTitle("Delete POI!");
            alertDelete.show();
        }
    });
}

private void fillViews() {
    et_alias.setText(poiDialog.getAlias());
    et_keyword.setText(poiDialog.getKeyword());
    et_address.setText(poiDialog.getAddress());
    sp_city.setSelection(adapter.getPosition(poiDialog.getCity()));
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    if (positiveResult) {
        String alias, keyword, address, city;
        if(deleted) {
            et_alias.setText("");
            et_keyword.setText("");
            et_address.setText("");
            sp_city.setPrompt("City");
        } else {
            alias = et_alias.getText().toString();
            keyword = et_keyword.getText().toString();
            address = et_address.getText().toString();
            city = sp_city.getSelectedItem().toString();
            if (!keyword.isEmpty() && !address.isEmpty() && !city.isEmpty()) {
                Toast.makeText(context, "Saving POI !", Toast.LENGTH_LONG).show();
                addPOI(alias, keyword, address, city);
            } else {
                Toast.makeText(context, "Required Fields are empty !", Toast.LENGTH_LONG).show();
            }
        }
    }
}

private void addPOI(String alias, String keyword, String address, String city) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .retryOnConnectionFailure(true)
            .connectTimeout(15, TimeUnit.SECONDS)
            .build();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setEmail(pref.getString(Constants.USER_EMAIL, ""));

    POI poi = new POI();
    poi.setAlias(alias);
    poi.setKeyword(keyword);
    poi.setAddress(address);
    poi.setCity(city);

    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.ADD_POI);
    request.setUser(user);
    request.setPoi(poi);

    Call <ServerResponse> response = requestInterface.operation(request);
    response.enqueue(new Callback <ServerResponse>() {
        @Override
        public void onResponse(Call <ServerResponse> call,
                               retrofit2.Response <ServerResponse> response) {
            ServerResponse resp = response.body();
            if(resp.getResult().equals(Constants.SUCCESS)) {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
                SharedPreferences.Editor editor = getEditor();
                save(editor);
            } else {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call <ServerResponse> call, Throwable t) {
            Log.d(Constants.TAG, "failed");
            Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    });
}

private void save(SharedPreferences.Editor editor) {
    editor.putString(Constants.FIRST_POI_ALIAS, poiDialog.getAlias());
    editor.putString(Constants.FIRST_POI_KEYWORD, poiDialog.getKeyword());
    editor.putString(Constants.FIRST_POI_ADDRESS, poiDialog.getAddress());
    editor.putString(Constants.FIRST_POI_CITY, poiDialog.getCity());
    editor.apply();
}

private void deletePOI() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setEmail(pref.getString(Constants.USER_EMAIL, ""));

    POI poi = new POI();
    poi.setKeyword(pref.getString(Constants.FIRST_POI_KEYWORD, ""));
    poi.setCity(pref.getString(Constants.FIRST_POI_CITY, ""));

    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.DELETE_POI);
    request.setUser(user);
    request.setPoi(poi);

    Call <ServerResponse> response = requestInterface.operation(request);
    response.enqueue(new Callback <ServerResponse>() {
        @Override
        public void onResponse(Call <ServerResponse> call,
                               retrofit2.Response <ServerResponse> response) {

            ServerResponse resp = response.body();
            if(resp.getResult().equals(Constants.SUCCESS)) {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
                SharedPreferences.Editor editor = getEditor();
                saveDelete(editor);
                deleted = true;
            } else {
                Toast.makeText(context, resp.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call <ServerResponse> call, Throwable t) {
            Log.d(Constants.TAG, "failed");
            Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    });
}

private void saveDelete(SharedPreferences.Editor editor) {
    editor.putString(Constants.FIRST_POI_ALIAS, "");
    editor.putString(Constants.FIRST_POI_KEYWORD, "");
    editor.putString(Constants.FIRST_POI_ADDRESS, "");
    editor.putString(Constants.FIRST_POI_CITY, "");
    editor.apply();
}

}

index.php:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

        <?php

        // dispaly all errors except Warnings
        ini_set('display_errors',1);
        error_reporting(E_ALL & ~E_WARNING);

        include 'fetch_data.php';
        require_once 'users/login.php';
        require_once 'preferences/preferences.php';
        require_once 'include/functions_validation.php';

        $login = new Login();
        $pref = new Preferences();
        $fun = new FunctionsValidation();

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $data = json_decode(file_get_contents("php://input"));

            if(isset($data -> operation)) {
                $operation = $data -> operation;
                if(!empty($operation)) {
                    /*
                    * User registration and login operations
                    */
                    if($operation == 'register') {
                        echo $login -> register($data);
                    }
                    else if ($operation == 'regVerify') {
                        echo $login -> registerVerify($data);
                    }
                    else if ($operation == 'login') {
                        echo $login -> login($data);
                    }
                    else if ($operation == 'chgPass') {
                        echo $login -> changePassword($data);
                    }
                    else if ($operation == 'resPassReq') {
                        echo $login -> resetPasswordReq($data);
                    }
                    else if ($operation == 'resPass') {
                        echo $login -> resetPassword($data);
                    }
                    /*
                     * Point of Interest operations
                     */
                    else if($operation == 'addPOI') {
                        echo $pref -> addPOI($data);
                    }
                    else if($operation == 'deletePOI') {
                        echo $pref -> deletePOI($data);
                    }

                    /**
                     * Mileage Distance operations
                     */
                    else if($operation == 'addMileage') {
                        echo $pref -> addMileage($data);
                    }
                    else if($operation == 'deleteMileage') {
                        echo $pref -> deleteMileage($data);
                    }
                } else { // if operation is empty
                    echo $fun -> getMsgParamNotEmpty();
                }
            } else { // if operation is not set
                echo $fun -> getMsgInvalidParam();
            }
        } else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            echo "GeolocationNews API";
        }
        ?>

Body:
Does Constants.BASE_URL point to your index.php page?

If so, you're trying to parse a HTML page as JSON, which is invalid. I suggest you send some kind of query parameter from your Android app that you can check for from PHP, so that the HTML portions aren't included in the output.

Let's say your Android app submits the request to index.php?output=json for example. Then in your index.php you can check for that:

<?php
$jsonOnly = (isset($_GET['output']) && $_GET['output'] == 'json');

if (!$jsonOnly):
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <pre>
<?php
endif;

// your existing PHP code here

if (!$jsonOnly):
?>
    </pre>
</body>
</html>
<?php
endif;
?>

Edit However, I think it would be better to separate your logic from your presentation. What if you were to put all your PHP code in a separate file, e.g. handle_request.php? Then in your index.php, you can have all your HTML code and then include that file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <pre>
        <?php include('handle_request.php'); ?>
    </pre>
</body>
</html>

For your app, you can then create a different file that you use as your Constants.BASE_URL, say app.php, which only sets up a proper JSON content-type header and includes the same file:

<?php
header('Content-Type: application/json');
include('handle_request.php');
?>


问:
Javascript hide items from dropdown
I have a dropdown list with 24 items, the user can check a radio button and this will set it to only show 12. If they de-select it, the dropdown will show the 24 items as before.

I have it working to only show 12 items using

```<code>document.getElementById('theMenu').length = 12;
</code>```

But then when I try to set it back to 24, the other 12 items are empty.

Am thinking I may need to store the values in a temp array of some sort, then just load these back into the dropdown menu? (Javascript only)

Thanks:)

答:
Yes setting the length to 12 is destroying the second 12 values.

It may be benifical to put these elements in memory when the page is ready and not to manipulate that array (use it as a constant), populate another array with ones you need, create a method that takes an array and populates a drop down (you could hard-code the target array, or make the target Id another parameter).

Are you able to use the JQuery library? I would suggest so. It will most probably have some useful methods for manipulating <select>s.

Title: Javascript hide items from dropdown

Body:
I have a dropdown list with 24 items, the user can check a radio button and this will set it to only show 12. If they de-select it, the dropdown will show the 24 items as before.

I have it working to only show 12 items using

document.getElementById('theMenu').length = 12;

But then when I try to set it back to 24, the other 12 items are empty.

Am thinking I may need to store the values in a temp array of some sort, then just load these back into the dropdown menu? (Javascript only)

Thanks:)


问:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to javafx.collections.ObservableList
when i want to add a data to tableview in javafx i receive this error

java.lang.ClassCastException: java.util.ArrayList cannot be cast to
  javafx.collections.ObservableList

class User

```<code>public class User {
    private int id;
    private  String nom;
    private  String prenom;
    private  String cin;
    private  String tel;
    private  String adresse;
    private  String dn;
</code>```

and Function data :

```<code>public ArrayList afficher_user() throws SQLException{
        ArrayList<User> data =  new ArrayList<>();
            Connection conn=null;
          try {
                Class.forName(Driver);
                conn = DriverManager.getConnection(URL,"root","");
                String sql ="select * from utilisateur";
                PreparedStatement Stmt = conn.prepareStatement(sql);
                ResultSet rs = Stmt.executeQuery(sql);
                while(rs.next()){
                User us = new User();
                us.setId(rs.getInt("id"));
                us.setNom(rs.getString("nom"));
                us.setPrenom(rs.getString("prenom"));
                us.setCin(rs.getString("cin"));
                us.setAdresse(rs.getString("adresse"));
                us.setTel(rs.getString("tel"));
                us.setDn(rs.getString("dn"));
                data.add(us);
                }
                rs.close();
                conn.close();
          } catch (ClassNotFoundException ex) {
                System.err.println(ex.getMessage());
          }
      return data;
}
</code>```

in controller class :

```<code>private TableView<User> dgv_user;
    @FXML
     private TableColumn<User,String> id;
    private TableColumn<User, String> nom;
    private TableColumn<User, String> prenom;
    private TableColumn<User, String> cin;
    private TableColumn<User, String> dn;
    private TableColumn<User, String> tel;
    private TableColumn<User,String> adresse;

     public void creer_user(ActionEvent event) throws SQLException {

        User u=new User();
        System.out.println(u.afficher_user());
        dgv_user.setItems((ObservableList<User>) u.afficher_user());

        }
</code>```

答:
You can't directly cast the ArrayList object to observableList, rather you need to use FXCollections.observableArrayList() as shown in the below code & set that list to your dgv_user object.

```<code>ObservableList<User> observableArrayList =
           FXCollections.observableArrayList(u.afficher_user());
dgv_user.setItems(observableArrayList);
</code>```

Body:
when i want to add a data to tableview in javafx i receive this error

java.lang.ClassCastException: java.util.ArrayList cannot be cast to
  javafx.collections.ObservableList

class User

public class User {
    private int id;
    private  String nom;
    private  String prenom;
    private  String cin;
    private  String tel;
    private  String adresse;
    private  String dn;

and Function data :

public ArrayList afficher_user() throws SQLException{
        ArrayList<User> data =  new ArrayList<>();
            Connection conn=null;
          try {
                Class.forName(Driver);
                conn = DriverManager.getConnection(URL,"root","");
                String sql ="select * from utilisateur";
                PreparedStatement Stmt = conn.prepareStatement(sql);
                ResultSet rs = Stmt.executeQuery(sql);
                while(rs.next()){
                User us = new User();
                us.setId(rs.getInt("id"));
                us.setNom(rs.getString("nom"));
                us.setPrenom(rs.getString("prenom"));
                us.setCin(rs.getString("cin"));
                us.setAdresse(rs.getString("adresse"));
                us.setTel(rs.getString("tel"));
                us.setDn(rs.getString("dn"));
                data.add(us);
                }
                rs.close();
                conn.close();
          } catch (ClassNotFoundException ex) {
                System.err.println(ex.getMessage());
          }
      return data;
}

in controller class :

private TableView<User> dgv_user;
    @FXML
     private TableColumn<User,String> id;
    private TableColumn<User, String> nom;
    private TableColumn<User, String> prenom;
    private TableColumn<User, String> cin;
    private TableColumn<User, String> dn;
    private TableColumn<User, String> tel;
    private TableColumn<User,String> adresse;

     public void creer_user(ActionEvent event) throws SQLException {

        User u=new User();
        System.out.println(u.afficher_user());
        dgv_user.setItems((ObservableList<User>) u.afficher_user());

        }

Body:
You can't directly cast the ArrayList object to observableList, rather you need to use FXCollections.observableArrayList() as shown in the below code & set that list to your dgv_user object.

ObservableList<User> observableArrayList =
           FXCollections.observableArrayList(u.afficher_user());
dgv_user.setItems(observableArrayList);


问:
Where can I find Delphi/Embarcadero redistributables
Even though I own a few Delphi versions, I got an executable missing, in this case, rtl190.bpl. I started looking for it, and concluded Embarcadero must have a peculiar redistribution policy, nothing like certain "runtime" downloads from  other vendors. Even as a registered developer I don't seem to have rights to any of the downloads for versions I do not own. Are XE5 runtimes, or any other Delphi runtimes, to be found somewhere?</p>

答: Apparently only possible source for such missing BPLs are other apps, I found my missing parts in the installation directories of AVG Tune Up and www.wlcsystems.com mscada where the rather rare cc32140mt.dll  was to be found</p>


问:
Converting a foldl into fold1
I am using the following fold to get the final monotonically decreasing sequence of a list.

```<code>foldl (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) [(-1)] a
</code>```

So [9,5,3,6,2,1]  would return [6,2,1]
However, with foldl I needed to supply a start for the fold namely [(-1)].  I was trying to turn into to a foldl1 to be able to handle any range of integers as well as any Ord a like so:

```<code>foldl1 (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) a
</code>```

But I get there error:

```<code>cannot construct infinite type: a ~ [a]
in the second argument of (<=) namely last acc
</code>```

I was under the impression that foldl1 was basically :

```<code>foldl (function) [head a] a
</code>```

But I guess this isn't so?  How would you go about making this fold generic for any Ord type?

答:
I was under the impression that foldl1 was basically :

```<code>foldl (function) [head a] a
</code>```

No, foldl1 is basically:

```<code>foldl function <b>(head a) (tail a)</b></code>```

So the initial element is not a list of head a, but head a.

How would you go about making this fold generic for any Ord type?

Well a quick fix is:

```<code>foldl (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) [<b>head a</b>] <b>(tail a)</b></code>```

But there are still two problems:

in case a is an empty list, this function will error (while you probably want to return the empty list); and

the code is not terribly efficient since both last and (++) run in O(n).

The first problem can easily be addressed by using pattern matching to prevent that scenario. But for the latter you better would for instance use a reverse approach. Like for instance:

```<code>f :: Ord t => [t] -> [t]
f [] = [] -- case when the empty list is given
f a = reverse $ foldl (\acc@(ac:_) x -> if x <= ac then (x:acc) else [x]) [head a] (tail a)
</code>```

Furthermore personally I am not a huge fan of if-then-else in functional programming, you can for instance define a helper function like:

```<code>f :: Ord t => [t] -> [t]
f [] = [] -- case when the empty list is given
f a = reverse $ foldl g [head a] (tail a)
    where g acc@(ac:_) x | x <= ac = (x:acc)
                         | otherwise = [x]
</code>```

Now reverse runs in O(n) but this is done only once. Furthermore the (:) construction runs in O(1) so all the actions in g run in O(1) (well given the comparison of course works efficient, etc.) making the algorithm itself O(n).

For your sample input it gives:

```<code>*Main> f [9,5,3,6,2,1]
[6,2,1]
</code>```

Title: Converting a foldl into fold1

Body:
I am using the following fold to get the final monotonically decreasing sequence of a list.

foldl (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) [(-1)] a

So [9,5,3,6,2,1]  would return [6,2,1]
However, with foldl I needed to supply a start for the fold namely [(-1)].  I was trying to turn into to a foldl1 to be able to handle any range of integers as well as any Ord a like so:

foldl1 (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) a

But I get there error:

cannot construct infinite type: a ~ [a]
in the second argument of (<=) namely last acc

I was under the impression that foldl1 was basically :

foldl (function) [head a] a

But I guess this isn't so?  How would you go about making this fold generic for any Ord type?

Body:
I was under the impression that foldl1 was basically :

foldl (function) [head a] a

No, foldl1 is basically:

foldl function (head a) (tail a)

So the initial element is not a list of head a, but head a.

How would you go about making this fold generic for any Ord type?

Well a quick fix is:

foldl (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) [head a] (tail a)

But there are still two problems:

in case a is an empty list, this function will error (while you probably want to return the empty list); and

the code is not terribly efficient since both last and (++) run in O(n).

The first problem can easily be addressed by using pattern matching to prevent that scenario. But for the latter you better would for instance use a reverse approach. Like for instance:

f :: Ord t => [t] -> [t]
f [] = [] -- case when the empty list is given
f a = reverse $ foldl (\acc@(ac:_) x -> if x <= ac then (x:acc) else [x]) [head a] (tail a)

Furthermore personally I am not a huge fan of if-then-else in functional programming, you can for instance define a helper function like:

f :: Ord t => [t] -> [t]
f [] = [] -- case when the empty list is given
f a = reverse $ foldl g [head a] (tail a)
    where g acc@(ac:_) x | x <= ac = (x:acc)
                         | otherwise = [x]

Now reverse runs in O(n) but this is done only once. Furthermore the (:) construction runs in O(1) so all the actions in g run in O(1) (well given the comparison of course works efficient, etc.) making the algorithm itself O(n).

For your sample input it gives:

*Main> f [9,5,3,6,2,1]
[6,2,1]


问:
React native use fetch inside for loop
In my React native app, I have an array of objects, each object has 3 properties: address, latitude and longitude. Latitude and longitude are initially null, so I m using google api for reverse geocoding. Since it is an array, I m looping inside my array and fetch google url to get lat and lng from given address. But when I try to save latitude and longitude inside my object, I have an error:

TypeError: undefined is not an object (evaluating:
  locations[i].latitude =
  responseJson.results[0].geometry.location.lat)

Here is my code:

for (var i = 0; i < locations.length; i++){

          if (locations[i].address){

            var googleRequestUrl = this.state.GoogleAPIUrl + locations[i].address;

            fetch(googleRequestUrl)
            .then((response) => response.json())
            .then((responseJson) => {
              locations[i].latitude = responseJson.results[0].geometry.location.lat;
              locations[i].longitude = responseJson.results[0].geometry.location.lng;
            })
            .catch((error) => {
              console.warn(error);
            })
            .done();
          }
        }```

The google API I m using is: "https://maps.googleapis.com/maps/api/geocode/json?address="

I have already checked if I m getting the response with response.text(): it gives me a complete response, with lat and lng.

I cannot understand why it gives me that error, what am I doing wrong? Is there something wrong with having fetch inside a loop? Or the problem is something else?

Any suggestions or better solutions are appreciated

答:
Probably one of your addresses cannot be geocoded correctly and you are trying to access non-existing result on response object.

I would check whether result exist and continue accordingly.

```<code>const result = responseJson.results[0];
if (result) {
    locations[i].latitude = result.geometry.location.lat;
    locations[i].longitude = result.geometry.location.lng;
}
</code>```

Title: React native use fetch inside for loop

Body:
In my React native app, I have an array of objects, each object has 3 properties: address, latitude and longitude. Latitude and longitude are initially null, so I m using google api for reverse geocoding. Since it is an array, I m looping inside my array and fetch google url to get lat and lng from given address. But when I try to save latitude and longitude inside my object, I have an error:

TypeError: undefined is not an object (evaluating:
  locations[i].latitude =
  responseJson.results[0].geometry.location.lat)

Here is my code:

for (var i = 0; i < locations.length; i++){

          if (locations[i].address){

            var googleRequestUrl = this.state.GoogleAPIUrl + locations[i].address;

            fetch(googleRequestUrl)
            .then((response) => response.json())
            .then((responseJson) => {
              locations[i].latitude = responseJson.results[0].geometry.location.lat;
              locations[i].longitude = responseJson.results[0].geometry.location.lng;
            })
            .catch((error) => {
              console.warn(error);
            })
            .done();
          }
        }

The google API I m using is: "https://maps.googleapis.com/maps/api/geocode/json?address="

I have already checked if I m getting the response with response.text(): it gives me a complete response, with lat and lng.

I cannot understand why it gives me that error, what am I doing wrong? Is there something wrong with having fetch inside a loop? Or the problem is something else?

Any suggestions or better solutions are appreciated

Body:
Probably one of your addresses cannot be geocoded correctly and you are trying to access non-existing result on response object.

I would check whether result exist and continue accordingly.

const result = responseJson.results[0];
if (result) {
    locations[i].latitude = result.geometry.location.lat;
    locations[i].longitude = result.geometry.location.lng;
}