问:
How remove black background around the circular image view in android
I have created circular image view with the CircularImageView library

and I am facing issues with black background around the circular image in my layout, I tried to resolve this issue but I am failed to fix this issue

Following code is CircularImageView.java file

```<code>package de.hdodenhof.circleimageview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircleImageView extends ImageView {

    private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;

    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    private static final int COLORDRAWABLE_DIMENSION = 2;

    private static final int DEFAULT_BORDER_WIDTH = 0;
    private static final int DEFAULT_BORDER_COLOR = Color.BLACK;

    private final RectF mDrawableRect = new RectF();
    private final RectF mBorderRect = new RectF();

    private final Matrix mShaderMatrix = new Matrix();
    private final Paint mBitmapPaint = new Paint();
    private final Paint mBorderPaint = new Paint();

    private int mBorderColor = DEFAULT_BORDER_COLOR;
    private int mBorderWidth = DEFAULT_BORDER_WIDTH;

    private Bitmap mBitmap;
    private BitmapShader mBitmapShader;
    private int mBitmapWidth;
    private int mBitmapHeight;

    private float mDrawableRadius;
    private float mBorderRadius;

    private ColorFilter mColorFilter;

    private boolean mReady;
    private boolean mSetupPending;

    public CircleImageView(Context context) {
        super(context);

        init();
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);

        mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
        mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);

        a.recycle();

        init();
    }

    private void init() {
        super.setScaleType(SCALE_TYPE);
        mReady = true;

        if (mSetupPending) {
            setup();
            mSetupPending = false;
        }
    }

    @Override
    public ScaleType getScaleType() {
        return SCALE_TYPE;
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (scaleType != SCALE_TYPE) {
            throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
        }
    }

    @Override
    public void setAdjustViewBounds(boolean adjustViewBounds) {
        if (adjustViewBounds) {
            throw new IllegalArgumentException("adjustViewBounds not supported.");
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) {
            return;
        }

        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
        if (mBorderWidth != 0) {
            canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setup();
    }

    public int getBorderColor() {
        return mBorderColor;
    }

    public void setBorderColor(int borderColor) {
        if (borderColor == mBorderColor) {
            return;
        }

        mBorderColor = borderColor;
        mBorderPaint.setColor(mBorderColor);
        invalidate();
    }

    public int getBorderWidth() {
        return mBorderWidth;
    }

    public void setBorderWidth(int borderWidth) {
        if (borderWidth == mBorderWidth) {
            return;
        }

        mBorderWidth = borderWidth;
        setup();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        mBitmap = bm;
        setup();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        mBitmap = getBitmapFromDrawable(drawable);
        setup();
    }

    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        if (cf == mColorFilter) {
            return;
        }

        mColorFilter = cf;
        mBitmapPaint.setColorFilter(mColorFilter);
        invalidate();
    }

    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap;

            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
            }

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    private void setup() {
        if (!mReady) {
            mSetupPending = true;
            return;
        }

        if (mBitmap == null) {
            return;
        }

        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setShader(mBitmapShader);

        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(mBorderColor);
        mBorderPaint.setStrokeWidth(mBorderWidth);

        mBitmapHeight = mBitmap.getHeight();
        mBitmapWidth = mBitmap.getWidth();

        mBorderRect.set(0, 0, getWidth(), getHeight());
        mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);

        mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
        mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);

        updateShaderMatrix();
        invalidate();
    }

    private void updateShaderMatrix() {
        float scale;
        float dx = 0;
        float dy = 0;

        mShaderMatrix.set(null);

        if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
            scale = mDrawableRect.height() / (float) mBitmapHeight;
            dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
        } else {
            scale = mDrawableRect.width() / (float) mBitmapWidth;
            dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
        }

        mShaderMatrix.setScale(scale, scale);
        mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);

        mBitmapShader.setLocalMatrix(mShaderMatrix);
    }

}
</code>```

And My layout is

```<code><com.example.util.CircleImageView
                xmlns:app="http://schemas.android.com/apk/res-auto"
                app:border_color="@color/white"
                app:border_width="2dp"
                android:id="@+id/chooseanavatar"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_marginTop="5dp"
                android:layout_gravity="center_horizontal"
                android:layout_centerVertical="true"

                 />
</code>```

答:
Came through the same problem with a similar view on 7.0.
Solved by drawing a white canvas before drawing anything else.

```<code>@Override
public void onDraw(Canvas canvas) {
      canvas.drawARGB(255, 255, 255, 255);
      ...
}
</code>```

This workaround has the same visual result as setting a white background directly in the XML, but will not work well if this view is child of a non-flat view (you will see a a white square).

Body:
I have created circular image view with the CircularImageView library

and I am facing issues with black background around the circular image in my layout, I tried to resolve this issue but I am failed to fix this issue

Following code is CircularImageView.java file

package de.hdodenhof.circleimageview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircleImageView extends ImageView {

    private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;

    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    private static final int COLORDRAWABLE_DIMENSION = 2;

    private static final int DEFAULT_BORDER_WIDTH = 0;
    private static final int DEFAULT_BORDER_COLOR = Color.BLACK;

    private final RectF mDrawableRect = new RectF();
    private final RectF mBorderRect = new RectF();

    private final Matrix mShaderMatrix = new Matrix();
    private final Paint mBitmapPaint = new Paint();
    private final Paint mBorderPaint = new Paint();

    private int mBorderColor = DEFAULT_BORDER_COLOR;
    private int mBorderWidth = DEFAULT_BORDER_WIDTH;

    private Bitmap mBitmap;
    private BitmapShader mBitmapShader;
    private int mBitmapWidth;
    private int mBitmapHeight;

    private float mDrawableRadius;
    private float mBorderRadius;

    private ColorFilter mColorFilter;

    private boolean mReady;
    private boolean mSetupPending;

    public CircleImageView(Context context) {
        super(context);

        init();
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);

        mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
        mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);

        a.recycle();

        init();
    }

    private void init() {
        super.setScaleType(SCALE_TYPE);
        mReady = true;

        if (mSetupPending) {
            setup();
            mSetupPending = false;
        }
    }

    @Override
    public ScaleType getScaleType() {
        return SCALE_TYPE;
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (scaleType != SCALE_TYPE) {
            throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
        }
    }

    @Override
    public void setAdjustViewBounds(boolean adjustViewBounds) {
        if (adjustViewBounds) {
            throw new IllegalArgumentException("adjustViewBounds not supported.");
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) {
            return;
        }

        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
        if (mBorderWidth != 0) {
            canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setup();
    }

    public int getBorderColor() {
        return mBorderColor;
    }

    public void setBorderColor(int borderColor) {
        if (borderColor == mBorderColor) {
            return;
        }

        mBorderColor = borderColor;
        mBorderPaint.setColor(mBorderColor);
        invalidate();
    }

    public int getBorderWidth() {
        return mBorderWidth;
    }

    public void setBorderWidth(int borderWidth) {
        if (borderWidth == mBorderWidth) {
            return;
        }

        mBorderWidth = borderWidth;
        setup();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        mBitmap = bm;
        setup();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        mBitmap = getBitmapFromDrawable(drawable);
        setup();
    }

    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        if (cf == mColorFilter) {
            return;
        }

        mColorFilter = cf;
        mBitmapPaint.setColorFilter(mColorFilter);
        invalidate();
    }

    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap;

            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
            }

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    private void setup() {
        if (!mReady) {
            mSetupPending = true;
            return;
        }

        if (mBitmap == null) {
            return;
        }

        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setShader(mBitmapShader);

        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(mBorderColor);
        mBorderPaint.setStrokeWidth(mBorderWidth);

        mBitmapHeight = mBitmap.getHeight();
        mBitmapWidth = mBitmap.getWidth();

        mBorderRect.set(0, 0, getWidth(), getHeight());
        mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);

        mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
        mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);

        updateShaderMatrix();
        invalidate();
    }

    private void updateShaderMatrix() {
        float scale;
        float dx = 0;
        float dy = 0;

        mShaderMatrix.set(null);

        if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
            scale = mDrawableRect.height() / (float) mBitmapHeight;
            dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
        } else {
            scale = mDrawableRect.width() / (float) mBitmapWidth;
            dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
        }

        mShaderMatrix.setScale(scale, scale);
        mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);

        mBitmapShader.setLocalMatrix(mShaderMatrix);
    }

}

