问:
Can't add a div using javascript where cakephp is used
I am working with cakephp.

I want to add a
 dynamically each time I press a button. My code works if I don't add array("type"=>"select"));

```<code>var div = document.createElement('div');
div.className = 'dataN' ;
div.innerHTML='<table border="0" cellpadding="0" cellspacing="0"      style="text-align: left;"></table>\n\
<tr>\n\
<td width="150px" style="text-align:center;background:#D9D9D9;">Step 1-Select Program Country </td>\n\
<td width="250px" style="padding-left:10px;"><?php echo $this->form->input("Proposal.program_country", array("type"=>"select")); ?></td></tr>\n\
</tr>';
document.getElementById('data').appendChild(div);
</code>```

答:
Have you tried changing the "type" => "select" to "options" => array()? Have not seen any other way to create a select tag in CakePHP 2.x form helper other than this one.

Please refer to this part of the CookBook.

Body:
I am working with cakephp.

I want to add a
 dynamically each time I press a button. My code works if I don't add array("type"=>"select"));

var div = document.createElement('div');
div.className = 'dataN' ;
div.innerHTML='

\n\

\n\
Step 1-Select Program Country 	\n\
<?php echo $this->form->input("Proposal.program_country", array("type"=>"select")); ?>
\n\

';
document.getElementById('data').appendChild(div);


来源: stackexchange

问:
Allure @Step(String s, byte[] b) when b is large (2.12.1 allure)
Allure 2.12.1
Have out of memory troubles on processing allure @Step
for large array byte[]

```<code>@Step
public void test(String s, byte[] b){}
</code>```

Here is the stack trace:

```<code>java.lang.AssertionError: java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:674)
at java.lang.StringBuilder.append(StringBuilder.java:208)
at java.util.Arrays.toString(Arrays.java:4446)
at io.qameta.allure.util.ObjectUtils.toString(ObjectUtils.java:70)
at io.qameta.allure.util.ResultsUtils.createParameter(ResultsUtils.java:110)
at io.qameta.allure.util.AspectUtils.lambda$getParameters$2(AspectUtils.java:63)
at io.qameta.allure.util.AspectUtils$$Lambda$488/432285879.apply(Unknown Source)
at java.util.stream.IntPipeline$4$1.accept(IntPipeline.java:250)
at java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:110)
at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at io.qameta.allure.util.AspectUtils.getParameters(AspectUtils.java:64)
at io.qameta.allure.aspects.StepsAspects.stepStart(StepsAspects.java:72)
</code>```

is there a way to avoid reporting all method parameters ?

答:
Found answer on allure gitter. Using

```<code>Allure.step("stepName", (step) -> {})
</code>```

allure-framework/allure-java#282

ContentLicense: CC BY-SA 4.0

Body:
Allure 2.12.1
Have out of memory troubles on processing allure @Step
for large array byte[]

@Step
public void test(String s, byte[] b){}

Here is the stack trace:

java.lang.AssertionError: java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:674)
at java.lang.StringBuilder.append(StringBuilder.java:208)
at java.util.Arrays.toString(Arrays.java:4446)
at io.qameta.allure.util.ObjectUtils.toString(ObjectUtils.java:70)
at io.qameta.allure.util.ResultsUtils.createParameter(ResultsUtils.java:110)
at io.qameta.allure.util.AspectUtils.lambda$getParameters$2(AspectUtils.java:63)
at io.qameta.allure.util.AspectUtils$$Lambda$488/432285879.apply(Unknown Source)
at java.util.stream.IntPipeline$4$1.accept(IntPipeline.java:250)
at java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:110)
at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at io.qameta.allure.util.AspectUtils.getParameters(AspectUtils.java:64)
at io.qameta.allure.aspects.StepsAspects.stepStart(StepsAspects.java:72)

is there a way to avoid reporting all method parameters ?

Body:
Found answer on allure gitter. Using

Allure.step("stepName", (step) -> {})

allure-framework/allure-java#282


问:
Pytorch method for conditional use of intermediate layer instead of final cnn layer output. ie: allow nn to learn to use more layers or less
I'm implementing a residual cnn(modified smaller version of xception) in a low latency environment. I've done a lot of manual tuning to minimize the run time speed of my network (reducing number of filters, removing layers, etc).

But now I want to try allowing my network to make its classification prediction(final fcnn layer) on the residual connection after each residual block.

basic logic-

attempt final prediction with residual connection as input

if this fcnn layer predicts a certain class with a probability > a set threshold:

```<code>return fcnn output as if it was normal final layer
</code>```

else:

```<code>do next residual block like normal and try the previous conditional again unless we are already at final block
</code>```

My hope is this will allow my network to learn to solve easier problems with less computation while allowing it to still do the additional layers if it is still unsure of the classification.

So my basic question is: In pytorch, whats the best way to implement this conditional in a way that allows my nn at run time to decide whether to do more processing or not

Currently Ive tested returning the intermediate x's after the blocks in the forward function, but I dont know how best to setup the conditional to chose which x to return

Also side note: I believe I may end up needing another cnn layer between the residual and fcnn to serve as a function to convert the internal representation for processing to a representation the fcnn understands for classification.

答:
It has already been done and presented in ICLR 2018.

It appears as if in ResNets the first few bottlenecks learn representations (and therefore cannot be skipped) while the remaining bottlenecks refine the features and therefore can be skipped at a moderate loss of accuracy. (Stanisław Jastrzebski, Devansh Arpit, Nicolas Ballas, Vikas Verma, Tong Che, Yoshua Bengio Residual Connections Encourage Iterative Inference, ICLR 2018).

This idea was taken to the extreme with sharing weights across bottlenecks in Sam Leroux, Pavlo Molchanov, Pieter Simoens, Bart Dhoedt, Thomas Breuel, Jan Kautz IamNN: Iterative and Adaptive Mobile Neural Network for efficient image classification, ICLR 2018.

Body:
I'm implementing a residual cnn(modified smaller version of xception) in a low latency environment. I've done a lot of manual tuning to minimize the run time speed of my network (reducing number of filters, removing layers, etc).

But now I want to try allowing my network to make its classification prediction(final fcnn layer) on the residual connection after each residual block.

basic logic-

attempt final prediction with residual connection as input

if this fcnn layer predicts a certain class with a probability > a set threshold:

return fcnn output as if it was normal final layer

else:

do next residual block like normal and try the previous conditional again unless we are already at final block

My hope is this will allow my network to learn to solve easier problems with less computation while allowing it to still do the additional layers if it is still unsure of the classification.

So my basic question is: In pytorch, whats the best way to implement this conditional in a way that allows my nn at run time to decide whether to do more processing or not

Currently Ive tested returning the intermediate x's after the blocks in the forward function, but I dont know how best to setup the conditional to chose which x to return

Also side note: I believe I may end up needing another cnn layer between the residual and fcnn to serve as a function to convert the internal representation for processing to a representation the fcnn understands for classification.


问:
Android - in Android Pie (API 28) RadialGradient draws a rectangle instead of a circle
I'm trying to simulate a TorchView with a background image and a foreground image. It works well on API 27 and below, but draw a rectangle on API 28.

Any idea why it doesn't work on Android Pie?

On API 27 and below
API 28

Torch View class:

```
class TorchView : View, OnTouchListener {

    var mBitmapBackground: Bitmap? = null
    var mBitmapForeground: Bitmap? = null
    var mMask: Bitmap? = null
    private var mPosX = 0f
    private var mPosY = 0f

    private lateinit var paintMask: Paint
    private lateinit var paintBackground: Paint
    private lateinit var paintForeground: Paint

    private var radius = 150

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    fun initBitmaps(bitmapBackground: Bitmap, bitmapForeground: Bitmap, radius: Int){
        this.radius = radius
        mBitmapBackground = bitmapBackground
        mBitmapForeground = bitmapForeground
        mMask = makeRadGrad()
        mPosX = (bitmapBackground.width/2 - radius).toFloat()
        mPosY = (bitmapBackground.height/2 - radius).toFloat()
        invalidate()
    }

    fun init() {
        paintBackground = Paint()

        paintMask = Paint()
        paintMask.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)

        paintForeground = Paint()
        paintForeground.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)

        isFocusable = true
        isFocusableInTouchMode = true
        this.setOnTouchListener(this)
    }

    public override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val mask = mMask
        val bitmapForeground = mBitmapBackground
        val bitmapBackground = mBitmapForeground
        if(mask != null && bitmapForeground != null && bitmapBackground != null){
            canvas.save()
            canvas.drawBitmap(bitmapBackground, 0f, 0f, paintBackground)
            canvas.drawBitmap(mask, mPosX, mPosY, paintMask)
            canvas.drawBitmap(bitmapForeground, 0f, 0f, paintForeground)
            canvas.restore()
        }
    }

    private fun makeRadGrad(): Bitmap {
        val gradient = RadialGradient(
            radius.toFloat(), radius.toFloat(), radius.toFloat(), -0xff0100,
            0x00000000, android.graphics.Shader.TileMode.CLAMP
        )
        val p = Paint()
        p.isDither = true
        p.shader = gradient

        val bitmap = Bitmap.createBitmap(radius*2, radius*2, Config.ARGB_8888)
        val c = Canvas(bitmap)
        c.drawCircle(radius.toFloat(), radius.toFloat(), radius.toFloat(), p)

        return bitmap
    }

    override fun onTouch(v: View?, event: MotionEvent): Boolean {
        mPosX = event.x - radius
        mPosY = event.y - radius
        invalidate()
        return true
    }
}
```

答:
check this https://issuetracker.google.com/issues/111819103

try this

```<code> public override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    val mask = mMask
    val bitmapForeground = mBitmapBackground
    val bitmapBackground = mBitmapForeground
    if(mask != null && bitmapForeground != null && bitmapBackground != null){
        canvas.save()
        canvas.drawBitmap(bitmapBackground, 0f, 0f, paintBackground)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            makeRadGradP(canvas, bitmapForeground)
        } else {
            canvas.drawBitmap(mask, mPosX, mPosY, paintMask)
            canvas.drawBitmap(bitmapForeground, 0f, 0f, paintForeground)
         }
        canvas.restore()
    }
}

private fun makeRadGradP(canvas: Canvas, bm: Bitmap) {
        val paint = Paint()
        paint.style = Paint.Style.FILL
        val shader = BitmapShader(bm, TileMode.CLAMP, TileMode.CLAMP)
        paint.shader = shader
        val corners = Path()
        corners.addCircle(mPosX + radius, mPosY + radius, radius.toFloat(), Path.Direction.CW)
        canvas.drawPath(corners, paint)

        val gradient = RadialGradient(
                mPosX + radius, mPosY + radius, radius.toFloat(), 0x00000000,
                Color.parseColor("#df000000"), TileMode.CLAMP
        )
        val p = Paint()
        p.isDither = true
        p.shader = gradient
        canvas.drawCircle(mPosX + radius, mPosY + radius, radius.toFloat(), p)
 }
</code>```

Body:
I'm trying to simulate a TorchView with a background image and a foreground image. It works well on API 27 and below, but draw a rectangle on API 28.

Any idea why it doesn't work on Android Pie?

On API 27 and below
API 28

Torch View class:

class TorchView : View, OnTouchListener {

    var mBitmapBackground: Bitmap? = null
    var mBitmapForeground: Bitmap? = null
    var mMask: Bitmap? = null
    private var mPosX = 0f
    private var mPosY = 0f

    private lateinit var paintMask: Paint
    private lateinit var paintBackground: Paint
    private lateinit var paintForeground: Paint

    private var radius = 150

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    fun initBitmaps(bitmapBackground: Bitmap, bitmapForeground: Bitmap, radius: Int){
        this.radius = radius
        mBitmapBackground = bitmapBackground
        mBitmapForeground = bitmapForeground
        mMask = makeRadGrad()
        mPosX = (bitmapBackground.width/2 - radius).toFloat()
        mPosY = (bitmapBackground.height/2 - radius).toFloat()
        invalidate()
    }

    fun init() {
        paintBackground = Paint()

        paintMask = Paint()
        paintMask.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)

        paintForeground = Paint()
        paintForeground.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)

        isFocusable = true
        isFocusableInTouchMode = true
        this.setOnTouchListener(this)
    }

    public override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val mask = mMask
        val bitmapForeground = mBitmapBackground
        val bitmapBackground = mBitmapForeground
        if(mask != null && bitmapForeground != null && bitmapBackground != null){
            canvas.save()
            canvas.drawBitmap(bitmapBackground, 0f, 0f, paintBackground)
            canvas.drawBitmap(mask, mPosX, mPosY, paintMask)
            canvas.drawBitmap(bitmapForeground, 0f, 0f, paintForeground)
            canvas.restore()
        }
    }

    private fun makeRadGrad(): Bitmap {
        val gradient = RadialGradient(
            radius.toFloat(), radius.toFloat(), radius.toFloat(), -0xff0100,
            0x00000000, android.graphics.Shader.TileMode.CLAMP
        )
        val p = Paint()
        p.isDither = true
        p.shader = gradient

        val bitmap = Bitmap.createBitmap(radius*2, radius*2, Config.ARGB_8888)
        val c = Canvas(bitmap)
        c.drawCircle(radius.toFloat(), radius.toFloat(), radius.toFloat(), p)

        return bitmap
    }

    override fun onTouch(v: View?, event: MotionEvent): Boolean {
        mPosX = event.x - radius
        mPosY = event.y - radius
        invalidate()
        return true
    }
}

Body:
check this https://issuetracker.google.com/issues/111819103

try this

 public override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    val mask = mMask
    val bitmapForeground = mBitmapBackground
    val bitmapBackground = mBitmapForeground
    if(mask != null && bitmapForeground != null && bitmapBackground != null){
        canvas.save()
        canvas.drawBitmap(bitmapBackground, 0f, 0f, paintBackground)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            makeRadGradP(canvas, bitmapForeground)
        } else {
            canvas.drawBitmap(mask, mPosX, mPosY, paintMask)
            canvas.drawBitmap(bitmapForeground, 0f, 0f, paintForeground)
         }
        canvas.restore()
    }
}

private fun makeRadGradP(canvas: Canvas, bm: Bitmap) {
        val paint = Paint()
        paint.style = Paint.Style.FILL
        val shader = BitmapShader(bm, TileMode.CLAMP, TileMode.CLAMP)
        paint.shader = shader
        val corners = Path()
        corners.addCircle(mPosX + radius, mPosY + radius, radius.toFloat(), Path.Direction.CW)
        canvas.drawPath(corners, paint)

        val gradient = RadialGradient(
                mPosX + radius, mPosY + radius, radius.toFloat(), 0x00000000,
                Color.parseColor("#df000000"), TileMode.CLAMP
        )
        val p = Paint()
        p.isDither = true
        p.shader = gradient
        canvas.drawCircle(mPosX + radius, mPosY + radius, radius.toFloat(), p)
 }


问:
PHP Array Not Working Properly in JS File
I wrote this script in PHP:

```<code>$mainArray = array();
$storageArray = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $array = array($row["TransactionAmount"], $row["AccountBalance"], $row["TransactionDate"]);
    array_push($storageArray, $array);
}
$paginationArray = array();
for ($i = 0; $i < sizeof($storageArray); $i++) {
    if (sizeof($paginationArray) < 15) {
        array_push($paginationArray, $storageArray[$i]);
    } else {
        array_push($mainArray, $paginationArray);
        $paginationArray = array();
    }
}
print_r($mainArray);
</code>```

What happens is that when I try to access elements of the array, instead of doing that it access each character to the array as if it were iterating through a string. If [["Hello"], ["World"]] is the array sent from PHP, when I do data[0] in the JS file it will literally grab the first brace instead of grabbing "Hello". I have no idea why this is because I have never had it happen before. What gives? It isn't a string and I've encoded and decoded the JSON on both ends to see if that solved the properly but get nothing.

答:
PHP print_r outputs a human readable information about a variable. Your output would be a string which would look something like this:

```<code>Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</code>```

To access the data you put in the PHP array in JS, it should be in a format JS can understand - let's say JSON.

So, in place of print_r, you should use

echo json_encode($mainArray);

This will create a json string.

Convert it to JS object by using JSON.parse in your front end.

Body:
I wrote this script in PHP:

$mainArray = array();
$storageArray = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $array = array($row["TransactionAmount"], $row["AccountBalance"], $row["TransactionDate"]);
    array_push($storageArray, $array);
}
$paginationArray = array();
for ($i = 0; $i < sizeof($storageArray); $i++) {
    if (sizeof($paginationArray) < 15) {
        array_push($paginationArray, $storageArray[$i]);
    } else {
        array_push($mainArray, $paginationArray);
        $paginationArray = array();
    }
}
print_r($mainArray);

What happens is that when I try to access elements of the array, instead of doing that it access each character to the array as if it were iterating through a string. If [["Hello"], ["World"]] is the array sent from PHP, when I do data[0] in the JS file it will literally grab the first brace instead of grabbing "Hello". I have no idea why this is because I have never had it happen before. What gives? It isn't a string and I've encoded and decoded the JSON on both ends to see if that solved the properly but get nothing.

Body:
PHP print_r outputs a human readable information about a variable. Your output would be a string which would look something like this:

Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)

To access the data you put in the PHP array in JS, it should be in a format JS can understand - let's say JSON.

So, in place of print_r, you should use

echo json_encode($mainArray);

This will create a json string.

Convert it to JS object by using JSON.parse in your front end.


问:
How to stop the running task that has been created using ShellExecute Command in VBA
How to stop running application that has been executed using ShellExecute command in VB

I have tried with objShell. Quit, objShell. Kill but not satisfied. Error of ActiveX Automation: no such property or method is thrown

```<code>Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute C:\Users\xyz.exe, "", ""
objShell.Kill
</code>```

答:
Your object is only opening the application, but not keeping any control of it.

One way of achieving more control is this:

Sub terminate()

Dim exeID As Double
exeID = Shell("C:\Users\xyz.exe", vbNormalFocus)
Call Shell("TaskKill /F /PID " & exeID, vbHide)