And My layout is

<com.example.util.CircleImageView
                xmlns:app="http://schemas.android.com/apk/res-auto"
                app:border_color="@color/white"
                app:border_width="2dp"
                android:id="@+id/chooseanavatar"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_marginTop="5dp"
                android:layout_gravity="center_horizontal"
                android:layout_centerVertical="true"

                 />

Body:
Came through the same problem with a similar view on 7.0.
Solved by drawing a white canvas before drawing anything else.

@Override
public void onDraw(Canvas canvas) {
      canvas.drawARGB(255, 255, 255, 255);
      ...
}

This workaround has the same visual result as setting a white background directly in the XML, but will not work well if this view is child of a non-flat view (you will see a a white square).


来源: stackexchange

问:
xsd.exe generating the same enum values in multiple class files
We do have more than one xsd, currently two teams are working on two different xsd along with one common xsd. If we generate separate class file for each xsd then the common xsd object types are duplicated. If we use all xsd in one command line it generate into one class file. We want separate class file for each xsd so that each team can manage separately and the future changes also can be tracked which team made the change.

Is it possible to create each class file for each xsd passed in the xsd.exe command line when multiple xsd’s are passed?

Thanks,

Zahir

答:
No, sorry, that's not possible.

Remember that the generated class file is an output . I don't know what sort of management that would require. It is the XSD files which are the input to the process, and which should be managed.

ContentLicense: CC BY-SA 2.5


问:
How to slice some part of Google Map and show the sliced one in a div?
I want to slice some part of Google Map and want to show it in a div. How can I do that? Is there any google apis?

I don't have any code but below example shows my requirement.

From the above map I want to slice below red color part and I want to put it in separate div.

Is it possible? If it is, then how can I do that? Any APIs?

答: To the best of my understanding, Google maps does not separate regions into layers. One solution I can think of is using Open Street Maps to export your desired region into an SVG and using illustrator to remove the unnecessary content.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How can I resolve my TypeScript error: Property 'then' does not exist on type 'void'
I am using the Sweet Alert library:

```<code>https://limonte.github.io/sweetalert2/
</code>```

and I am trying to use the following code from the site:

```<code>swal({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, cancel!',
  confirmButtonClass: 'btn btn-success',
  cancelButtonClass: 'btn btn-danger',
  buttonsStyling: false
}).then(function () {
  swal(
    'Deleted!',
    'Your file has been deleted.',
    'success'
  )
}, function (dismiss) {
  // dismiss can be 'cancel', 'overlay',
  // 'close', and 'timer'
  if (dismiss === 'cancel') {
    swal(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})
</code>```

I have installed types by running:

```<code>npm install --save @types/sweetalert
</code>```

but I am still getting an error message in relation to the use of 'then':

```<code>error TS2339: Property 'then' does not exist on type 'void'.
</code>```

How do I resolve this?

答:
I think your type definition file and your library do not add up. You've pulled in @types/sweetalert, which is the .d.ts file for https://sweetalert.js.org/, instead of https://limonte.github.io/sweetalert2/.

Looking at the repository for SweetAlert2, it includes type definitions in the same npm package as the library.

Body:
I am using the Sweet Alert library:

https://limonte.github.io/sweetalert2/

and I am trying to use the following code from the site:

swal({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, cancel!',
  confirmButtonClass: 'btn btn-success',
  cancelButtonClass: 'btn btn-danger',
  buttonsStyling: false
}).then(function () {
  swal(
    'Deleted!',
    'Your file has been deleted.',
    'success'
  )
}, function (dismiss) {
  // dismiss can be 'cancel', 'overlay',
  // 'close', and 'timer'
  if (dismiss === 'cancel') {
    swal(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})

I have installed types by running:

npm install --save @types/sweetalert

but I am still getting an error message in relation to the use of 'then':

error TS2339: Property 'then' does not exist on type 'void'.

How do I resolve this?


问:
Read html file as string in Powershell
I need to read a html file and parse the content to a string

From this

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>
</head>
<body>
    Index
</body>
</html>
</code>```

To an output like this

```<code>$stringValue = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"...
</code>```

I've tried with $stringValue = $htmlFile | ConvertTo-Json but it transforms some characters into new codes (> = u003e) where I want to keep the special characters intact.

Any help is appreciated

答:
You can use below command to get the content of html file and that you can store in any string variable like below.</p>

```<code>[string]$Datas = Get-Content [HTML_file_Location]
</code>```

Title: Read html file as string in Powershell

Body:
I need to read a html file and parse the content to a string

From this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>

    Index

To an output like this

$stringValue = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"...

I've tried with $stringValue = $htmlFile | ConvertTo-Json but it transforms some characters into new codes (> = u003e) where I want to keep the special characters intact.

Any help is appreciated

Body:
You can use below command to get the content of html file and that you can store in any string variable like below.

[string]$Datas = Get-Content [HTML_file_Location]


问:
Is it possible to reference to an element in the document via context?
The classic way to access an element would be:

```<code><div id="myId"></div>
<script type="text/javascript">
    $(document).ready(function(){
        $('#myId').something();
    });
</script>
</code>```

Let alone the many times when there is no clear id to use to access an element, where we end up using the class attribute's value(s), but we can never be sure if there is more than just one such element in the page.

After writing this or similar code thousands of times, i got to wonder:

Is there a way to use context to directly reference a HTML element?

I'm thinking of something like this:

```<code><div>
    <script type="text/javascript">
        $(document).ready(function(){
            $.getContext().something(); // accessing the encapsulating div
        });
    </script>
</div>
</code>```

Or anything similar?

答:
You can pass an optional second context parameter to your jQuery(selector, context) where context is:

A DOM Element, Document, or jQuery to use as context

For instance, in your example you could pass this to your selector to reference the document context:

```<code>$(document).ready(function(){
    $('#myId', this).something();
});
</code>```

The example is contrived because of the ID selector though, and since document is the default context. A better example would be something like:

```<code>$('div.foo').click(function() {
    $('span', this).addClass('bar');
});
</code>```

Body:
The classic way to access an element would be:

Let alone the many times when there is no clear id to use to access an element, where we end up using the class attribute's value(s), but we can never be sure if there is more than just one such element in the page.

After writing this or similar code thousands of times, i got to wonder:

Is there a way to use context to directly reference a HTML element?

I'm thinking of something like this:

Or anything similar?

Body:
You can pass an optional second context parameter to your jQuery(selector, context) where context is:

A DOM Element, Document, or jQuery to use as context

For instance, in your example you could pass this to your selector to reference the document context:

$(document).ready(function(){
    $('#myId', this).something();
});

The example is contrived because of the ID selector though, and since document is the default context. A better example would be something like:

$('div.foo').click(function() {
    $('span', this).addClass('bar');
});


问:
POST immediately after select a file
I have the following HTML code

```<code><form action="/script/upload_key.py" method="POST" enctype="multipart/form-data">
    Key filename: <input name="file_1" type="file">
    <input name="submit" type="submit">
</form>
</code>```

which gives me the following stuff.

I was wondering

How I can use JavaScript, to eliminate the need of Submit button. That's mean, once I Choose File, the selected file will be uploaded immediately?

How can I make sure the field to display selected file name is long enough, so that ... will not be shown?

答:
To submit it immediately, just do this:

```<code><input name="file_1" type="file" onchange="this.form.submit();">
</code>```

If you are using JQuery:

```<code>$("input[name='file_1']").change(function() { this.form.submit(); });
</code>```

About your other questions:

1) There are many methods out there... for example:

http://valums.com/ajax-upload/

http://www.webtoolkit.info/ajax-file-upload.html

(and many more. Just google for: "Ajax file upload" or "iframe file upload")

2) Don't worry about the width of the field. As you don't know how long can it be the path, it would never be long enough (i think). Also browsers may display it very different. For example Safari or Chrome show it very different from Firefox or IE. Just use the default length or the one that looks better with your design.

Title: POST immediately after select a file

Body:
I have the following HTML code

<form action="/script/upload_key.py" method="POST" enctype="multipart/form-data">
    Key filename: <input name="file_1" type="file">
    <input name="submit" type="submit">
</form>

which gives me the following stuff.

I was wondering

How I can use JavaScript, to eliminate the need of Submit button. That's mean, once I Choose File, the selected file will be uploaded immediately?

How can I make sure the field to display selected file name is long enough, so that ... will not be shown?

Body:
To submit it immediately, just do this:

<input name="file_1" type="file" onchange="this.form.submit();">

If you are using JQuery:

$("input[name='file_1']").change(function() { this.form.submit(); });

About your other questions:

1) There are many methods out there... for example:

http://valums.com/ajax-upload/

http://www.webtoolkit.info/ajax-file-upload.html

(and many more. Just google for: "Ajax file upload" or "iframe file upload")

2) Don't worry about the width of the field. As you don't know how long can it be the path, it would never be long enough (i think). Also browsers may display it very different. For example Safari or Chrome show it very different from Firefox or IE. Just use the default length or the one that looks better with your design.


问:
How can I limit text box width of QLineEdit to display at most four characters?
I am working with a GUI based on PySide. I made a (one line) text box with QLineEdit and the input is just four characters long, a restriction I already successfully applied.

The problem is I have a wider than needed text box (i.e. there is a lot of unused space after the text). How can I shorten the length of the text box?

I know this is something that is easily fixed by designing the text box with Designer; however, this particular text box is not created in Designer.

答:
Looking at the source of QLineEdit.sizeHint() one sees that a line edit is typically wide enough to display 17 latin "x" characters. I tried to replicate this in Python and change it to display 4 characters but I failed in getting the style dependent margins of the line edit correctly due to limitations of the Python binding of Qt.

A simple:

```<code>e = QtGui.QLineEdit()
fm = e.fontMetrics()
m = e.textMargins()
c = e.contentsMargins()
w = 4*fm.width('x')+m.left()+m.right()+c.left()+c.right()
</code>```

is returning 24 in my case which however is not  enough to display four characters like "abcd" in a QLineEdit. A better value would be about 32 which you can set for example like.

```<code>e.setMaximumWidth(w+8) # mysterious additional factor required
</code>```

which might still be okay even if the font is changed on many systems.

Body:
Looking at the source of QLineEdit.sizeHint() one sees that a line edit is typically wide enough to display 17 latin "x" characters. I tried to replicate this in Python and change it to display 4 characters but I failed in getting the style dependent margins of the line edit correctly due to limitations of the Python binding of Qt.

A simple:

e = QtGui.QLineEdit()
fm = e.fontMetrics()
m = e.textMargins()
c = e.contentsMargins()
w = 4*fm.width('x')+m.left()+m.right()+c.left()+c.right()

is returning 24 in my case which however is not  enough to display four characters like "abcd" in a QLineEdit. A better value would be about 32 which you can set for example like.

e.setMaximumWidth(w+8) # mysterious additional factor required

which might still be okay even if the font is changed on many systems.


问:
Unix count line of file command - from java code
I'm trying to count the number of lines of a text file using a unix command from java code.

My code looks like:

```<code>String filePath = "/dir1/testFile.txt";

Runtime rt = Runtime.getRuntime();
Process p;
try {
    System.out.println("No: of lines : ");
    findLineCount = "cat " + filePath + " | wc -l";
    p = rt.exec(findLineCount);
    p.waitFor();
} catch (Exception e) {
    //code
}
</code>```

But, nothing is displayed in the console. When I execute the command directly, it works. What could be the issue in the above code?

答:
This is how i printed number of lines </p>

```<code>public static void main(String[] args) {
        try {
            Runtime run = Runtime.getRuntime();
            String[] env = new String[] { "path=%PATH%;" + "your shell path " }; //path of  cigwin  bin or any similar application. this is needed only for windows
            Process proc = run.exec(new String[] { "bash.exe", "-c", "wc -l < yourfile" }, env);
             BufferedReader reader = new BufferedReader(new InputStreamReader(
                     proc.getInputStream()));
                    String s;
                    while ((s = reader.readLine()) != null) {
                      System.out.println("Number of lines " + s);
                    }

            proc.waitFor();
            int exitValue = proc.exitValue();
            System.out.println("Status {}" +  exitValue);

        }  catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
I'm trying to count the number of lines of a text file using a unix command from java code.

My code looks like:

String filePath = "/dir1/testFile.txt";

Runtime rt = Runtime.getRuntime();
Process p;
try {
    System.out.println("No: of lines : ");
    findLineCount = "cat " + filePath + " | wc -l";
    p = rt.exec(findLineCount);
    p.waitFor();
} catch (Exception e) {
    //code
}

But, nothing is displayed in the console. When I execute the command directly, it works. What could be the issue in the above code?

Body:
This is how i printed number of lines

public static void main(String[] args) {
        try {
            Runtime run = Runtime.getRuntime();
            String[] env = new String[] { "path=%PATH%;" + "your shell path " }; //path of  cigwin  bin or any similar application. this is needed only for windows
            Process proc = run.exec(new String[] { "bash.exe", "-c", "wc -l < yourfile" }, env);
             BufferedReader reader = new BufferedReader(new InputStreamReader(
                     proc.getInputStream()));
                    String s;
                    while ((s = reader.readLine()) != null) {
                      System.out.println("Number of lines " + s);
                    }

            proc.waitFor();
            int exitValue = proc.exitValue();
            System.out.println("Status {}" +  exitValue);

        }  catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }


问:
Let users edit/delete only their own content (in generic repositories)
I want to let users only manage their own content(edit/delete/list of things... and everything need to admin panel for their own content). In my project I use unitOfwork and GenericRepositories and i have BaseRepositoy  for implementing the rest of the repositories(to avoid duplicate codes); I know I must implement user repository and use it in other repositories for getting user and continuing the operation ..., but i want to know if there's any way to implement BaseRepository?or another way to avoid manipulating repositories and writing duplicate code?

```<code>namespace ServiceLayer.Repository
{
    public abstract class BaseRepository<T> : IBaseRepository<T> where T : BaseModel
    {
        private readonly IDbSet<T> _t;
        private readonly IUnitOfWork _unitOfWork;
        private IQueryable<T> _db;
        protected BaseRepository(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _t = _unitOfWork.Set<T>();
            _db = _t;
        }
        public virtual (IQueryable<T> List, int? PageId, int? PageCount) GetAll(int? pageId, Expression<Func<T, bool>>[] searchExpression, params Expression<Func<T, object>>[] includeExpressions)
        {

            if (includeExpressions != null && includeExpressions.Any())
            {
                foreach (var expression in includeExpressions)
                {
                    _db = _db.Include(expression);
                }
            }
            if (searchExpression != null && searchExpression.Any())
            {
                foreach (var expression in searchExpression)
                {
                    _db = _db.Where(expression);
                }
            }

            if (pageId == null) return (_db, null, null);

            if (pageId <= 0)
                pageId = 1;

            int take = 5;
            int skip = ((int)pageId - 1) * take;
            int count = _db.Count();
            int pageCount = count / take;

            var list = _db.OrderByDescending(x => x.Id).Skip(skip).Take(take);
            return (list, (int)pageId, pageCount);
        }

        public virtual T Get(long id, params Expression<Func<T, object>>[] includeExpression)
        {
            if (includeExpression == null) return _t.Find(id);

            foreach (var expression in includeExpression)
            {
                _db = _db.Include(expression);
            }
            return _db.SingleOrDefault(x => x.Id == id);
        }

        public virtual List<T> GetIdsArray(long?[] ids, params Expression<Func<T, object>>[] includeExpression)
        {
            if (ids == null) return null;
            if (includeExpression == null) return _t.Where(x => ids.Contains(x.Id)).ToList();
            foreach (var expression in includeExpression)
            {
                _db = _db.Include(expression);
            }
            return _db.Where(x => ids.Contains(x.Id)).ToList();
        }

        public virtual T Update(T obj)
        {
            _unitOfWork.MarkAsChanged(obj);
            _unitOfWork.SaveAllChanges();
            return obj;
        }

        public virtual T Add(T obj)
        {
            _t.Add(obj);
            _unitOfWork.SaveAllChanges();
            return obj;
        }

        public virtual int Remove(T obj)
        {
            _t.Remove(obj);
            return _unitOfWork.SaveAllChanges();
        }

        public virtual int RemoveIdsArray(long?[] objs)
        {
            if (objs == null || objs.Length <= 0) return -5;
            var objects = GetIdsArray(objs, null);
            foreach (var o in objects)
            {
                _t.Remove(o);
            }
            return _unitOfWork.SaveAllChanges();
        }

        public virtual (string[] fieldName, IEnumerable<string> DisplayAttribute) GetAllNameAndTitleOfDbTable()
        {
            var fieldName = typeof(T).GetProperties(BindingFlags.DeclaredOnly |
                                                    BindingFlags.Public |
                                                    BindingFlags.Instance)
                .Select(property => property.Name)
                .ToArray();
            var name = typeof(T).GetProperties(BindingFlags.DeclaredOnly |
                                               BindingFlags.Public |
                                               BindingFlags.Instance).Select(property =>
                ((DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault())
                ?.Name).ToArray();
            return (fieldName, name);
        }
    }
}
</code>```

答:
I think I understand what you are trying to achieve.

Something I've done in the past is to create an IOwnedEntity interface

```<code>public interface IOwnedEntity
{
    string EntityOwner { get; set;  }
}
</code>```

which is then implemented by my models.

```<code>public string EntityOwner
{
    get { return Owner; }
    set { Owner = value; }
}
</code>```

Then in your repository you can check if T is owned and filter accordingly

```<code>private bool EntityIsOwnedByOwner(T entity)
{
    return (entity as IOwnedEntity).EntityOwner == CurrentLoggedOnUserID;
}
</code>```

Obviously this will all need a bit of work to get functioning in your example, but the approach should be sound.

Body:
I want to let users only manage their own content(edit/delete/list of things... and everything need to admin panel for their own content). In my project I use unitOfwork and GenericRepositories and i have BaseRepositoy  for implementing the rest of the repositories(to avoid duplicate codes); I know I must implement user repository and use it in other repositories for getting user and continuing the operation ..., but i want to know if there's any way to implement BaseRepository?or another way to avoid manipulating repositories and writing duplicate code?

namespace ServiceLayer.Repository
{
    public abstract class BaseRepository<T> : IBaseRepository<T> where T : BaseModel
    {
        private readonly IDbSet<T> _t;
        private readonly IUnitOfWork _unitOfWork;
        private IQueryable<T> _db;
        protected BaseRepository(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _t = _unitOfWork.Set<T>();
            _db = _t;
        }
        public virtual (IQueryable<T> List, int? PageId, int? PageCount) GetAll(int? pageId, Expression<Func<T, bool>>[] searchExpression, params Expression<Func<T, object>>[] includeExpressions)
        {

            if (includeExpressions != null && includeExpressions.Any())
            {
                foreach (var expression in includeExpressions)
                {
                    _db = _db.Include(expression);
                }
            }
            if (searchExpression != null && searchExpression.Any())
            {
                foreach (var expression in searchExpression)
                {
                    _db = _db.Where(expression);
                }
            }

            if (pageId == null) return (_db, null, null);

            if (pageId <= 0)
                pageId = 1;

            int take = 5;
            int skip = ((int)pageId - 1) * take;
            int count = _db.Count();
            int pageCount = count / take;

            var list = _db.OrderByDescending(x => x.Id).Skip(skip).Take(take);
            return (list, (int)pageId, pageCount);
        }

        public virtual T Get(long id, params Expression<Func<T, object>>[] includeExpression)
        {
            if (includeExpression == null) return _t.Find(id);

            foreach (var expression in includeExpression)
            {
                _db = _db.Include(expression);
            }
            return _db.SingleOrDefault(x => x.Id == id);
        }

        public virtual List<T> GetIdsArray(long?[] ids, params Expression<Func<T, object>>[] includeExpression)
        {
            if (ids == null) return null;
            if (includeExpression == null) return _t.Where(x => ids.Contains(x.Id)).ToList();
            foreach (var expression in includeExpression)
            {
                _db = _db.Include(expression);
            }
            return _db.Where(x => ids.Contains(x.Id)).ToList();
        }

        public virtual T Update(T obj)
        {
            _unitOfWork.MarkAsChanged(obj);
            _unitOfWork.SaveAllChanges();
            return obj;
        }

        public virtual T Add(T obj)
        {
            _t.Add(obj);
            _unitOfWork.SaveAllChanges();
            return obj;
        }

        public virtual int Remove(T obj)
        {
            _t.Remove(obj);
            return _unitOfWork.SaveAllChanges();
        }

        public virtual int RemoveIdsArray(long?[] objs)
        {
            if (objs == null || objs.Length <= 0) return -5;
            var objects = GetIdsArray(objs, null);
            foreach (var o in objects)
            {
                _t.Remove(o);
            }
            return _unitOfWork.SaveAllChanges();
        }

        public virtual (string[] fieldName, IEnumerable<string> DisplayAttribute) GetAllNameAndTitleOfDbTable()
        {
            var fieldName = typeof(T).GetProperties(BindingFlags.DeclaredOnly |
                                                    BindingFlags.Public |
                                                    BindingFlags.Instance)
                .Select(property => property.Name)
                .ToArray();
            var name = typeof(T).GetProperties(BindingFlags.DeclaredOnly |
                                               BindingFlags.Public |
                                               BindingFlags.Instance).Select(property =>
                ((DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault())
                ?.Name).ToArray();
            return (fieldName, name);
        }
    }
}

Body:
I think I understand what you are trying to achieve.

Something I've done in the past is to create an IOwnedEntity interface

public interface IOwnedEntity
{
    string EntityOwner { get; set;  }
}

which is then implemented by my models.

public string EntityOwner
{
    get { return Owner; }
    set { Owner = value; }
}

Then in your repository you can check if T is owned and filter accordingly

private bool EntityIsOwnedByOwner(T entity)
{
    return (entity as IOwnedEntity).EntityOwner == CurrentLoggedOnUserID;
}

Obviously this will all need a bit of work to get functioning in your example, but the approach should be sound.


问:
How to remove scripts tags inside another code by regex
I'm trying to remove script tags from the source code using regular expression.

```<code>/<\s*script[^>]*[^\/]>(.*?)<\s*\/\s*script\s*>/is
</code>```

But I ran into the problem when I need to remove the code inside another code.

Please see this screenshot

I'm tested in https://regex101.com/r/R6XaUT/1

How do I correctly create a regular expression so that it can cover all the code?

答:
Sample text:

```<code>$text = '<b>sample</b> text with <div>tags</div>';
</code>```

Result for strip_tags($text):

```<code>Output: sample text with tags
</code>```

Result for strip_tags_content($text):

```<code>Output: text with
</code>```

Result for strip_tags_content($text, ''):

```<code>Output: <b>sample</b> text with
</code>```

Result for strip_tags_content($text, '', TRUE);

```<code>Output: text with <div>tags</div>
</code>```

I hope that someone is useful :)
source link

Body:
I'm trying to remove script tags from the source code using regular expression.

/<\s*script[^>]*[^\/]>(.*?)<\s*\/\s*script\s*>/is

But I ran into the problem when I need to remove the code inside another code.

Please see this screenshot

I'm tested in https://regex101.com/r/R6XaUT/1

How do I correctly create a regular expression so that it can cover all the code?

Body:
Sample text:

$text = '<b>sample</b> text with <div>tags</div>';

Result for strip_tags($text):

Output: sample text with tags

Result for strip_tags_content($text):

Output: text with

Result for strip_tags_content($text, ''):

Output: <b>sample</b> text with

Result for strip_tags_content($text, '', TRUE);

Output: text with <div>tags</div>

I hope that someone is useful :)
source link


问:
Can a Cassandra snapshot be restored with a lower replication factor on fewer nodes?
I am using this tool to take Cassandra snapshots of a keyspace:
https://github.com/AppliedInfrastructure/cassandra-snapshot-tools

This keyspace has a replication factor of 3 and is hosted on 3 nodes.
Is there a way to fully restore it locally on a single-node Cassandra instance with a replication factor of 1?

I tried restoring this way:

```<code>sudo bash ./putSnapshot -f backup-20171114152959.tar.gz -n 192.168.0.172 -k backup_restored -d datacenter1 -r 1
</code>```

-r 1 option should override the replication factor.

While it did work, it seems like some information is missing.

My first guess is that it only restored the data from the first node of 3.

From what I can see only the data from one table is missing and I saw this error when I restored the backup:

Failed to list files in
  /home/ubuntu/putSnapshot.tmp7564/backup/user-fade6090bee711e7bf39db885b6c90ca

Caused by: java.lang.RuntimeException: Unknown column device during
  deserialization

So my other guess is that the data was restored from all 3 nodes into 1, but there was an issue with restoring one of the tables in the keyspace. What could cause such an error?

答:
Yes, it most likely only restored data from one node. Use sstableloader instead as it has the ability to:

Load existing SSTables into another cluster with a different number of nodes or replication strategy.

https://docs.datastax.com/en/cassandra/3.0/cassandra/tools/toolsBulkloader.html

Body:
I am using this tool to take Cassandra snapshots of a keyspace:
https://github.com/AppliedInfrastructure/cassandra-snapshot-tools

This keyspace has a replication factor of 3 and is hosted on 3 nodes.
Is there a way to fully restore it locally on a single-node Cassandra instance with a replication factor of 1?

I tried restoring this way:

sudo bash ./putSnapshot -f backup-20171114152959.tar.gz -n 192.168.0.172 -k backup_restored -d datacenter1 -r 1

-r 1 option should override the replication factor.

While it did work, it seems like some information is missing.

My first guess is that it only restored the data from the first node of 3.

From what I can see only the data from one table is missing and I saw this error when I restored the backup:

Failed to list files in
  /home/ubuntu/putSnapshot.tmp7564/backup/user-fade6090bee711e7bf39db885b6c90ca

Caused by: java.lang.RuntimeException: Unknown column device during
  deserialization

So my other guess is that the data was restored from all 3 nodes into 1, but there was an issue with restoring one of the tables in the keyspace. What could cause such an error?


问:
How to edit application configuration settings? App.config best way to go?
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

```<code>    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }
</code>```

Gives me a read-only error when I compile.

答:
How are you referencing the Settings class in your code?  Are you using the default instance or creating a new Settings object?  I believe that the default instance uses the designer generated value which is re-read from the configuration file only when the properties are opened.  If you create a new object, I believe that the value is read directly from the configuration file itself rather from the designer-generated attribute, unless the setting doesn't exist in the app.config file.

Typically my settings will be in a library rather than directly in the application.  I set valid defaults in the properties file.  I can then override these by adding the appropriate config section (retrieved and modified from the library app.config file) in the application's configuration (either web.config or app.config, as appropriate).

Using:

```<code> Settings configuration = new Settings();
 string mySetting = configuration.MySetting;
</code>```

instead of:

```<code> string mySetting = Settings.Default.MySetting;
</code>```

is the key for me.

OwnerDisplayName: MattRuma

Body:
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

Gives me a read-only error when I compile.

LastEditorDisplayName: MattRuma

Body:
How are you referencing the Settings class in your code?  Are you using the default instance or creating a new Settings object?  I believe that the default instance uses the designer generated value which is re-read from the configuration file only when the properties are opened.  If you create a new object, I believe that the value is read directly from the configuration file itself rather from the designer-generated attribute, unless the setting doesn't exist in the app.config file.

Typically my settings will be in a library rather than directly in the application.  I set valid defaults in the properties file.  I can then override these by adding the appropriate config section (retrieved and modified from the library app.config file) in the application's configuration (either web.config or app.config, as appropriate).

Using:

 Settings configuration = new Settings();
 string mySetting = configuration.MySetting;

instead of:

 string mySetting = Settings.Default.MySetting;

is the key for me.

OwnerDisplayName: tvanfosson


问:
Console Error with CCParallaxNode and crash
I'm getting an error in the console that reads
Assertion failure in -[CCParallaxNode addChild:z:tag:]
This is for the code

```<code>    CGSize winSize = [[CCDirector sharedDirector] winSize];
    node = info;
    voidNode = [CCParallaxNode node];
    [voidNode addChild:node z:2 parallaxRatio:ccp(0.0f, 1.0f) positionOffset:ccp(info.contentSize.width/2, info.contentSize.height/2 - winSize.height)];
    [self addChild:voidNode z:2 tag:kTagNode];
</code>```

Not very familiar with debugging with the console

答: Why don't you simply put there a breakpoint and see what is happening ?  Every time i had such error the problem was trying to add a nil child to the parent (there is an assertation of it in a addChild method

Body:
I'm getting an error in the console that reads
Assertion failure in -[CCParallaxNode addChild:z:tag:]
This is for the code

    CGSize winSize = [[CCDirector sharedDirector] winSize];
    node = info;
    voidNode = [CCParallaxNode node];
    [voidNode addChild:node z:2 parallaxRatio:ccp(0.0f, 1.0f) positionOffset:ccp(info.contentSize.width/2, info.contentSize.height/2 - winSize.height)];
    [self addChild:voidNode z:2 tag:kTagNode];

Not very familiar with debugging with the console


问:
Corda: How to add custom validating code for every node on a particular transacting state in Corda
In the Corda-example, if we want to add custom validating code, we can override checkTransaction() in the responder codes to make sure the IOU is above a certain threshold. This assumes that all responders are agreeable to that threshold.

What if we allow every lender to set their own threshold. In that case the threshold becomes a variable. To address this, I created a UI that directly publishes the threshold (an integer) to the database. However I am finding it hard to extract the value and passing it to a threshold variable in the flow code. Is there a better way? If this works, I can quarantine more variables and using the UI for individual nodes, I get to set custom parameters (into the database) used in the validation of the state in the Tx.

答:
The easiest way to achieve this is to provide a different implementation of the flow for each node. For example, if you had an AcceptTxBasedOnThreshold flow, you'd create several implementations:

One AcceptTxBasedOnThreshold flow implementation for NodeA, which perhaps has a threshold of 10

One AcceptTxBasedOnThreshold flow implementation for NodeB, which perhaps has a threshold of 20 instead

And so on for any additional nodes...

You'd then create several CorDapps:

The first CorDapp would include the shared state and contract definitions that everyone uses. You'd install this CorDapp on every node. This CorDapp wouldn't include any flow definitions

You'd then create an additional CorDapp for each node:

A CorDapp with only NodeA's AcceptTxBasedOnThreshold flow. This CorDapp would only be installed by NodeA

A CorDapp with only NodeB's AcceptTxBasedOnThreshold flow. This CorDapp would only be installed by NodeB


问:
insert into / copy data from table to same with some changing value PL-SQL
```<code>BEGIN
  FOR i IN (select * from Mpl_Form_Responses t  WHERE t.form_ID = 1944 and t.response_id > 15) LOOP
    INSERT INTO Mpl_Form_Responses
      (Form_Id, Response_Id,remarks, Userid)
    VALUES
      (7399, i.RESPONSE_ID,i.remarks, i.userid);
  END LOOP;
END;
</code>```

anyone know why its not working

答:
You can select rows and insert them to the same table with some changing like this:</p>

```<code>INSERT INTO Mpl_Form_Responses(Form_Id, Response_Id,remarks + 'edited', Userid)
select  7399, t.Response_Id, t.remarks, t.Userid
from  Mpl_Form_Responses t
WHERE t.form_ID = 1944
</code>```

Body:
BEGIN
  FOR i IN (select * from Mpl_Form_Responses t  WHERE t.form_ID = 1944 and t.response_id > 15) LOOP
    INSERT INTO Mpl_Form_Responses
      (Form_Id, Response_Id,remarks, Userid)
    VALUES
      (7399, i.RESPONSE_ID,i.remarks, i.userid);
  END LOOP;
END;

anyone know why its not working

Body:
You can select rows and insert them to the same table with some changing like this:

INSERT INTO Mpl_Form_Responses(Form_Id, Response_Id,remarks + 'edited', Userid)
select  7399, t.Response_Id, t.remarks, t.Userid
from  Mpl_Form_Responses t
WHERE t.form_ID = 1944


问:
Unable to start Apache on CentOS Private Key Not Found
I am unable to start Apache on a CentOS Server with SELinux. The error log gives.

```<code>[root@server httpd]# cat test-error_log
[Wed Nov 15 05:42:34 2017] [error] Init: Private key not found
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218640442 error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 67710980 error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error
</code>```

It fails here also

```<code>[root@server private]#  openssl rsa -in test.key -check -noout
unable to load Private Key
140598241089352:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140598241089352:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=RSA
140598241089352:error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib:rsa_ameth.c:115:
140598241089352:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140598241089352:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=PKCS8_PRIV_KEY_INFO
140598241089352:error:0907B00D:PEM routines:PEM_READ_BIO_PRIVATEKEY:ASN1 lib:pem_pkey.c:132:
</code>```

The path is in the conf file

```<code>[root@server conf]# cat /etc/httpd/conf.d/test.conf
<VirtualHost *:443>
ServerAdmin webmaster@server.com
DocumentRoot /var/www/html/test
ServerName server.server.com

SSLEngine on
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
SSLCertificateFile /etc/pki/tls/certs/test.crt
SSLCertificateKeyFile /etc/pki/tls/private/test.key

ErrorLog logs/test-error_log
CustomLog logs/test-access_log common
</code>```

I also checked there are no spaces in the Private Key. Any other ideas where this is going wrong?

Also

```<code>[root@server etc]#  ls -dZ /etc/pki/tls/private/
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /etc/pki/tls/private/
[root@server etc]#  ls -dZ /etc/pki/tls/certs/
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /etc/pki/tls/certs/
</code>```

I have also checked there are no spaces in the Private Key and appropriate number of dashes.

EDIT: Output of ls -al /etc/pki/tls/private/ and ls -al /etc/pki/tls/certs/

```<code>[root@server ~]# ls -al /etc/pki/tls/certs/
total 1788
drwxr-xr-x. 2 root root    4096 Nov 15 08:51 .
drwxr-xr-x. 5 root root    4096 Feb 11  2015 ..
-rw-r--r--. 1 root root  786601 Jul 14  2014 ca-bundle.crt
-rw-r--r--. 1 root root 1005005 Jul 14  2014 ca-bundle.trust.crt
-rw-------. 1 root root    1513 Feb 11  2015 localhost.crt
-rwxr-xr-x. 1 root root     610 Jan 20  2015 make-dummy-cert
-rw-r--r--. 1 root root    2242 Jan 20  2015 Makefile
-rwxr-xr-x. 1 root root     829 Jan 20  2015 renew-dummy-cert
-rw-r--r--. 1 root root    1208 Feb 11  2015 test.crt
-rw-------. 1 root root    3258 Nov 15 08:51 test_1.cert
[root@ip-10-155-16-219 ~]# ls -al /etc/pki/tls/private/
total 16
drwxr-xr-x. 2 root root 4096 Nov 18 21:15 .
drwxr-xr-x. 5 root root 4096 Feb 11  2015 ..
-rw-------. 1 root root 1679 Feb 11  2015 localhost.key
-rw-r--r--. 1 root root 1679 Nov 18 21:15 test.key
[root@server ~]#
</code>```

答:
Is you private key encrypted?
To determine if your private key is encrypted:

```<code>grep ENCRYPTED /etc/pki/tls/private/test.key
</code>```

If yes, remove the password from the private key:

```<code>openssl rsa -in /etc/pki/tls/private/test.key -out /etc/pki/tls/private/test-new.key
</code>```

Check the header of your private key, should look like this:

```<code>-----BEGIN RSA PRIVATE KEY-----
</code>```

And check the footer, should look like this:

```<code>-----END RSA PRIVATE KEY-----
</code>```

Remove any space or newline after the footer.

Hope this helps

Body:
I am unable to start Apache on a CentOS Server with SELinux. The error log gives.

[root@server httpd]# cat test-error_log
[Wed Nov 15 05:42:34 2017] [error] Init: Private key not found
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218640442 error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 67710980 error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed Nov 15 05:42:34 2017] [error] SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error

It fails here also

[root@server private]#  openssl rsa -in test.key -check -noout
unable to load Private Key
140598241089352:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140598241089352:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=RSA
140598241089352:error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib:rsa_ameth.c:115:
140598241089352:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140598241089352:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=PKCS8_PRIV_KEY_INFO
140598241089352:error:0907B00D:PEM routines:PEM_READ_BIO_PRIVATEKEY:ASN1 lib:pem_pkey.c:132:

The path is in the conf file

[root@server conf]# cat /etc/httpd/conf.d/test.conf
<VirtualHost *:443>
ServerAdmin webmaster@server.com
DocumentRoot /var/www/html/test
ServerName server.server.com

SSLEngine on
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
SSLCertificateFile /etc/pki/tls/certs/test.crt
SSLCertificateKeyFile /etc/pki/tls/private/test.key

ErrorLog logs/test-error_log
CustomLog logs/test-access_log common

I also checked there are no spaces in the Private Key. Any other ideas where this is going wrong?

Also

[root@server etc]#  ls -dZ /etc/pki/tls/private/
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /etc/pki/tls/private/
[root@server etc]#  ls -dZ /etc/pki/tls/certs/
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /etc/pki/tls/certs/

I have also checked there are no spaces in the Private Key and appropriate number of dashes.

EDIT: Output of ls -al /etc/pki/tls/private/ and ls -al /etc/pki/tls/certs/

[root@server ~]# ls -al /etc/pki/tls/certs/
total 1788
drwxr-xr-x. 2 root root    4096 Nov 15 08:51 .
drwxr-xr-x. 5 root root    4096 Feb 11  2015 ..
-rw-r--r--. 1 root root  786601 Jul 14  2014 ca-bundle.crt
-rw-r--r--. 1 root root 1005005 Jul 14  2014 ca-bundle.trust.crt
-rw-------. 1 root root    1513 Feb 11  2015 localhost.crt
-rwxr-xr-x. 1 root root     610 Jan 20  2015 make-dummy-cert
-rw-r--r--. 1 root root    2242 Jan 20  2015 Makefile
-rwxr-xr-x. 1 root root     829 Jan 20  2015 renew-dummy-cert
-rw-r--r--. 1 root root    1208 Feb 11  2015 test.crt
-rw-------. 1 root root    3258 Nov 15 08:51 test_1.cert
[root@ip-10-155-16-219 ~]# ls -al /etc/pki/tls/private/
total 16
drwxr-xr-x. 2 root root 4096 Nov 18 21:15 .
drwxr-xr-x. 5 root root 4096 Feb 11  2015 ..
-rw-------. 1 root root 1679 Feb 11  2015 localhost.key
-rw-r--r--. 1 root root 1679 Nov 18 21:15 test.key
[root@server ~]#

Body:
Is you private key encrypted?
To determine if your private key is encrypted:

grep ENCRYPTED /etc/pki/tls/private/test.key

If yes, remove the password from the private key:

openssl rsa -in /etc/pki/tls/private/test.key -out /etc/pki/tls/private/test-new.key

Check the header of your private key, should look like this:

-----BEGIN RSA PRIVATE KEY-----

And check the footer, should look like this:

-----END RSA PRIVATE KEY-----

Remove any space or newline after the footer.

Hope this helps


问:
HTML/CSS: Why doesn't scrolling work in iframe?
I have a website with 3 iframes and none of them works, although the text is longer than the windows: in Firefox the scroll bars appear but don't work; in Chrome the bars don't even appear. They do scroll in IE 6.

So I suspect there is a problem with the CSS. Probably it's something trivial, but I fail to see it.

CSS code:

```<code>.header
{
position:fixed;
top:0%;
right:0%;
height:4%;
width:100%;
text-align:center;
background-color:#BF1E4B;
font-family: "Trebuchet MS",Arial,Helvetica,sans-serif;
z-index:+1;
}

.nav,.nav ul
{
list-style:none;
margin:0.5%;
padding:0;
}

.nav
{
top:0%;
left:0%;
position:absolute;
}

.nav ul
{
height:0;
left:0;
position:absolute;
overflow:hidden;
top:100%;
}

.nav li
{
float:left;
position:relative;
}

.nav li a
{
-moz-transition:0.1s;
-o-transition:0.1s;
-webkit-transition:0.1s;
background-color:#BF1E4B;
color:#fff;
display:block;
font-size:100%;
line-height:100%;
padding:4px 35px;
text-decoration:none;
transition:0.1s;
}

.nav li:hover > a
{
background:#000;
color:#fff;
}

.nav li:hover ul.subs
{
height:auto;
 width:100%;
}

.nav ul li
{
-moz-transition:0.1s;
-o-transition:0.1s;
-webkit-transition:0.1s;
opacity:0;
transition:0.1s;
width:100%;
}

.nav li:hover ul li
{
opacity:1;
-moz-transition-delay:0.1s;
-o-transition-delay:0.1s;
-webkit-transition-delay:0.1s;
transition-delay:0.1s;
}

.nav ul li a
{
background:#BF1E4B;
color:#fff;
line-height:0%;
-moz-transition:0.1s;
-o-transition:0.1s;
-webkit-transition:0.1s;
transition:0.1s;
}

.nav li:hover ul li a {
    line-height:150%;
}

.nav ul li a:hover
{
background:#000;
}

.iframe1
{
position:fixed;
bottom:48%;
right:0%;
height:48%;
width:50%;
}

.iframe2
{
position:fixed;
top:4%;
left:0%;
height:96%;
width:50%;
}

.iframe3
{
position:fixed;
top:52%;
right:0%;
height:48%;
width:50%;
}
</code>```

Sorry for the amateur look, and thanks in advance :)