End Sub
```

Body:
How to stop running application that has been executed using ShellExecute command in VB

I have tried with objShell. Quit, objShell. Kill but not satisfied. Error of ActiveX Automation: no such property or method is thrown

Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute C:\Users\xyz.exe, "", ""
objShell.Kill


问:
Iterating over substrings of equal size
I want to convert my String object to Enumerable of its 1-sized substrings (not chars), how can I do this efficiently in Ruby?</p>

OwnerDisplayName: Dmitriy Matveev

ContentLicense: CC BY-SA 2.5

Title: Iterating over substrings of equal size

Body: "xyzzy".split(//) => ["x", "y", "z", "z", "y"]

OwnerDisplayName: womble


问:
I need delete two " " with sed command
I need to delete "" in file

```<code>"CITFFUSKD-E0"
</code>```

I have tried sed 's/\"//.

Result is:

```<code>CITFFUSKD-E0"
</code>```

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

```<code>"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"
</code>```

Result I want it:

```<code>CITFFUSKD
</code>```

答:
You may use

```<code>sed 's/"//g' file | sed 's/[^[:alnum:]].*//' > newfile
</code>```

Or, contract the two sed commands into one sed call as @Wiimm suggests:

```<code>sed 's/"//g;s/[^[:alnum:]].*//' file > newfile
</code>```

If you want to replace inline, see sed edit file in place.

Explanation:

sed 's/"//g' file - removes all " chars from the file

sed 's/[^[:alnum:]].*//' > newfile - also removes all chars from a line starting from the first non-alphanumeric char and saves the result into a newfile.

Title: I need delete two " " with sed command

Body:
I need to delete "" in file

"CITFFUSKD-E0"

I have tried sed 's/\"//.

Result is:

CITFFUSKD-E0"

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"

Result I want it:

CITFFUSKD

Body:
You may use

sed 's/"//g' file | sed 's/[^[:alnum:]].*//' > newfile

Or, contract the two sed commands into one sed call as @Wiimm suggests:

sed 's/"//g;s/[^[:alnum:]].*//' file > newfile

If you want to replace inline, see sed edit file in place.

Explanation:

sed 's/"//g' file - removes all " chars from the file

sed 's/[^[:alnum:]].*//' > newfile - also removes all chars from a line starting from the first non-alphanumeric char and saves the result into a newfile.


问:
Set default home page via <welcome-file> in JSF project
I am unable to set a default page that loads in the browser when I start a Java EE project using Tomcat 8.0 from Eclipse.
I am trying to learn JSF, so I followed this tutorial

Everything works fine, but I can only see the created pages when I right click on the login.xhtml or welcome.xhtml file and choose "Run As/Run on Server".

So far, all the other web applications I have created loaded default page when I started the entire project. The default behavior is to load index.html page (or maybe index.jsp if there is some). So I added index.html and index.xhtml pages into my WEB-INF folder in the project, hoping that at least one of them will be shown. However, nothing happens. The browser always shows just the page on localhost:8080/JSFFaceletsTutorial/ URL, but the page is white clean, not even an error message. I think I have been getting error 404 in the process of solving this issue along the way, however, I am no longer able to reproduce this error and I don't remember what caused it.

I found that it's possible to change the default starting page

However, it doesn't work for me either. Regardless if I edit the web.xml file or not, I am getting the same result.

What is even more puzzling, is that when I tried to change the web browser: "Window/Web Browser/..." it acted for a while differently in the external web browsers than in the internal Eclipse web browser. The internal had always blank page - but the external web browsers once managed to show the index.html page - but it was some outdated version. Despite I made absolutely sure that I edited it, saved the changes, restarted the server... and still, it showed me the outdated version of the page.
And even in this case, it still ignored the changes made in the web.xml file.
But when I am trying it now, it again shows blank white page in all browsers. I am not aware of any change I made except for editing web.xml file...

My guess is that the problem is in the JSF technology I don't fully grasp yet. It's because when I choose to run the login.xhtml and welcome.xhtml pages using right click "Run As/Run on Server", the URL of those pages are on localhost:8080: with path /JSFFaceletsTutorial/faces/login.xhtml and /JSFFaceletsTutorial/faces/welcome.xhtml. That is weird, because I don't have any directory "faces" in my project.
Typing all possible permutations of:

```<code><welcome-file-list>
    <welcome-file>faces/index.html</welcome-file>
    <welcome-file>faces/index.xhtm</welcome-file>