HTML code:

```<code><div class="header">
<ul class="nav">

<li><a href="">Links</a>
<ul class="subs">
<li><a href="xxx" target="_blank">link</a></li>
<li><a href="xxx" target="_blank">link</a></li>
<li><a href="xxx" target="_blank">link</a></li>
</ul>
</li>

</li>
</ul>
<div style="clear:both"></div>
</div>

<div class="iframe1">
<iframe src="xxx" width=100% height=100% scrolling="yes"></iframe>
</div>

<div class="iframe2"">
<iframe src="xxx" width=100% height=100% scrolling="yes"></iframe>
</div>

<div class="iframe3">
<iframe src="xxx" width=100% height=100% scrolling="yes"></iframe>
</div>
</code>```

答:
try playing with the z-index value, you might cover it, change it to 1000 in the iframe and see you still cant use it</p>

```<code>{
   z-index: 1000;
}
</code>```

Body:
I have a website with 3 iframes and none of them works, although the text is longer than the windows: in Firefox the scroll bars appear but don't work; in Chrome the bars don't even appear. They do scroll in IE 6.

So I suspect there is a problem with the CSS. Probably it's something trivial, but I fail to see it.

CSS code:

.header
{
position:fixed;
top:0%;
right:0%;
height:4%;
width:100%;
text-align:center;
background-color:#BF1E4B;
font-family: "Trebuchet MS",Arial,Helvetica,sans-serif;
z-index:+1;
}

.nav,.nav ul
{
list-style:none;
margin:0.5%;
padding:0;
}

.nav
{
top:0%;
left:0%;
position:absolute;
}

.nav ul
{
height:0;
left:0;
position:absolute;
overflow:hidden;
top:100%;
}

.nav li
{
float:left;
position:relative;
}

.nav li a
{
-moz-transition:0.1s;
-o-transition:0.1s;
-webkit-transition:0.1s;
background-color:#BF1E4B;
color:#fff;
display:block;
font-size:100%;
line-height:100%;
padding:4px 35px;
text-decoration:none;
transition:0.1s;
}

.nav li:hover > a
{
background:#000;
color:#fff;
}

.nav li:hover ul.subs
{
height:auto;
 width:100%;
}

.nav ul li
{
-moz-transition:0.1s;
-o-transition:0.1s;
-webkit-transition:0.1s;
opacity:0;
transition:0.1s;
width:100%;
}

.nav li:hover ul li
{
opacity:1;
-moz-transition-delay:0.1s;
-o-transition-delay:0.1s;
-webkit-transition-delay:0.1s;
transition-delay:0.1s;
}

.nav ul li a
{
background:#BF1E4B;
color:#fff;
line-height:0%;
-moz-transition:0.1s;
-o-transition:0.1s;
-webkit-transition:0.1s;
transition:0.1s;
}