</welcome-file-list>
</code>```

in the web.xml didn't help either. It didn't help when I typed the full address there either.

Here are warnings I am getting in the console (I skipped the INFO log entries):

"Dec 19, 2014 9:39:55 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
  WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:JSFFaceletsTutorial' did not find a matching property.
  ...
  WARNING: JSF1074: Managed bean named 'loginBean' has already been registered.  Replacing existing managed bean class type com.tutorial.LoginBean with com.tutorial.LoginBean.
  Dec 19, 2014 9:39:57 AM org.apache.coyote.AbstractProtocol start"

I am not sure this is helpful though.
I am out of ideas now.

答:
i think this will work</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.xyz.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.xyz.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <welcome-file-list>
    <welcome-file>/main/login.xhtml</welcome-file>
      </welcome-file-list>
<!--         <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.xyz.servlets.login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping> -->

</web-app>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am unable to set a default page that loads in the browser when I start a Java EE project using Tomcat 8.0 from Eclipse.
I am trying to learn JSF, so I followed this tutorial

Everything works fine, but I can only see the created pages when I right click on the login.xhtml or welcome.xhtml file and choose "Run As/Run on Server".

So far, all the other web applications I have created loaded default page when I started the entire project. The default behavior is to load index.html page (or maybe index.jsp if there is some). So I added index.html and index.xhtml pages into my WEB-INF folder in the project, hoping that at least one of them will be shown. However, nothing happens. The browser always shows just the page on localhost:8080/JSFFaceletsTutorial/ URL, but the page is white clean, not even an error message. I think I have been getting error 404 in the process of solving this issue along the way, however, I am no longer able to reproduce this error and I don't remember what caused it.

I found that it's possible to change the default starting page

However, it doesn't work for me either. Regardless if I edit the web.xml file or not, I am getting the same result.

What is even more puzzling, is that when I tried to change the web browser: "Window/Web Browser/..." it acted for a while differently in the external web browsers than in the internal Eclipse web browser. The internal had always blank page - but the external web browsers once managed to show the index.html page - but it was some outdated version. Despite I made absolutely sure that I edited it, saved the changes, restarted the server... and still, it showed me the outdated version of the page.
And even in this case, it still ignored the changes made in the web.xml file.
But when I am trying it now, it again shows blank white page in all browsers. I am not aware of any change I made except for editing web.xml file...

My guess is that the problem is in the JSF technology I don't fully grasp yet. It's because when I choose to run the login.xhtml and welcome.xhtml pages using right click "Run As/Run on Server", the URL of those pages are on localhost:8080: with path /JSFFaceletsTutorial/faces/login.xhtml and /JSFFaceletsTutorial/faces/welcome.xhtml. That is weird, because I don't have any directory "faces" in my project.
Typing all possible permutations of:

<welcome-file-list>
    <welcome-file>faces/index.html</welcome-file>
    <welcome-file>faces/index.xhtm</welcome-file>
</welcome-file-list>

in the web.xml didn't help either. It didn't help when I typed the full address there either.

Here are warnings I am getting in the console (I skipped the INFO log entries):

"Dec 19, 2014 9:39:55 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
  WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:JSFFaceletsTutorial' did not find a matching property.
  ...
  WARNING: JSF1074: Managed bean named 'loginBean' has already been registered.  Replacing existing managed bean class type com.tutorial.LoginBean with com.tutorial.LoginBean.
  Dec 19, 2014 9:39:57 AM org.apache.coyote.AbstractProtocol start"

I am not sure this is helpful though.
I am out of ideas now.

Body:
i think this will work

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.xyz.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.xyz.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <welcome-file-list>
    <welcome-file>/main/login.xhtml</welcome-file>
      </welcome-file-list>
<!--         <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.xyz.servlets.login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping> -->

</web-app>


问:
Tagging s3 objects written with glueContext.write_dynamic_frame
I am using AWS Glue ETL jobs to ingest some datasets using their PySpark API; namely loading a DynamicFrame from S3 objects, doing some transformations and finally writing the results in some S3 location (using glueContext.write_dynamic_frame.from_options) or a catalog (using glueContext.write_dynamic_frame.from_catalog).

To keep things organized, we have policies that prevent object creation in the target locations if they are not tagged properly.

I am wondering if there is a way to tag the s3 objects that are created as part of the write process.

答: It is not possible using Glue APIs. You may have to use S3 Boto library to add tags.</p>


问:
How I can do a reference code in my C# documentation?
I am doing the HTML format documentation for my C# code and I'd like to know if it's possible to do a reference inside my own code.

For example:

```<code>public class Test{
public bool Calculate(int x){ //code }
}

public class Check{
void Checking(int y, int x, int z){
//code
bool aux = Test.Calcultate(x);
//code
}
</code>```

When I'm doing the documentation like this:

```<code> /// <summary>
 ///
 /// </summary>
 /// <param name=""></param>
 /// <returns></returns>
</code>```

How I can do a reference into documentation from the method Checking to the method Calculate? I mean, if I'm watching the documentation of the method Checking, there must be a link to Calculate

答:
You should use the <see> element, for example:

```<code>/// <summary>
/// This uses the <see cref="Test.Calculate"/> method
/// </summary>
/// <param name=""></param>
/// <returns></returns>
void Checking(int y, int x, int z)
{
    //code
    bool aux = Test.Calcultate(x);
    //code
}
</code>```

This will show up in IntelliSense like this:

Body:
I am doing the HTML format documentation for my C# code and I'd like to know if it's possible to do a reference inside my own code.

For example:

public class Test{
public bool Calculate(int x){ //code }
}

public class Check{
void Checking(int y, int x, int z){
//code
bool aux = Test.Calcultate(x);
//code
}

When I'm doing the documentation like this:

 ///
 ///
 ///
 /// <param name=""></param>
 /// <returns></returns>

How I can do a reference into documentation from the method Checking to the method Calculate? I mean, if I'm watching the documentation of the method Checking, there must be a link to Calculate

Body:
You should use the <see> element, for example:

/// <summary>
/// This uses the <see cref="Test.Calculate"/> method
/// </summary>
/// <param name=""></param>
/// <returns></returns>
void Checking(int y, int x, int z)
{
    //code
    bool aux = Test.Calcultate(x);
    //code
}

This will show up in IntelliSense like this:


答:
delete everything behind first word

```<code>sed 's/^"\([[:alpha:]]*\)[^[:alpha:]]*.*/\1/'
</code>```

Match the first ". Then match a sequence of alphabetic characters. Match until you find non-alphabetic character ^[:alpha:]. Then match the rest. Substitute it all for \1 - it is a backreference for the part inside \( ... \), ie. the first word.

I need delete two “ ” with sed command

Remove all possible ":

```<code>sed 's/"//g'
</code>```

Extract the string between ":

```<code>sed 's/"\([^"]*\)"/\1/'
</code>```

Remove everything except alphanumeric characters (numbers + a-z + a-Z, ie. [0-9a-zA-z]):

```<code>sed 's/[^[:alnum:]]//g'
</code>```

Title: I need delete two " " with sed command

Body:
delete everything behind first word

sed 's/^"\([[:alpha:]]*\)[^[:alpha:]]*.*/\1/'

Match the first ". Then match a sequence of alphabetic characters. Match until you find non-alphabetic character ^[:alpha:]. Then match the rest. Substitute it all for \1 - it is a backreference for the part inside \( ... \), ie. the first word.

I need delete two “ ” with sed command

Remove all possible ":

sed 's/"//g'

Extract the string between ":

sed 's/"\([^"]*\)"/\1/'

Remove everything except alphanumeric characters (numbers + a-z + a-Z, ie. [0-9a-zA-z]):

sed 's/[^[:alnum:]]//g'


问:
Extract URL parameter
I am trying to get a URL parameter from the following URL

```<code>http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==
</code>```

The parameter value that I need is the userid but I seem to be getting a null.

Here is my code

```<code>location = window.location;
urlHref = location.href;
urlConvert = new URL(this.urlHref);

if (location.toString().includes('userid')) {
  this.userId = this.urlConvert.searchParams.get("userid");
  console.log(this.userId);
} else {
  this.userId = 'user';
  console.log('gets user not candidate');
}
</code>```

答:
You can use URLSearchParams and its .get function to get the query string value.

const str = 'http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==';
const urlParams = new URLSearchParams(str);
const userId = urlParams.get('userid') || '';

console.log(userId);```

Title: Extract URL parameter

Body:
I am trying to get a URL parameter from the following URL

http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==

The parameter value that I need is the userid but I seem to be getting a null.

Here is my code

location = window.location;
urlHref = location.href;
urlConvert = new URL(this.urlHref);

if (location.toString().includes('userid')) {
  this.userId = this.urlConvert.searchParams.get("userid");
  console.log(this.userId);
} else {
  this.userId = 'user';
  console.log('gets user not candidate');
}


问:
MySQL fetch X columns for each category_id
I don't know if this is possible in mysql via ONE query .

assuming I have a table "products" that has "id","category_id","product_name","price"

Case 1 : I want to fetch 5 products from each category where price is more than 100$

Case 2: I want to fetch

1-"3 products from category 1"

2- "5 products from category 2"

3- "3 products from category 2 where the price is more than 100 and is not fetched in point 2 above"

each case in ONE query , is that possible ?

PS : The table has about 100K rows ...

答:
I think that you could do this using nested select statements.

http://dev.mysql.com/tech-resources/articles/4.1/subqueries.html

Although, I'm not sure how you would utilize them as seperate select statements after you've gotten your query.  I mean, they will all be one record set.


问:
Remove everything from the master branch
I have two branches - develop and master.
I worked constantly on the dev branch and the master is completely unnecessary code, quite different than on dev branch.

how to transfer everything from dev to master in such a way that nothing is left of the old master ?

答:
You could delete master branch if it's not locked
and then checkout the master branch from develop </p>

```<code>git checkout dev
git branch -D master
git checkout -b master
</code>```

Body:
You could delete master branch if it's not locked
and then checkout the master branch from develop

git checkout dev
git branch -D master
git checkout -b master


答:
You can delete the master branch. And then create a new master from dev branch.

Here's how you can achieve this:

```<code>git checkout develop
git branch -D master
git checkout -b master
</code>```

If you want to push your new master branch to remote, then you can use force push option, it will overwrite the old master from the remote.

```<code>git push origin -f master
</code>```

Title: Remove everything from the master branch

Body:
I have two branches - develop and master.
I worked constantly on the dev branch and the master is completely unnecessary code, quite different than on dev branch.

how to transfer everything from dev to master in such a way that nothing is left of the old master ?

Body:
You can delete the master branch. And then create a new master from dev branch.

Here's how you can achieve this:

git checkout develop
git branch -D master
git checkout -b master

If you want to push your new master branch to remote, then you can use force push option, it will overwrite the old master from the remote.

git push origin -f master


问:
1000 questions in android need to create 1000 activities?
I'm doing a app that will ask question to users like:

what is the capital of australia?

Camberra - paris - washington - toquio

and I will have 4 options, so user can select the right one.

When it choose the answer the next question will show.

I'd like to know if I need to create one activity for each of this questions/answers or there is another method? can I have examples?

答:
I would change dynamically the content of the question and answers components.

If you animate the changes in those components it will look really nice and you'll be saving resources that you would waste creating an activity for each question.


问:
apple In-App Purchase server call back JSON does not contain a “latest_receipt_info” key?
before 2019-05-29 the callback json have  “latest_receipt_info” key, but today the callback json does have any receipt info  example:</p>

```<code>    {
  "auto_renew_product_id": "com.xx.xx",
  "notification_type": "DID_CHANGE_RENEWAL_STATUS",
  "environment": "PROD",
  "password": "xxxxx",
  "auto_renew_status_change_date_ms": "1559178490000",
  "auto_renew_status_change_date_pst": "2019-05-29 18:08:10 America/Los_Angeles",
  "auto_renew_status_change_date": "2019-05-30 01:08:10 Etc/GMT",
  "auto_renew_status": "false"
}
</code>```

答: According to the apple documentation "latest_receipt_info" is the JSON representation of the receipt for the most recent renewal. Posted only if renewal is successful. Not posted for notification_type CANCEL. See more details here.</p>

Body:
before 2019-05-29 the callback json have  “latest_receipt_info” key, but today the callback json does have any receipt info  example:

    {
  "auto_renew_product_id": "com.xx.xx",
  "notification_type": "DID_CHANGE_RENEWAL_STATUS",
  "environment": "PROD",
  "password": "xxxxx",
  "auto_renew_status_change_date_ms": "1559178490000",
  "auto_renew_status_change_date_pst": "2019-05-29 18:08:10 America/Los_Angeles",
  "auto_renew_status_change_date": "2019-05-30 01:08:10 Etc/GMT",
  "auto_renew_status": "false"
}


问:
Replace identical placeholders in a string using an array of replacement strings
I have a text:

foo {{bar}} foo {{bar}} foo

I have an array:

```<code>$bar[0] = 'lol';
$bar[1] = 'kek';
</code>```

I want to have this result:

foo lol foo kek foo

I tried this:

```<code>preg_replace("/{{bar}}/usi",$bar,$text);
</code>```

but it doesn't work.

答:
You can get your desired result by iterating through your replacements array, using the limit parameter to preg_replace to prevent it replacing more than 1 value at a time:

```<code>foreach ($bar as $b) {
    $string = preg_replace('/{{bar}}/usi', $b, $string, 1);
}

echo $string;
</code>```

Output:

```<code>foo lol foo kek foo
</code>```

Demo on 3v4l.org

Body:
I have a text:

foo {{bar}} foo {{bar}} foo

I have an array:

$bar[0] = 'lol';
$bar[1] = 'kek';

I want to have this result:

foo lol foo kek foo

I tried this:

preg_replace("/{{bar}}/usi",$bar,$text);

but it doesn't work.

Body:
You can get your desired result by iterating through your replacements array, using the limit parameter to preg_replace to prevent it replacing more than 1 value at a time:

foreach ($bar as $b) {
    $string = preg_replace('/{{bar}}/usi', $b, $string, 1);
}

echo $string;

Output:

foo lol foo kek foo

Demo on 3v4l.org


问:
Android Picasso Recyclerview Image downloading slow
I have endless recyclerview that almost mimics Instagram list/feeds. Where Image is loading into full screen width Imageview. I am using Picasso to load images. Here is my code:

```<code>public class HomeAdapter extends RecyclerView.Adapter {

Context context;

private Contract contract;

List<Feed> feeds;

static final int ITEM_TYPE_HEADER = 0;

static final int ITEM_TYPE_LOAD_MORE = 1;

static final int ITEM_TYPE_DESIGN = 2;

public HomeAdapter(Context context, List<Feed> feeds) {
    this.context = context;
    this.feeds = feeds;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View row;
    if (viewType == ITEM_TYPE_HEADER) {
        row = inflater.inflate(R.layout.list_item_home_header, parent, false);
        return new HeaderHolder(row);
    } else if (viewType == ITEM_TYPE_LOAD_MORE) {
        row = inflater.inflate(R.layout.list_item_load_more, parent, false);
        return new LoadMoreHolder(row);
    } else if (viewType == ITEM_TYPE_DESIGN) {
        row = inflater.inflate(R.layout.list_item_feed_home, parent, false);
        return new DesignItemHolder(row);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    Feed feed = feeds.get(position);
    if (holder instanceof HeaderHolder) {
        HeaderHolder headerHolder = (HeaderHolder) holder;
        Header header = (Header) feed;
        headerHolder.tvTitle.setText(header.getTitle());
        headerHolder.tvDescription.setText(header.getDescription());

    } else if (holder instanceof LoadMoreHolder) {
        LoadMoreHolder loadMoreHolder = (LoadMoreHolder) holder;
        LoadMore loadMore = (LoadMore) feed;
        if(loadMore.getType() == LOAD_MORE_TYPE_PROGRESS) {
            loadMoreHolder.pbLoadMore.setVisibility(View.VISIBLE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.GONE);
        } else {
            loadMoreHolder.pbLoadMore.setVisibility(View.GONE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(loadMore.getTitle())) {
                loadMoreHolder.tvTitle.setText(loadMore.getTitle());
                loadMoreHolder.tvTitle.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvTitle.setVisibility(View.GONE);

            if(StringUtils.isValid(loadMore.getDescription())) {
                loadMoreHolder.tvDescription.setText(loadMore.getDescription());
                loadMoreHolder.tvDescription.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvDescription.setVisibility(View.GONE);
        }

        loadMoreHolder.btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onRetryLoadMoreClick();
            }
        });

    } else if (holder instanceof DesignItemHolder) {
        final DesignItemHolder designItemHolder = (DesignItemHolder) holder;
        final DesignFeed designFeed = (DesignFeed) feed;
        String title = getFeedTitle(designFeed.getDesignCategory().getTitle(), designFeed.getEvent().getTitle());
        designItemHolder.tvCategory.setText(StringUtils.toUpperCaseSentence(designFeed.getDesignCategory().getTitle()));
        designItemHolder.tvDate.setText(DateTimeUtils.formatTime(designFeed.getDate()));
        designItemHolder.tvTitle.setText(StringUtils.toUpperCaseSentence(title));
        designItemHolder.tvBrand.setText(getBrandTitle(designFeed.getBrand().getTitle()));

        if(StringUtils.isValid(designFeed.getShopLink())) {
            designItemHolder.tvShop.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(designFeed.getPrice())) {
                designItemHolder.tvPrice.setVisibility(View.VISIBLE);
                designItemHolder.tvPrice.setText(designFeed.getPrice() + " PKR");
            } else
                designItemHolder.tvPrice.setVisibility(View.GONE);

            designItemHolder.tvShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(contract != null)
                        contract.onOpenShopLink(designFeed.getShopLink());
                }
            });
        }
        else {
            designItemHolder.tvPrice.setVisibility(View.GONE);
            designItemHolder.tvShop.setVisibility(View.GONE);
        }

        showFeedImage(designFeed, designItemHolder.ivThumbnail, designItemHolder.progressBar);

        Picasso.get()
                .load(designFeed.getDesignCategory().getThumbnail())
                .transform(new CircleTransform())
                .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                .into(designItemHolder.ivCategory);

        designItemHolder.ivThumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignFeedClick(designFeed);
            }
        });

        designItemHolder.tvCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.ivCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvBrand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onBrandClick(designFeed.getBrand());
            }
        });

        designItemHolder.ibFavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onFavouriteClick(designFeed);
            }
        });

        designItemHolder.ibShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onShareClick(designFeed);
            }
        });

        designItemHolder.ibDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDownloadClick(designFeed);
            }
        });
    }
}

private void showFeedImage(final DesignFeed designFeed, final ImageView ivThumbnail, final ProgressBar progressBar) {
    Picasso.get()
            .load(designFeed.getThumbnail())
            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(ivThumbnail, new Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(Exception e) {
                    //Try again online if cache failed
                    Picasso.get()
                            .load(designFeed.getThumbnail())
                            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                            .into(ivThumbnail, new Callback() {
                                @Override
                                public void onSuccess() {
                                }

                                @Override
                                public void onError(Exception e) {

                                }
                            });
                }
            });
}

@Override
public int getItemViewType(int position) {
    Feed feed = feeds.get(position);
    if (feed instanceof Header)
        return ITEM_TYPE_HEADER;
    else if (feed instanceof LoadMore)
        return ITEM_TYPE_LOAD_MORE;
    else if (feed instanceof DesignFeed)
        return ITEM_TYPE_DESIGN;
    else
        return super.getItemViewType(position);
}

@Override
public int getItemCount() {
    return feeds.size();
}

public void insertFeedAtStart(Feed feed) {
    feeds.add(0, feed);
    notifyDataSetChanged();
}

public void updateFeeds(ArrayList<Feed> mFeeds) {
    feeds.addAll(mFeeds);
    notifyDataSetChanged();
}

public void addLoadMoreItem(Feed loadMoreFeed) {
    feeds.add(loadMoreFeed);
    notifyItemInserted(getItemCount() - 1);
}

public void removeItem(int index) {
    feeds.remove(index);
    notifyDataSetChanged();
}

private class DesignItemHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvCategory, tvBrand, tvDate, tvPrice, tvShop;
    ImageView ivCategory, ivThumbnail;
    ImageButton ibFavourite, ibShare, ibDownload;
    ProgressBar progressBar;

    DesignItemHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvCategory = itemView.findViewById(R.id.tvCategory);
        tvBrand = itemView.findViewById(R.id.tvBrand);
        tvDate = itemView.findViewById(R.id.tvDate);
        ivCategory = itemView.findViewById(R.id.ivCategory);
        ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
        tvPrice = itemView.findViewById(R.id.tvPrice);
        tvShop = itemView.findViewById(R.id.tvShop);
        ibFavourite = itemView.findViewById(R.id.ibFavourite);
        ibShare = itemView.findViewById(R.id.ibShare);
        ibDownload = itemView.findViewById(R.id.ibDownload);
        progressBar = itemView.findViewById(R.id.progressBar);
    }
}

private class HeaderHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvDescription;
    HeaderHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
    }
}

private class LoadMoreHolder extends RecyclerView.ViewHolder {
    ProgressBar pbLoadMore;
    RelativeLayout rlMessageRetry;
    TextView tvTitle, tvDescription;
    AppCompatButton btnRetry;

    LoadMoreHolder(View itemView) {
        super(itemView);
        pbLoadMore = itemView.findViewById(R.id.pbLoadMore);
        rlMessageRetry = itemView.findViewById(R.id.rlMessageRetry);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
        btnRetry = itemView.findViewById(R.id.btnRetry);
    }
}

public void setContract(Contract contract) {
    this.contract = contract;
}

public interface Contract {

    void onDesignCategoryClick(DesignCategory designCategory);

    void onDesignFeedClick(DesignFeed designCategory);

    void onBrandClick(Brand brand);

    void onRetryLoadMoreClick();

    void onShopClick(String shopLink);

    void onFavouriteClick(DesignFeed designFeed);

    void onShareClick(DesignFeed designFeed);

    void onDownloadClick(DesignFeed designFeed);

    void onOpenShopLink(String shopLink);
}
</code>```

}

Average image size is 80-100 kbs. But image download time is too slow. It almost takes 3-4 seconds to download an image. On the other hand when images are loading from cache it obviously loads an image in no time. I get 15 items from server to load into recyclerview which means 15 images would be downloading in parallel. But still it is quite slow as compared to Instagram or Facebook feeds.

Can anyone guide me about the correct technique to make it as fast as possible, so that when user scrolls down the list images should be already loaded instead him waiting for image to load?

答:
For your case you can your this code flow:

Create a Feeds class (POJO or Model) with Singleton ability with a constructor,

Start filling the Feeds class in Asynchronous Background Task when your app starts to get some extra time,
  Feeds feed_ins = Feeds.getInstance(SomeData)

In the Feeds class get the bitmap from Picasso by calling a defined method from the constructor and save it to a list, List<Bitmap> imageBitmaps = new ArrayList<>()

In the Feeds class create a method that returns the particular bitmap on call with the poitsion, getImageBitmap(int position){ return imageBitmaps.get(position) }

At HomeAdapter get Feeds class instance, Feeds feed_ins = Feeds.getInstance();

Now at the HomeAdapter class use the Feeds class singleton to directly fetch the bitmap,
  ivThumbnail.setImageBitmap(feed_ins.getImageBitmap(int position))

This shall solve you load time problem by the preloading of images.

Body:
I have endless recyclerview that almost mimics Instagram list/feeds. Where Image is loading into full screen width Imageview. I am using Picasso to load images. Here is my code:

public class HomeAdapter extends RecyclerView.Adapter {

Context context;

private Contract contract;

List<Feed> feeds;

static final int ITEM_TYPE_HEADER = 0;

static final int ITEM_TYPE_LOAD_MORE = 1;

static final int ITEM_TYPE_DESIGN = 2;

public HomeAdapter(Context context, List<Feed> feeds) {
    this.context = context;
    this.feeds = feeds;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View row;
    if (viewType == ITEM_TYPE_HEADER) {
        row = inflater.inflate(R.layout.list_item_home_header, parent, false);
        return new HeaderHolder(row);
    } else if (viewType == ITEM_TYPE_LOAD_MORE) {
        row = inflater.inflate(R.layout.list_item_load_more, parent, false);
        return new LoadMoreHolder(row);
    } else if (viewType == ITEM_TYPE_DESIGN) {
        row = inflater.inflate(R.layout.list_item_feed_home, parent, false);
        return new DesignItemHolder(row);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    Feed feed = feeds.get(position);
    if (holder instanceof HeaderHolder) {
        HeaderHolder headerHolder = (HeaderHolder) holder;
        Header header = (Header) feed;
        headerHolder.tvTitle.setText(header.getTitle());
        headerHolder.tvDescription.setText(header.getDescription());

    } else if (holder instanceof LoadMoreHolder) {
        LoadMoreHolder loadMoreHolder = (LoadMoreHolder) holder;
        LoadMore loadMore = (LoadMore) feed;
        if(loadMore.getType() == LOAD_MORE_TYPE_PROGRESS) {
            loadMoreHolder.pbLoadMore.setVisibility(View.VISIBLE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.GONE);
        } else {
            loadMoreHolder.pbLoadMore.setVisibility(View.GONE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(loadMore.getTitle())) {
                loadMoreHolder.tvTitle.setText(loadMore.getTitle());
                loadMoreHolder.tvTitle.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvTitle.setVisibility(View.GONE);

            if(StringUtils.isValid(loadMore.getDescription())) {
                loadMoreHolder.tvDescription.setText(loadMore.getDescription());
                loadMoreHolder.tvDescription.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvDescription.setVisibility(View.GONE);
        }

        loadMoreHolder.btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onRetryLoadMoreClick();
            }
        });

    } else if (holder instanceof DesignItemHolder) {
        final DesignItemHolder designItemHolder = (DesignItemHolder) holder;
        final DesignFeed designFeed = (DesignFeed) feed;
        String title = getFeedTitle(designFeed.getDesignCategory().getTitle(), designFeed.getEvent().getTitle());
        designItemHolder.tvCategory.setText(StringUtils.toUpperCaseSentence(designFeed.getDesignCategory().getTitle()));
        designItemHolder.tvDate.setText(DateTimeUtils.formatTime(designFeed.getDate()));
        designItemHolder.tvTitle.setText(StringUtils.toUpperCaseSentence(title));
        designItemHolder.tvBrand.setText(getBrandTitle(designFeed.getBrand().getTitle()));

        if(StringUtils.isValid(designFeed.getShopLink())) {
            designItemHolder.tvShop.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(designFeed.getPrice())) {
                designItemHolder.tvPrice.setVisibility(View.VISIBLE);
                designItemHolder.tvPrice.setText(designFeed.getPrice() + " PKR");
            } else
                designItemHolder.tvPrice.setVisibility(View.GONE);

            designItemHolder.tvShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(contract != null)
                        contract.onOpenShopLink(designFeed.getShopLink());
                }
            });
        }
        else {
            designItemHolder.tvPrice.setVisibility(View.GONE);
            designItemHolder.tvShop.setVisibility(View.GONE);
        }

        showFeedImage(designFeed, designItemHolder.ivThumbnail, designItemHolder.progressBar);

        Picasso.get()
                .load(designFeed.getDesignCategory().getThumbnail())
                .transform(new CircleTransform())
                .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                .into(designItemHolder.ivCategory);

        designItemHolder.ivThumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignFeedClick(designFeed);
            }
        });

        designItemHolder.tvCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.ivCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvBrand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onBrandClick(designFeed.getBrand());
            }
        });

        designItemHolder.ibFavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onFavouriteClick(designFeed);
            }
        });

        designItemHolder.ibShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onShareClick(designFeed);
            }
        });

        designItemHolder.ibDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDownloadClick(designFeed);
            }
        });
    }
}