.nav li:hover ul li a {
    line-height:150%;
}

.nav ul li a:hover
{
background:#000;
}

.iframe1
{
position:fixed;
bottom:48%;
right:0%;
height:48%;
width:50%;
}

.iframe2
{
position:fixed;
top:4%;
left:0%;
height:96%;
width:50%;
}

.iframe3
{
position:fixed;
top:52%;
right:0%;
height:48%;
width:50%;
}

Sorry for the amateur look, and thanks in advance :)

HTML code:

Links

link

link

link

Body:
try playing with the z-index value, you might cover it, change it to 1000 in the iframe and see you still cant use it

{
   z-index: 1000;
}


问:
Java: I want to get TextField value when I clicked a button. How to do it?
```<code>public Monster createCharacterScene() {
    String name;
    TextField nameTextField = new TextField();
    nameTextField.setLocation(65, 50);
    nameTextField.setSize(60, 10);
    Button myButton = new Button("OK");
    myButton.setLocation(25, 50);
    myButton.setSize(30, 40);
    add(myButton);
    add(nameTextField);
    myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            name = nameTextField.getText();
        }
    });
    return null;
}
</code>```

I can't do it like this. They says "local variables referenced from an inner class must be final or effectively final". Is there alternative way to do it?

Thanks a lot.