private void showFeedImage(final DesignFeed designFeed, final ImageView ivThumbnail, final ProgressBar progressBar) {
    Picasso.get()
            .load(designFeed.getThumbnail())
            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(ivThumbnail, new Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(Exception e) {
                    //Try again online if cache failed
                    Picasso.get()
                            .load(designFeed.getThumbnail())
                            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                            .into(ivThumbnail, new Callback() {
                                @Override
                                public void onSuccess() {
                                }

                                @Override
                                public void onError(Exception e) {

                                }
                            });
                }
            });
}

@Override
public int getItemViewType(int position) {
    Feed feed = feeds.get(position);
    if (feed instanceof Header)
        return ITEM_TYPE_HEADER;
    else if (feed instanceof LoadMore)
        return ITEM_TYPE_LOAD_MORE;
    else if (feed instanceof DesignFeed)
        return ITEM_TYPE_DESIGN;
    else
        return super.getItemViewType(position);
}

@Override
public int getItemCount() {
    return feeds.size();
}

public void insertFeedAtStart(Feed feed) {
    feeds.add(0, feed);
    notifyDataSetChanged();
}

public void updateFeeds(ArrayList<Feed> mFeeds) {
    feeds.addAll(mFeeds);
    notifyDataSetChanged();
}

public void addLoadMoreItem(Feed loadMoreFeed) {
    feeds.add(loadMoreFeed);
    notifyItemInserted(getItemCount() - 1);
}

public void removeItem(int index) {
    feeds.remove(index);
    notifyDataSetChanged();
}

private class DesignItemHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvCategory, tvBrand, tvDate, tvPrice, tvShop;
    ImageView ivCategory, ivThumbnail;
    ImageButton ibFavourite, ibShare, ibDownload;
    ProgressBar progressBar;

    DesignItemHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvCategory = itemView.findViewById(R.id.tvCategory);
        tvBrand = itemView.findViewById(R.id.tvBrand);
        tvDate = itemView.findViewById(R.id.tvDate);
        ivCategory = itemView.findViewById(R.id.ivCategory);
        ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
        tvPrice = itemView.findViewById(R.id.tvPrice);
        tvShop = itemView.findViewById(R.id.tvShop);
        ibFavourite = itemView.findViewById(R.id.ibFavourite);
        ibShare = itemView.findViewById(R.id.ibShare);
        ibDownload = itemView.findViewById(R.id.ibDownload);
        progressBar = itemView.findViewById(R.id.progressBar);
    }
}

private class HeaderHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvDescription;
    HeaderHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
    }
}

private class LoadMoreHolder extends RecyclerView.ViewHolder {
    ProgressBar pbLoadMore;
    RelativeLayout rlMessageRetry;
    TextView tvTitle, tvDescription;
    AppCompatButton btnRetry;

    LoadMoreHolder(View itemView) {
        super(itemView);
        pbLoadMore = itemView.findViewById(R.id.pbLoadMore);
        rlMessageRetry = itemView.findViewById(R.id.rlMessageRetry);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
        btnRetry = itemView.findViewById(R.id.btnRetry);
    }
}

public void setContract(Contract contract) {
    this.contract = contract;
}

public interface Contract {

    void onDesignCategoryClick(DesignCategory designCategory);

    void onDesignFeedClick(DesignFeed designCategory);

    void onBrandClick(Brand brand);

    void onRetryLoadMoreClick();

    void onShopClick(String shopLink);

    void onFavouriteClick(DesignFeed designFeed);

    void onShareClick(DesignFeed designFeed);

    void onDownloadClick(DesignFeed designFeed);

    void onOpenShopLink(String shopLink);
}

}

Average image size is 80-100 kbs. But image download time is too slow. It almost takes 3-4 seconds to download an image. On the other hand when images are loading from cache it obviously loads an image in no time. I get 15 items from server to load into recyclerview which means 15 images would be downloading in parallel. But still it is quite slow as compared to Instagram or Facebook feeds.

Can anyone guide me about the correct technique to make it as fast as possible, so that when user scrolls down the list images should be already loaded instead him waiting for image to load?


答:
Please ensure to wrap the response in ResponseBody like below:

```<code>@GET(your url param)
Call<ResponseBody>getNews();
</code>```

Above Responsebody will return the response and then you can use this ResponseBody to convert it into JSONArray or JSONObject using below Statement

```<code>JSONArray jsonArray=new JSONArray(ResponseBody.body().String())
</code>```

Title: Retrofit and GSON without pojo

Body:
I am using hacker news api in app. I want to make retrofit call using gson factory converter but I am unable to convert response to pojo since it is just list of integers.

Following is api call and response

https://hacker-news.firebaseio.com/v0/topstories.json

[15332819,15335462,15336072,15333899,15335010,15335146,15335216,15334678,15335039,15332171,15334533,15332613,15336632,15334763,15331016,15333082,15332051,15332394,15331604,15332122,15333838,15332187,15334207,15334381,15335717,15330541,15335107,15332770,15332753,15328356,15328247,15336492,15332099,15330564,15328744,15330712,15332138,15333036,15324954,15330757,15328889,15327551,15330864,15334158,15336389,15328516,15330409,15328698,15326480,15334931,15335520,15333085,15332145,15328861,15330556,15334665,15325649,15332306,15335032,15321850,15336063,15325691,15329356,15328850,15335962,15331999,15326098,15325154,15327837,15335448,15325767,15314006,15318440,15329550,15331089,15329374,15330830,15332929,15325226,15331750,15328165,15326335,15333198,15325820,15316175,15315129,15331393,15328948,15327502,15328680,15326652,15306398,15302730,15309393,15324818,15318530,15324596,15331731,15309989,15321070,15317075,15325659,15323707,15335129,15330835,15324883,15302484,15302707,15330966,15320936,15315813,15332031,15332370,15318904,15304242,15326984,15298833,15327455,15324011,15324542,15313257,15318233,15326845,15294171,15302841,15330977,15325480,15308771,15334514,15326648,15312755,15329699,15321555,15302500,15324547,15304482,15311773,15310465,15326553,15297912,15326276,15324656,15323842,15300069,15326158,15332620,15314486,15305892,15310664,15310291,15317275,15333631,15303254,15335753,15306365,15303833,15302662,15312966,15318741,15299849,15321002,15312103,15324530,15330981,15326045,15324917,15308824,15317471,15329527,15321015,15324386,15311280,15321772,15320778,15310849,15323267,15325456,15301766,15320489,15321031,15325545,15310680,15332367,15317639,15314262,15316726,15314510,15312303,15315028,15302887,15322805,15319616,15305774,15318958,15307205,15326577,15315863,15325735,15297861,15318390,15323042,15320623,15330052,15326106,15314877,15297915,15294742,15325829,15322887,15300052,15322627,15301982,15324195,15305991,15307358,15326535,15320922,15328992,15304139,15310154,15314629,15330970,15307563,15312118,15316627,15307152,15314663,15314964,15301151,15316762,15322415,15300241,15330355,15319340,15304951,15313330,15315844,15304269,15299900,15324237,15308577,15320952,15314492,15300407,15311274,15314659,15307870,15309190,15299359,15294131,15320342,15329781,15322447,15309929,15317515,15301131,15317735,15309290,15314020,15314503,15321807,15314058,15324325,15325188,15312288,15299165,15309403,15305581,15314276,15321588,15305258,15307097,15319237,15302186,15327658,15306523,15302718,15302701,15317788,15309249,15297371,15324414,15306223,15316719,15309683,15326666,15326089,15312132,15306976,15316348,15311742,15325030,15319103,15327571,15304863,15297708,15308667,15303894,15320426,15320676,15308680,15312046,15322156,15308022,15323136,15302035,15311952,15302636,15296170,15323754,15301638,15301785,15328618,15299822,15296438,15328266,15326165,15317902,15299023,15328481,15325457,15302432,15302592,15313787,15313307,15316994,15326297,15301981,15324838,15298050,15321750,15320682,15295146,15294722,15319061,15311955,15302495,15303947,15297827,15315213,15309072,15306920,15306278,15320799,15302317,15325546,15317835,15299754,15327183,15301848,15330037,15308858,15299116,15303555,15306187,15298570,15305476,15321366,15321323,15297448,15325264,15316148,15294483,15326021,15302749,15321069,15327575,15319476,15327225,15299138,15298300,15306612,15327253,15319758,15315008,15302750,15310829,15321162,15295561,15318821,15314229,15306193,15320616,15304210,15332726,15301365,15309228,15324169,15318644,15305042,15311711,15307009,15304935,15298146,15311954,15326684,15297164,15323962,15303210,15301014,15295585,15299887,15307267,15307001,15293573,15297387,15314426,15304867,15293855,15307099,15293596,15310588,15307180,15303079,15324055,15314077,15318880,15306846,15306593,15317078,15326176,15296245,15295992,15297545,15320880,15309332,15295813,15317987,15314741,15325563,15313733,15306990,15317376,15308043,15326456,15306295,15294929,15293902,15298337,15295228,15311889,15300357,15293605,15314046,15300142,15305035,15297770,15293741,15299442,15302464,15314615,15302251,15309767,15302857,15298862,15295834,15301591,15314781,15301351,15304550,15311658,15307987,15304485,15332474,15307383,15320350,15299205,15307054,15323574,15332566,15305762,15319775,15306074,15319474,15297748,15304907,15305220,15317438,15320809,15303835,15307014,15317109,15320767,15305674,15300269,15316517,15328743,15312652,15300688,15298881,15318128,15313280,15321945,15313153,15306169,15316935,15318889,15304986,15307778,15330453]

Body:
Please ensure to wrap the response in ResponseBody like below:

@GET(your url param)
Call<ResponseBody>getNews();

Above Responsebody will return the response and then you can use this ResponseBody to convert it into JSONArray or JSONObject using below Statement

JSONArray jsonArray=new JSONArray(ResponseBody.body().String())