PS. I using applet.

答:
You cannot read this value directly in createCharacterScene() method. Because it's unknown yet. The only thing you can do is to define a eventHandler, that will be triggered, on key press.

```<code>Consumer<String> nameConsumer = text -> { /*You will handle event here*/};
myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameConsumer.apply(nameTextField.getText());
        }
    });
</code>```

The cheaper version would be to use a small workaround for final modifier:

```<code>final String[] nameHolder = new String[1];
myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameHolder[0] = nameTextField.getText();
        }
    });
</code>```

Here nameHolder will initially hold null, but when someone will trigger the event, it's value will be set, so you need to check if value is set or not.

Body:
public Monster createCharacterScene() {
    String name;
    TextField nameTextField = new TextField();
    nameTextField.setLocation(65, 50);
    nameTextField.setSize(60, 10);
    Button myButton = new Button("OK");
    myButton.setLocation(25, 50);
    myButton.setSize(30, 40);
    add(myButton);
    add(nameTextField);
    myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            name = nameTextField.getText();
        }
    });
    return null;
}

I can't do it like this. They says "local variables referenced from an inner class must be final or effectively final". Is there alternative way to do it?

Thanks a lot.

PS. I using applet.

Body:
You cannot read this value directly in createCharacterScene() method. Because it's unknown yet. The only thing you can do is to define a eventHandler, that will be triggered, on key press.

Consumer<String> nameConsumer = text -> { /*You will handle event here*/};
myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameConsumer.apply(nameTextField.getText());
        }
    });

The cheaper version would be to use a small workaround for final modifier:

final String[] nameHolder = new String[1];
myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameHolder[0] = nameTextField.getText();
        }
    });

Here nameHolder will initially hold null, but when someone will trigger the event, it's value will be set, so you need to check if value is set or not.