问:
Function doesn't update the variable
My function is update the ArrayList, but doesn't update the boolean, it's very weird!

I just not understand, or them both updates, or them both not.

```<code>private ArrayList<String> arrayList = new ArrayList<>();
private boolean isEmpty = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList, isEmpty);
    Log.d("status", arrayList.size() + " " + isEmpty);

}

private void addNames(ArrayList<String> names, boolean empty) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
    empty = false;
}
</code>```

How can i update the isEmpty variable?
(this.isEmpty = false; is not good for me, i need another way)

答:
You don't need to any isEmpty field, you can check on the fly by calling arrayList.isEmpty().

```<code>private List<String> arrayList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList);
    Log.d("status", arrayList.size() + " " + arrayList.isEmpty());

}

private void addNames(List<String> names) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
}
</code>```

Look here for further information

Title: Function doesn't update the variable

Body:
My function is update the ArrayList, but doesn't update the boolean, it's very weird!

I just not understand, or them both updates, or them both not.

private ArrayList<String> arrayList = new ArrayList<>();
private boolean isEmpty = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList, isEmpty);
    Log.d("status", arrayList.size() + " " + isEmpty);

}

private void addNames(ArrayList<String> names, boolean empty) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
    empty = false;
}

How can i update the isEmpty variable?
(this.isEmpty = false; is not good for me, i need another way)

Body:
You don't need to any isEmpty field, you can check on the fly by calling arrayList.isEmpty().

private List<String> arrayList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList);
    Log.d("status", arrayList.size() + " " + arrayList.isEmpty());

}

private void addNames(List<String> names) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
}

Look here for further information


问:
pimp up a plain jar to be a maven jar with internal pom.xml for Artifactory
I need to use a xyz.jar wich was generated with ant. Hence, the transitive dependencies are missing. So I had the idea, to modify the xyz.jar to add the internal META-INF/maven/groupId/artifactId/pom.xml and pom.properties files.

When I deployed it to Artifactory, it ignored them and generated it's own pom.xml without dependencies.

What has one to do, Artifactory deploys the pom.xml lying about in the same folder as the xyz.jar file?

Lost way too much time on this allready...

答:
Chances are that Artifactory skips the deployment of the internal POM because it cannot read the POM's physical size from the archive (done for historical reasons); You can verify this by looking at the log for a warning message along the lines of:

"Found pom.xml file with size -1 inside the zip. Ignoring"

If you've already gone to the lengths of creating a customized POM file, you can paste it's contents in the POM content editor of the artifact deployer or deploy it independently; though the first option will give you the benefit of auto detecting the deployment coordinates for the JAR file.


问:
How to add file in Solr?
I use Apache Solr so that I can work with files, I can add regular text fields via Spring, but I don’t know how to add TXT / pdf

```<code>@SolrDocument(solrCoreName = "accounting")
public class Accounting {
@Id
@Field
private String id;
@Field
private File txtFile;
@Field
private String docType;
@Field
private String docTitle;

public Accounting() {
}

public Accounting(String id, String docType, String docTitle) {
    this.id = id;
    this.docTitle = docTitle;
    this.docType = docType;
}
</code>```

here is the problem with the txtFile field

```<code>   <field name="docTitle" type="strings"/>
  <field name="docType" type="strings"/>
</code>```

These fields that I manually added to schema.xml, I can not figure out how to add a field here that will be responsible for the file, for example, I will add here a txt file, how to do it? Thank you very much. And do I correctly declare the field  private File txtFile; in the entity for the file?

答:
Solr will not store the actual file anywhere. Depending on your config it can store the binary content though. Using the extract request handler Apache Solr which relies on Apache Tika to extract the content from the document.

You can try something like below code. The current code is not using anything from the springboot. Here the content is read from the pdf document and then the data is indexed into solr along with id and filename. I have used the tika apis to extract the content of the pdf.

```<code>public static void main(final String[] args) throws IOException, TikaException, SAXException {

        String urlString = "http://localhost:8983/solr/TestCore1";
        SolrClient solr = new HttpSolrClient.Builder(urlString).build();

        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        File file = new File("C://Users//abhijitb//Desktop//TestDocument.pdf");
        FileInputStream inputstream = new FileInputStream(file);
        ParseContext pcontext = new ParseContext();

        // parsing the document using PDF parser
        PDFParser pdfparser = new PDFParser();
        pdfparser.parse(inputstream, handler, metadata, pcontext);

        // getting the content of the document
        //System.out.println("Contents of the PDF :" + handler.toString());

        try {
            String fileName = file.getName();
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", "123456");
            document.addField("title", fileName);
            document.addField("text", handler.toString());
            solr.add(document);
            solr.commit();
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Once you index the data, it can be verified on the solr admin page by querying for it.
Please find the image for your reference.

Title: How to add file in Solr?

Body:
I use Apache Solr so that I can work with files, I can add regular text fields via Spring, but I don’t know how to add TXT / pdf

@SolrDocument(solrCoreName = "accounting")
public class Accounting {
@Id
@Field
private String id;
@Field
private File txtFile;
@Field
private String docType;
@Field
private String docTitle;

public Accounting() {
}

public Accounting(String id, String docType, String docTitle) {
    this.id = id;
    this.docTitle = docTitle;
    this.docType = docType;
}

here is the problem with the txtFile field

   <field name="docTitle" type="strings"/>
  <field name="docType" type="strings"/>

These fields that I manually added to schema.xml, I can not figure out how to add a field here that will be responsible for the file, for example, I will add here a txt file, how to do it? Thank you very much. And do I correctly declare the field  private File txtFile; in the entity for the file?

Body:
Solr will not store the actual file anywhere. Depending on your config it can store the binary content though. Using the extract request handler Apache Solr which relies on Apache Tika to extract the content from the document.

You can try something like below code. The current code is not using anything from the springboot. Here the content is read from the pdf document and then the data is indexed into solr along with id and filename. I have used the tika apis to extract the content of the pdf.

public static void main(final String[] args) throws IOException, TikaException, SAXException {

        String urlString = "http://localhost:8983/solr/TestCore1";
        SolrClient solr = new HttpSolrClient.Builder(urlString).build();

        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        File file = new File("C://Users//abhijitb//Desktop//TestDocument.pdf");
        FileInputStream inputstream = new FileInputStream(file);
        ParseContext pcontext = new ParseContext();

        // parsing the document using PDF parser
        PDFParser pdfparser = new PDFParser();
        pdfparser.parse(inputstream, handler, metadata, pcontext);

        // getting the content of the document
        //System.out.println("Contents of the PDF :" + handler.toString());

        try {
            String fileName = file.getName();
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", "123456");
            document.addField("title", fileName);
            document.addField("text", handler.toString());
            solr.add(document);
            solr.commit();
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
    }

Once you index the data, it can be verified on the solr admin page by querying for it.
Please find the image for your reference.


问:
How to get the xPath of an element
I'm trying to get the value of the data-content_published_date attribute which is published date of an article with xPath but for some reason I cant!

Here is how I tried:

```<code>//div[@id='page-segment-values']/@data-content_published_date
</code>```

And here is the div tag:

```<code><div id="page-segment-values" class="">
  <div class="keyvals" data-content_author_name="Eli Meixler" data-content_cms_id="5461956" data-content_headline="British Academic" data-content_modified_date="" data-content_published_date="2018-11-22T08:15:43.000Z" data-content_shown_on_platform="own" data-content_type="article" data-path="/5461956/british-academic-sentenced-spying-united-arab-emirates/" data-referrer="" data-search="" data-content_is_post="post" data-title="A British Academic Has Been Sentenced to Life in Prison on Espionage Charges in the United Arab Emirates" data-affiliate_link_count="0" data-content_cms_category="World" data-content_cms_tags="onetime|overnight|United Arab Emirates" data-content_cms_terms="World,onetime,overnight,United Arab Emirates" data-time_inc_brand="time.com" data-time_inc_application="front end" data-content_syndicated="false" data-content_syndicated_brand="" data-content_syndicated_url="" data-content_nlp_sentiment_label="negative" data-content_nlp_sentiment_score="-0.2" data-content_nlp_sentiment_magnitude="5.9" data-content_nlp_entities="Matthew Hedges" data-content_nlp_payload="{"entities":[{"type":"PERSON","text":"Matthew Hedges","relevance":0.57477295,"disambiguation":{}},{"type":"WORK_OF_ART","text":"British Academic Sentenced to Life on Spying Charges","relevance":0.02937225,"disambiguation":{}},{"type":"LOCATION","text":"British","relevance":0.029201617,"disambiguation":{"mid":"\/m\/07ssc","wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Kingdom"}},{"type":"PERSON","text":"academic","relevance":0.020707963,"disambiguation":{}},{"type":"OTHER","text":"life","relevance":0.018888554,"disambiguation":{}},{"type":"OTHER","text":"spying charges","relevance":0.013851213,"disambiguation":{}},{"type":"LOCATION","text":"prison","relevance":0.0133453375,"disambiguation":{}},{"type":"LOCATION","text":"United Arab Emirates","relevance":0.011457251,"disambiguation":{"wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Arab_Emirates","mid":"\/m\/0j1z8"}},{"type":"OTHER","text":"threats","relevance":0.009783207,"disambiguation":{}},{"type":"EVENT","text":"blowback","relevance":0.009783207,"disambiguation":{}}],"categories":[{"label":"\/Law & Government\/Public Safety\/Crime & Justice","score":0.64}],"docSentiment":{"magnitude":5.9,"score":-0.2,"label":"negative"},"language":"en"}" data-content_nlp_categories="/Law & Government/Public Safety/Crime & Justice"></div>
</div>
</code>```

Anyone has any idea why can't I access the value of it? And how to get it?

答:
You've missed nested div element, thus you're trying to get value of data-content_published_date of outer div.

Correct XPath query should be

```<code>//div[@id='page-segment-values']/div/@data-content_published_date
</code>```

Or even more precisely

```<code>//div[@id='page-segment-values']/div[@class='keyvals']/@data-content_published_date
</code>```

Title: How to get the xPath of an element

Body:
I'm trying to get the value of the data-content_published_date attribute which is published date of an article with xPath but for some reason I cant!

Here is how I tried:

//div[@id='page-segment-values']/@data-content_published_date

And here is the div tag:

  <div class="keyvals" data-content_author_name="Eli Meixler" data-content_cms_id="5461956" data-content_headline="British Academic" data-content_modified_date="" data-content_published_date="2018-11-22T08:15:43.000Z" data-content_shown_on_platform="own" data-content_type="article" data-path="/5461956/british-academic-sentenced-spying-united-arab-emirates/" data-referrer="" data-search="" data-content_is_post="post" data-title="A British Academic Has Been Sentenced to Life in Prison on Espionage Charges in the United Arab Emirates" data-affiliate_link_count="0" data-content_cms_category="World" data-content_cms_tags="onetime|overnight|United Arab Emirates" data-content_cms_terms="World,onetime,overnight,United Arab Emirates" data-time_inc_brand="time.com" data-time_inc_application="front end" data-content_syndicated="false" data-content_syndicated_brand="" data-content_syndicated_url="" data-content_nlp_sentiment_label="negative" data-content_nlp_sentiment_score="-0.2" data-content_nlp_sentiment_magnitude="5.9" data-content_nlp_entities="Matthew Hedges" data-content_nlp_payload="{"entities":[{"type":"PERSON","text":"Matthew Hedges","relevance":0.57477295,"disambiguation":{}},{"type":"WORK_OF_ART","text":"British Academic Sentenced to Life on Spying Charges","relevance":0.02937225,"disambiguation":{}},{"type":"LOCATION","text":"British","relevance":0.029201617,"disambiguation":{"mid":"\/m\/07ssc","wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Kingdom"}},{"type":"PERSON","text":"academic","relevance":0.020707963,"disambiguation":{}},{"type":"OTHER","text":"life","relevance":0.018888554,"disambiguation":{}},{"type":"OTHER","text":"spying charges","relevance":0.013851213,"disambiguation":{}},{"type":"LOCATION","text":"prison","relevance":0.0133453375,"disambiguation":{}},{"type":"LOCATION","text":"United Arab Emirates","relevance":0.011457251,"disambiguation":{"wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Arab_Emirates","mid":"\/m\/0j1z8"}},{"type":"OTHER","text":"threats","relevance":0.009783207,"disambiguation":{}},{"type":"EVENT","text":"blowback","relevance":0.009783207,"disambiguation":{}}],"categories":[{"label":"\/Law & Government\/Public Safety\/Crime & Justice","score":0.64}],"docSentiment":{"magnitude":5.9,"score":-0.2,"label":"negative"},"language":"en"}" data-content_nlp_categories="/Law & Government/Public Safety/Crime & Justice">

Anyone has any idea why can't I access the value of it? And how to get it?

Body:
You've missed nested div element, thus you're trying to get value of data-content_published_date of outer div.

Correct XPath query should be

//div[@id='page-segment-values']/div/@data-content_published_date

Or even more precisely

//div[@id='page-segment-values']/div[@class='keyvals']/@data-content_published_date


问:
How do I get elements from an array without repetition?
How do I get 5 elements from an array without repetition?

I'm trying to create an online version of story dice using Tumult Hype. All that I need to do is choose 5 image names from an array without repetition. But I just can't get it to work.

I've tried borrowing code from other stackoverflow answers and I can't get them working.

The code below is currently working but gives me repeats. How do I tinker with it to eliminate the repeats?

(You can see it in action here: https://davebirss.com/storydice/)

I know that it's probably verbose and inelegant. I only speak pidgin javascript, I'm afraid. And what I'm trying to do is currently beyond my ability.

Thank you so much in advance for your help.

```<code>var diceRoll = ['${resourcesFolderName}/story_dice1.png',
        '${resourcesFolderName}/story_dice2.png',
        '${resourcesFolderName}/story_dice3.png',
        ...,
        '${resourcesFolderName}/story_dice51.png']

function choose(n, arr) {
    while (arr.length > n) {
        var del = Math.floor(Math.random() * arr.length);
        arr = arr.filter(function(item, i) {
            return i !== del;
        });
    }
    return arr;}

var result1 = [choose(1, diceRoll)];
var result2 = [choose(1, diceRoll)];
var result3 = [choose(1, diceRoll)];
var result4 = [choose(1, diceRoll)];
var result5 = [choose(1, diceRoll)];

hypeDocument.getElementById("dice1").innerHTML = "<img src='"+result1+" 'height='125' width='125'>";
hypeDocument.getElementById("dice2").innerHTML = "<img src='"+result2+" 'height='125' width='125'>";
hypeDocument.getElementById("dice3").innerHTML = "<img src='"+result3+" 'height='125' width='125'>";
hypeDocument.getElementById("dice4").innerHTML = "<img src='"+result4+" 'height='125' width='125'>";
hypeDocument.getElementById("dice5").innerHTML = "<img src='"+result5+" 'height='125' width='125'>";
</code>```

Update

Thank you all for your help. I'm sure all the answers were great but the snippet from U25lYWt5IEJhc3RhcmQg is the code that I managed to successfully incorporate. For the record, this is how I did it:

```<code>const rollTheDice = (arr, n) => {
  const randomN = [];
  while(randomN.length < n){
    const randomIndex = Math.floor(Math.random()*arr.length);
    randomN.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }
  return randomN;}

var result1 = (rollTheDice(images,1));
var result2 = (rollTheDice(images,1));
var result3 = (rollTheDice(images,1));
var result4 = (rollTheDice(images,1));
var result5 = (rollTheDice(images,1));
</code>```

I've been repeatedly reloading the page and haven't seen any repeats yet. Perfect!

答:
I guess, the trickiest part here is not to waste the performance, limiting possible options to those, not previously chosen:

const images = ['a','b','c','d','e','f'];

const rollTheDice = (arr, n) => {
  const randomN = [];
  while(randomN.length < n){
    const randomIndex = Math.floor(Math.random()*arr.length);
    randomN.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }
  return randomN;
}

console.log(rollTheDice(images, 5));```

Body:
How do I get 5 elements from an array without repetition?

I'm trying to create an online version of story dice using Tumult Hype. All that I need to do is choose 5 image names from an array without repetition. But I just can't get it to work.

I've tried borrowing code from other stackoverflow answers and I can't get them working.

The code below is currently working but gives me repeats. How do I tinker with it to eliminate the repeats?

(You can see it in action here: https://davebirss.com/storydice/)

I know that it's probably verbose and inelegant. I only speak pidgin javascript, I'm afraid. And what I'm trying to do is currently beyond my ability.

Thank you so much in advance for your help.

var diceRoll = ['${resourcesFolderName}/story_dice1.png',
        '${resourcesFolderName}/story_dice2.png',
        '${resourcesFolderName}/story_dice3.png',
        ...,
        '${resourcesFolderName}/story_dice51.png']

function choose(n, arr) {
    while (arr.length > n) {
        var del = Math.floor(Math.random() * arr.length);
        arr = arr.filter(function(item, i) {
            return i !== del;
        });
    }
    return arr;}

var result1 = [choose(1, diceRoll)];
var result2 = [choose(1, diceRoll)];
var result3 = [choose(1, diceRoll)];
var result4 = [choose(1, diceRoll)];
var result5 = [choose(1, diceRoll)];

hypeDocument.getElementById("dice1").innerHTML = "";
hypeDocument.getElementById("dice2").innerHTML = "";
hypeDocument.getElementById("dice3").innerHTML = "";
hypeDocument.getElementById("dice4").innerHTML = "";
hypeDocument.getElementById("dice5").innerHTML = "";

Update

Thank you all for your help. I'm sure all the answers were great but the snippet from U25lYWt5IEJhc3RhcmQg is the code that I managed to successfully incorporate. For the record, this is how I did it:

const rollTheDice = (arr, n) => {
  const randomN = [];
  while(randomN.length < n){
    const randomIndex = Math.floor(Math.random()*arr.length);
    randomN.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }
  return randomN;}

var result1 = (rollTheDice(images,1));
var result2 = (rollTheDice(images,1));
var result3 = (rollTheDice(images,1));
var result4 = (rollTheDice(images,1));
var result5 = (rollTheDice(images,1));

I've been repeatedly reloading the page and haven't seen any repeats yet. Perfect!


问:
How can I swap the axes on an eCharts bar chart with javascript
I have created an eCharts barchart and I just want to swap the x and y axes

I have tried just swapping the data objects for the axes but that doesn't work and googling hasn't turned up much at all.

This is the initialisation script for the bar chart

```<code>var chart = echarts.init(document.getElementById('chart'));
var option = {
    yAxis: {
        name: '',
        data: ''
    },

    xAxis: {
        name: '',
        data: ["CARH"  , "CDFR"  , "HGA"  , "O2RG"  , "SHLA"  , "SHWS"]
    },

    series: {
        name: '',
        type: 'bar',
        data: [100.29, 101.05, 100.78, 96.3, 101.8, 99.9]
    }
};
chart.setOption(option);
</code>```

Body:
I have created an eCharts barchart and I just want to swap the x and y axes

I have tried just swapping the data objects for the axes but that doesn't work and googling hasn't turned up much at all.

This is the initialisation script for the bar chart

var chart = echarts.init(document.getElementById('chart'));
var option = {
    yAxis: {
        name: '',
        data: ''
    },

    xAxis: {
        name: '',
        data: ["CARH"  , "CDFR"  , "HGA"  , "O2RG"  , "SHLA"  , "SHWS"]
    },

    series: {
        name: '',
        type: 'bar',
        data: [100.29, 101.05, 100.78, 96.3, 101.8, 99.9]
    }
};
chart.setOption(option);

Body:
Try this:

var option = {
yAxis: [{
    name: '',
    data: ["CARH"  , "CDFR"  , "HGA"  , "O2RG"  , "SHLA"  , "SHWS"]
}],

xAxis: [{
    name: '',
    data: ['100.29', '101.05', '100.78', '96.3', '101.8', '50']
    }],

series: [{
    name: '',
    type: 'bar',
    data: [1  , 2  , 3  , 4 , 5  , 6]
}]

};