问:
error: option -Xbootclasspath/p: not allowed with target 12 (Netbeans 11.0)
I am upgrading my IDE to newest versions of netbeans (11.0) and jdk (12.0). When i make a simple basic Web Application With Ant Project, i can't compile it because the output shows following error message:

error: option -Xbootclasspath/p: not allowed with target 12
BUILD FAILED (total time: 1 second)

Obviously Ant script uses this option and jdk 12 does not allow it? But how to fix this??

EDIT: this is the section (build-impl.xml) where the option -Xbootclasspath is used. This is a netbeans generated script. If i remove the option completely, compilation succeeds and application seems to work

```<code><target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-init-macrodef-property" name="-do-init">
    <condition property="have.tests">
        <or>
            <available file="${test.src.dir}"/>
        </or>
    </condition>
    <condition property="have.sources">
        <or>
            <available file="${src.dir}"/>
        </or>
    </condition>
    <condition property="netbeans.home+have.tests">
        <and>
            <isset property="netbeans.home"/>
            <isset property="have.tests"/>
        </and>
    </condition>
    <condition property="no.javadoc.preview">
        <isfalse value="${javadoc.preview}"/>
    </condition>
    <property name="javac.compilerargs" value=""/>
    <condition property="no.deps">
        <and>
            <istrue value="${no.dependencies}"/>
        </and>
    </condition>
    <condition property="no.dist.ear.dir">
        <not>
            <isset property="dist.ear.dir"/>
        </not>
    </condition>
    <property name="build.web.excludes" value="${build.classes.excludes}"/>
    <condition property="do.compile.jsps">
        <istrue value="${compile.jsps}"/>
    </condition>
    <condition property="do.debug.server">
        <or>
            <not>
                <isset property="debug.server"/>
            </not>
            <istrue value="${debug.server}"/>
            <and>
                <not>
                    <istrue value="${debug.server}"/>
                </not>
                <not>
                    <istrue value="${debug.client}"/>
                </not>
            </and>
        </or>
    </condition>
    <condition property="do.debug.client">
        <istrue value="${debug.client}"/>
    </condition>
    <condition property="do.display.browser">
        <istrue value="${display.browser}"/>
    </condition>
    <condition property="do.display.browser.debug.old">
        <and>
            <isset property="do.display.browser"/>
            <not>
                <isset property="do.debug.client"/>
            </not>
            <not>
                <isset property="browser.context"/>
            </not>
        </and>
    </condition>
    <condition property="do.display.browser.debug">
        <and>
            <isset property="do.display.browser"/>
            <not>
                <isset property="do.debug.client"/>
            </not>
            <isset property="browser.context"/>
        </and>
    </condition>
    <available file="${conf.dir}/MANIFEST.MF" property="has.custom.manifest"/>
    <available file="${persistence.xml.dir}/persistence.xml" property="has.persistence.xml"/>
    <condition property="do.war.package.with.custom.manifest">
        <isset property="has.custom.manifest"/>
    </condition>
    <condition property="do.war.package.without.custom.manifest">
        <not>
            <isset property="has.custom.manifest"/>
        </not>
    </condition>
    <condition property="do.tmp.war.package.with.custom.manifest">
        <and>
            <isset property="has.custom.manifest"/>
            <or>
                <isfalse value="${directory.deployment.supported}"/>
                <isset property="dist.ear.dir"/>
            </or>
        </and>
    </condition>
    <condition property="do.tmp.war.package.without.custom.manifest">
        <and>
            <not>
                <isset property="has.custom.manifest"/>
            </not>
            <or>
                <isfalse value="${directory.deployment.supported}"/>
                <isset property="dist.ear.dir"/>
            </or>
        </and>
    </condition>
    <condition property="do.tmp.war.package">
        <or>
            <isfalse value="${directory.deployment.supported}"/>
            <isset property="dist.ear.dir"/>
        </or>
    </condition>
    <property name="build.meta.inf.dir" value="${build.web.dir}/META-INF"/>
    <condition else="" property="application.args.param" value="${application.args}">
        <and>
            <isset property="application.args"/>
            <not>
                <equals arg1="${application.args}" arg2="" trim="true"/>
            </not>
        </and>
    </condition>
    <property name="source.encoding" value="${file.encoding}"/>
    <condition property="javadoc.encoding.used" value="${javadoc.encoding}">
        <and>
            <isset property="javadoc.encoding"/>
            <not>
                <equals arg1="${javadoc.encoding}" arg2=""/>
            </not>
        </and>
    </condition>
    <property name="javadoc.encoding.used" value="${source.encoding}"/>
    <property name="includes" value="**"/>
    <property name="excludes" value=""/>
    <property name="runmain.jvmargs" value=""/>
    <path id="endorsed.classpath.path" path="${endorsed.classpath}"/>
    <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'">
        <and>
            <isset property="endorsed.classpath"/>
            <length length="0" string="${endorsed.classpath}" when="greater"/>
        </and>
    </condition>
    <condition else="false" property="jdkBug6558476">
        <and>
            <matches pattern="1\.[56]" string="${java.specification.version}"/>
            <not>
                <os family="unix"/>
            </not>
        </and>
    </condition>
    <property name="javac.fork" value="${jdkBug6558476}"/>
    <condition property="junit.available">
        <or>
            <available classname="org.junit.Test" classpath="${run.test.classpath}"/>
            <available classname="junit.framework.Test" classpath="${run.test.classpath}"/>
        </or>
    </condition>
    <condition property="testng.available">
        <available classname="org.testng.annotations.Test" classpath="${run.test.classpath}"/>
    </condition>
    <condition property="junit+testng.available">
        <and>
            <istrue value="${junit.available}"/>
            <istrue value="${testng.available}"/>
        </and>
    </condition>
    <condition else="testng" property="testng.mode" value="mixed">
        <istrue value="${junit+testng.available}"/>
    </condition>
    <condition else="" property="testng.debug.mode" value="-mixed">
        <istrue value="${junit+testng.available}"/>
    </condition>
</target>
</code>```

答: I just noticed that netbeans 11 recommends using JDK 8 with it instead of newer versions. So i'm going back to JDK 8.. ("problem" solved).</p>

Body:
I am upgrading my IDE to newest versions of netbeans (11.0) and jdk (12.0). When i make a simple basic Web Application With Ant Project, i can't compile it because the output shows following error message:

error: option -Xbootclasspath/p: not allowed with target 12
BUILD FAILED (total time: 1 second)

Obviously Ant script uses this option and jdk 12 does not allow it? But how to fix this??

EDIT: this is the section (build-impl.xml) where the option -Xbootclasspath is used. This is a netbeans generated script. If i remove the option completely, compilation succeeds and application seems to work

<target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-init-macrodef-property" name="-do-init">
    <condition property="have.tests">
        <or>
            <available file="${test.src.dir}"/>
        </or>
    </condition>
    <condition property="have.sources">
        <or>
            <available file="${src.dir}"/>
        </or>
    </condition>
    <condition property="netbeans.home+have.tests">
        <and>
            <isset property="netbeans.home"/>
            <isset property="have.tests"/>
        </and>
    </condition>
    <condition property="no.javadoc.preview">
        <isfalse value="${javadoc.preview}"/>
    </condition>
    <property name="javac.compilerargs" value=""/>
    <condition property="no.deps">
        <and>
            <istrue value="${no.dependencies}"/>
        </and>
    </condition>
    <condition property="no.dist.ear.dir">
        <not>
            <isset property="dist.ear.dir"/>
        </not>
    </condition>
    <property name="build.web.excludes" value="${build.classes.excludes}"/>
    <condition property="do.compile.jsps">
        <istrue value="${compile.jsps}"/>
    </condition>
    <condition property="do.debug.server">
        <or>
            <not>
                <isset property="debug.server"/>
            </not>
            <istrue value="${debug.server}"/>
            <and>
                <not>
                    <istrue value="${debug.server}"/>
                </not>
                <not>
                    <istrue value="${debug.client}"/>
                </not>
            </and>
        </or>
    </condition>
    <condition property="do.debug.client">
        <istrue value="${debug.client}"/>
    </condition>
    <condition property="do.display.browser">
        <istrue value="${display.browser}"/>
    </condition>
    <condition property="do.display.browser.debug.old">
        <and>
            <isset property="do.display.browser"/>
            <not>
                <isset property="do.debug.client"/>
            </not>
            <not>
                <isset property="browser.context"/>
            </not>
        </and>
    </condition>
    <condition property="do.display.browser.debug">
        <and>
            <isset property="do.display.browser"/>
            <not>
                <isset property="do.debug.client"/>
            </not>
            <isset property="browser.context"/>
        </and>
    </condition>
    <available file="${conf.dir}/MANIFEST.MF" property="has.custom.manifest"/>
    <available file="${persistence.xml.dir}/persistence.xml" property="has.persistence.xml"/>
    <condition property="do.war.package.with.custom.manifest">
        <isset property="has.custom.manifest"/>
    </condition>
    <condition property="do.war.package.without.custom.manifest">
        <not>
            <isset property="has.custom.manifest"/>
        </not>
    </condition>
    <condition property="do.tmp.war.package.with.custom.manifest">
        <and>
            <isset property="has.custom.manifest"/>
            <or>
                <isfalse value="${directory.deployment.supported}"/>
                <isset property="dist.ear.dir"/>
            </or>
        </and>
    </condition>
    <condition property="do.tmp.war.package.without.custom.manifest">
        <and>
            <not>
                <isset property="has.custom.manifest"/>
            </not>
            <or>
                <isfalse value="${directory.deployment.supported}"/>
                <isset property="dist.ear.dir"/>
            </or>
        </and>
    </condition>
    <condition property="do.tmp.war.package">
        <or>
            <isfalse value="${directory.deployment.supported}"/>
            <isset property="dist.ear.dir"/>
        </or>
    </condition>
    <property name="build.meta.inf.dir" value="${build.web.dir}/META-INF"/>
    <condition else="" property="application.args.param" value="${application.args}">
        <and>
            <isset property="application.args"/>
            <not>
                <equals arg1="${application.args}" arg2="" trim="true"/>
            </not>
        </and>
    </condition>
    <property name="source.encoding" value="${file.encoding}"/>
    <condition property="javadoc.encoding.used" value="${javadoc.encoding}">
        <and>
            <isset property="javadoc.encoding"/>
            <not>
                <equals arg1="${javadoc.encoding}" arg2=""/>
            </not>
        </and>
    </condition>
    <property name="javadoc.encoding.used" value="${source.encoding}"/>
    <property name="includes" value="**"/>
    <property name="excludes" value=""/>
    <property name="runmain.jvmargs" value=""/>
    <path id="endorsed.classpath.path" path="${endorsed.classpath}"/>
    <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'">
        <and>
            <isset property="endorsed.classpath"/>
            <length length="0" string="${endorsed.classpath}" when="greater"/>
        </and>
    </condition>
    <condition else="false" property="jdkBug6558476">
        <and>
            <matches pattern="1\.[56]" string="${java.specification.version}"/>
            <not>
                <os family="unix"/>
            </not>
        </and>
    </condition>
    <property name="javac.fork" value="${jdkBug6558476}"/>
    <condition property="junit.available">
        <or>
            <available classname="org.junit.Test" classpath="${run.test.classpath}"/>
            <available classname="junit.framework.Test" classpath="${run.test.classpath}"/>
        </or>
    </condition>
    <condition property="testng.available">
        <available classname="org.testng.annotations.Test" classpath="${run.test.classpath}"/>
    </condition>
    <condition property="junit+testng.available">
        <and>
            <istrue value="${junit.available}"/>
            <istrue value="${testng.available}"/>
        </and>
    </condition>
    <condition else="testng" property="testng.mode" value="mixed">
        <istrue value="${junit+testng.available}"/>
    </condition>
    <condition else="" property="testng.debug.mode" value="-mixed">
        <istrue value="${junit+testng.available}"/>
    </condition>
</target>


来源: stackexchange

问:
How to get hours difference between now and next friday
I want to get hours difference between now and next friday 18:00 (weekend) using momentjs, I tried this but it doesn't work :

```<code>public getWeekend() {
    const nextFriday = moment().weekday(4)
    nextFriday.hours(18) // Weekend time: 18:00
    nextFriday.minutes(0)
    nextFriday.seconds(0)

    const diff = moment(nextFriday.diff(moment()))
    console.log(diff.days())
    if (diff.days() * 24 + diff.hours() <= 99) {
      return nextFriday.toString()
    } else {
      return 0
    }
  }
}
</code>```

console.log(diff.days()) is printing 6 days whereas we are Wednesday

答:
UPDATED , it is totally correct now.

First of all Friday actually has sequence number 5, so use it instead 4.
const nextFriday = moment().weekday(5) - this is correct Friday.

Next important thing is that nearest Friday is taken by default, it means that already passed Friday can be selected (for example if it is Satturday today). In such case we just need to add one week.

Here is working code snippet:

function getWeekend() {
    const today = moment();
    const friday = moment().weekday(5);
    // check if wee need to add one week in case of previous Friday selected
    if (friday < today) {
        friday.add(1, 'weeks');
    }
    friday.hours(18) // Weekend time: 18:00
    friday.minutes(0)
    friday.seconds(0)
    return friday.diff(moment(), 'hours');
}

const hoursToFriday = getWeekend();
console.log(`Friday 18:00 will be in ${hoursToFriday} hours`);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to get hours difference between now and next friday 18:00 (weekend) using momentjs, I tried this but it doesn't work :

public getWeekend() {
    const nextFriday = moment().weekday(4)
    nextFriday.hours(18) // Weekend time: 18:00
    nextFriday.minutes(0)
    nextFriday.seconds(0)

    const diff = moment(nextFriday.diff(moment()))
    console.log(diff.days())
    if (diff.days() * 24 + diff.hours() <= 99) {
      return nextFriday.toString()
    } else {
      return 0
    }
  }
}

console.log(diff.days()) is printing 6 days whereas we are Wednesday

Body:
UPDATED , it is totally correct now.

First of all Friday actually has sequence number 5, so use it instead 4.
const nextFriday = moment().weekday(5) - this is correct Friday.

Next important thing is that nearest Friday is taken by default, it means that already passed Friday can be selected (for example if it is Satturday today). In such case we just need to add one week.

Here is working code snippet:

function getWeekend() {
    const today = moment();
    const friday = moment().weekday(5);
    // check if wee need to add one week in case of previous Friday selected
    if (friday < today) {
        friday.add(1, 'weeks');
    }
    friday.hours(18) // Weekend time: 18:00
    friday.minutes(0)
    friday.seconds(0)
    return friday.diff(moment(), 'hours');
}

const hoursToFriday = getWeekend();
console.log(`Friday 18:00 will be in ${hoursToFriday} hours`);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>


问:
Blank bar at the bottom of a page
I've been working on a few sites, and for some reason, a blank bar keeps showing up at the bottom. I've tried inspecting the elements, and I get nothing that makes any sense. html and body elements are set for margin: 0 and padding: 0.

Any ideas on how to remove the blank bar at the bottom?

Thank you!

答: Remove the   from your clearfixing divs. Even with the height:0, the space character is taking up space. One you remove it, the div will collapse properly.

OwnerDisplayName: Brandon Martinez

ContentLicense: CC BY-SA 3.0

Title: Blank bar at the bottom of a page

Body: Remove the &nbsp; from your clearfixing divs. Even with the height:0, the space character is taking up space. One you remove it, the div will collapse properly.

OwnerDisplayName: Ciaran


问:
Color columns based on x axis and not on values (y axis) in highcharts
Trying to color columns based on x axis( negative, 0s and positives), just not able to do it. Tried several things.

Tried several options in fiddle.. but not able to do it.

Tried the zone method, added zones at all possible places.

```<code>zones: [{
        value: -3,
        color: 'red'
    }, {
        value: 0,
        color: 'orange'
    }, {
        color: 'green'
    }]
</code>```

http://jsfiddle.net/rxnj0qc1/

No errors.. the colors just wont appear.

答:
You need to set zones in a series:

```<code>series: [{
    ...,
    zoneAxis: 'x',
    zones: [{
        value: 10,
        color: 'red'
    }, {
        value: 12,
        color: 'orange'
    }, {
        color: 'green'
    }]
}]
</code>```

Live demo: http://jsfiddle.net/BlackLabel/mpxtqzsv/

API Reference:

https://api.highcharts.com/highcharts/series.column.zoneAxis

https://api.highcharts.com/highcharts/series.column.zones

Body:
Trying to color columns based on x axis( negative, 0s and positives), just not able to do it. Tried several things.

Tried several options in fiddle.. but not able to do it.

Tried the zone method, added zones at all possible places.

zones: [{
        value: -3,
        color: 'red'
    }, {
        value: 0,
        color: 'orange'
    }, {
        color: 'green'
    }]

http://jsfiddle.net/rxnj0qc1/

No errors.. the colors just wont appear.

Body:
You need to set zones in a series:

series: [{
    ...,
    zoneAxis: 'x',
    zones: [{
        value: 10,
        color: 'red'
    }, {
        value: 12,
        color: 'orange'
    }, {
        color: 'green'
    }]
}]

Live demo: http://jsfiddle.net/BlackLabel/mpxtqzsv/

API Reference:

https://api.highcharts.com/highcharts/series.column.zoneAxis

https://api.highcharts.com/highcharts/series.column.zones


问:
How to make a comment on board in Nodejs
I am creating an application using Nodejs and React, but the comment function does not work. I do not know the cause.

Error :

board validation failed: comments.0.content: Path content is required.

I don't know why this is not working. What mistake did I make?

route/api/board.js

```<code>router.post(
    '/:id/comments',
    [
        auth,
        [
            check('content', 'input your content. ')
                .not()
                .isEmpty()
        ]
    ],
    async (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() }, 'isEmpty');
        }

        try {
            const user = await User.findById(req.user.id).select('-password');
            const board = await Board.findById(req.params.id);
            const newComment = new Board({
                content: req.body.content,
                user: req.user.id
            });

            board.comments.unshift(newComment);

            await board.save();

            res.json(board.comments);
        } catch (err) {
            console.error(err.message);
            res.status(500).send('Server error!!');
        }
    }
);
</code>```

models/Board.js

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BoardSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'user'
    },
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    view_count: {
        type: Number,
        default: 1
    },
    created_at: {
        type: Date,
        default: Date.now
    },
    likes: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: 'user'
            }
        }
    ],
    comments: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: 'user'
            },
            content: {
                type: String,
                required: true
            },
            created_at: {
                type: Date,
                default: Date.now
            }
        }
    ]
});

module.exports = Board = mongoose.model('board', BoardSchema);
</code>```

答:
The error is pretty explicit, one of your comments in the comments array doesn't have a property content which seem to be required based on your model.

So double check what you are sending to the server by debugging/logging the content of the req.body.

Body:
I am creating an application using Nodejs and React, but the comment function does not work. I do not know the cause.

Error :

board validation failed: comments.0.content: Path content is required.

I don't know why this is not working. What mistake did I make?

route/api/board.js

router.post(
    '/:id/comments',
    [
        auth,
        [
            check('content', 'input your content. ')
                .not()
                .isEmpty()
        ]
    ],
    async (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() }, 'isEmpty');
        }

        try {
            const user = await User.findById(req.user.id).select('-password');
            const board = await Board.findById(req.params.id);
            const newComment = new Board({
                content: req.body.content,
                user: req.user.id
            });

            board.comments.unshift(newComment);

            await board.save();

            res.json(board.comments);
        } catch (err) {
            console.error(err.message);
            res.status(500).send('Server error!!');
        }
    }
);

models/Board.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BoardSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'user'
    },
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    view_count: {
        type: Number,
        default: 1
    },
    created_at: {
        type: Date,
        default: Date.now
    },
    likes: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: 'user'
            }
        }
    ],
    comments: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: 'user'
            },
            content: {
                type: String,
                required: true
            },
            created_at: {
                type: Date,
                default: Date.now
            }
        }
    ]
});

module.exports = Board = mongoose.model('board', BoardSchema);


答:
I recommended to use moment

```<code>const diff = moment.duration(nextFriday.diff(moment()))
const deepDiff = diff.format("D [day], H [hour and] m [min]")
</code>```

Title: How to get hours difference between now and next friday

Body:
I recommended to use moment

const diff = moment.duration(nextFriday.diff(moment()))
const deepDiff = diff.format("D [day], H [hour and] m [min]")


问:
Safari pauses all animation on redirect / form submission
I have an animation that triggers when a link is clicked. It is a jQuery animation that enlarges a div then fades out. To ensure speed, at the exact same time that the link is clicked, the redirect is fired off. This has to happen and I cannot put the redirect in the success function of jQuery's animate(). This redirect is done via a form submission. On Chrome, Firefox, and IE it works as expected, the animation plays and if the page loads entirely before the finish of the animation, it redirects but the animation does play.

On Safari (primarily testing on iPad), as soon as the link is clicked, the page seemingly 'freezes' and the animation fails to execute. There are also GIF's that are on the screen at page load, and if I click a link while those GIF's are on screen and animating, they pause as well. I have seen a post that says to set a timeout, apply styling, then submit, but the problem is that although the HTML will apply that CSS style, it still freezes the screen, and they are not dealing with animation, just static CSS styling.

Here is some example code to show the method of how I am accomplishing this (it is not tested just trying to illustrate my point, so there may be missing parts or syntax errors):

var someData = 'foo'; //This value is irrelevant, just there for syntactical consistency.
$("#link").on("click", function() {
    var form = $("<form method='POST'></form>");
    form.attr("action", "http://someurl.com");
    var input = $("<input type='hidden'/>");
    input.val(someData);
    form.append(input);
    $(document.body).append(form);
    form.submit();

    //Form has been submitted, now run a short animation for the remaining life of the current page
    $(this).animate({width: "100px", height: "100px", opacity: "0"}, 150);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="link" style="width: 100px; height: 100px; background-color: #FFF">Click Me</div></code>```

Essentially, I need to make sure that once the Safari browser begins to load a new page / link, it does not stop updating the current page. This sounds like a problem in Safari from what I have seen, but this issue has also not been run into very commonly across the web as I have seen. There are posts dealing with GIF animations, but this is a CSS style animation.

Thanks for any help!

答: Possibly use some Ajax to load the new page in a hidden frame while the animation is still going. When it finishes loading, do a normal redirect to the same URL. Then hopefully it would be an instant redirect since the new page may then be cached and its underlying query already processed.</p>

Body:
I have an animation that triggers when a link is clicked. It is a jQuery animation that enlarges a div then fades out. To ensure speed, at the exact same time that the link is clicked, the redirect is fired off. This has to happen and I cannot put the redirect in the success function of jQuery's animate(). This redirect is done via a form submission. On Chrome, Firefox, and IE it works as expected, the animation plays and if the page loads entirely before the finish of the animation, it redirects but the animation does play.

On Safari (primarily testing on iPad), as soon as the link is clicked, the page seemingly 'freezes' and the animation fails to execute. There are also GIF's that are on the screen at page load, and if I click a link while those GIF's are on screen and animating, they pause as well. I have seen a post that says to set a timeout, apply styling, then submit, but the problem is that although the HTML will apply that CSS style, it still freezes the screen, and they are not dealing with animation, just static CSS styling.

Here is some example code to show the method of how I am accomplishing this (it is not tested just trying to illustrate my point, so there may be missing parts or syntax errors):

var someData = 'foo'; //This value is irrelevant, just there for syntactical consistency.
$("#link").on("click", function() {
    var form = $("<form method='POST'></form>");
    form.attr("action", "http://someurl.com");
    var input = $("<input type='hidden'/>");
    input.val(someData);
    form.append(input);
    $(document.body).append(form);
    form.submit();

    //Form has been submitted, now run a short animation for the remaining life of the current page
    $(this).animate({width: "100px", height: "100px", opacity: "0"}, 150);
  });

Click Me

Essentially, I need to make sure that once the Safari browser begins to load a new page / link, it does not stop updating the current page. This sounds like a problem in Safari from what I have seen, but this issue has also not been run into very commonly across the web as I have seen. There are posts dealing with GIF animations, but this is a CSS style animation.

Thanks for any help!


问:
Reject issue: "We are not able to continue because we need a demo QR code or AR marker (image) to fully assess your app features."
I have a project in a flutter. It has QR code scanner and the QR code is generated from the web and is called using API. QR code scanner scans the QR-code to get the information of the user. I submitted my app and got rejected saying :

```<code>We have started the review of your app, but we are not able to continue
because we need a demo QR code or AR marker (image) to fully assess your
app features.
</code>```

Next Steps

```<code>To help us proceed with the review of your app, please provide the demo
details in the App Review Information section for your app in App Store
Connect or reply to this message with the requested demo information.
Please ensure that the information you provide includes any data necessary
to demonstrate the functionality of your app features.
</code>```

To provide QR codes or images information:

```<code>- Log in to App Store Connect
- Click on "My Apps"
- Select your app
- Click on the app version on the left side of the screen
- Scroll down to "App Review Information"
- Provide information in "Notes" as appropriate
- Click "Save"
- Once you've completed all changes, click the "Save" button at the top of
the Version Information page.
</code>```

Then I created a demo video to use QR code scanner and wrote some

notes as:

```<code>  *The QR code image for each user is provided from our API and set on
  lock
  screen by the user.
  *The purpose of the camera permission is to scan the QR code.
  *The Scanned QR code returns the details uploaded by the user whose
  phone is lost. A demo video is attached on attachment.
</code>```

I again submitted to the app store and still, it rejected saying the same error as above. I couldn't find the possible solutions. Anyone could help me?

答:
You need to give them the QR code (may be the qr code image) so they can scan and check your app feature/functionality. (Provide access to your web to generate QR-code, if possible)

Also include a detailed notes (including steps, data, etc.) about this feature/functionality.

Possible Rejection reason

It might possible that they were scanning the QR code but they may not proceed with the invalid QR-code scanning. Thats the reason they ask for the QR-code demo (QR-code image) so that can use in review process.

Body:
I have a project in a flutter. It has QR code scanner and the QR code is generated from the web and is called using API. QR code scanner scans the QR-code to get the information of the user. I submitted my app and got rejected saying :

We have started the review of your app, but we are not able to continue
because we need a demo QR code or AR marker (image) to fully assess your
app features.

Next Steps

To help us proceed with the review of your app, please provide the demo
details in the App Review Information section for your app in App Store
Connect or reply to this message with the requested demo information.
Please ensure that the information you provide includes any data necessary
to demonstrate the functionality of your app features.

To provide QR codes or images information:

- Log in to App Store Connect
- Click on "My Apps"
- Select your app
- Click on the app version on the left side of the screen
- Scroll down to "App Review Information"
- Provide information in "Notes" as appropriate
- Click "Save"
- Once you've completed all changes, click the "Save" button at the top of
the Version Information page.

Then I created a demo video to use QR code scanner and wrote some

notes as:

  *The QR code image for each user is provided from our API and set on
  lock
  screen by the user.
  *The purpose of the camera permission is to scan the QR code.
  *The Scanned QR code returns the details uploaded by the user whose
  phone is lost. A demo video is attached on attachment.

I again submitted to the app store and still, it rejected saying the same error as above. I couldn't find the possible solutions. Anyone could help me?


问:
Loop through an array with special condition
I want to do save me some code with if statements so I do a loop here.

How can I do the following without creating a new array? I want to keep relying on the first $arr

This is a simple example, my array is actually much bigger than that :) So please keep that in mind, I have to check on the items of firstname and then do something.

```<code>$arr = ['man_firstname', 'man_lastname', 'woman_firstname', 'woman_lastname'];

// just making sure the value from db is set
// otherwise set it to an empty string
foreach ($arr as $item) {
    isset($db[$item]) ? $$item = $db[$item] : $$item = '';
}

// with that loop I have now $man_firstname, $man_lastname, $woman_firstname
// and $woman_lastname  are all set to their db values or are empty

// now I want to echo both first name
// and last name of the man and woman but ONLY WHEN THEIR FIRST NAMES IS NOT EMPTY

foreach (?? as ??) {
    if (!empty(firstname)) {
        // echo both first name and last name
    }
}

// desired results: echo "john doe" only if firstname of the man is set,
// the same with "jenna smith" if her first name is not set then do
// nothing with her array item```
```

答:
If I correctly understood your problem you want something like that :

```<code>$arr = ['john', 'doe', 'john', '', 'jenna', 'smith', '', 'smith'];

if (count($arr) % 2) {
   throw new Exception('Missing person name / surname !');
}

for ($i=0; $i < count($arr); $i+=2) {
   if ($arr[$i] && $arr[$i+1]) {
      echo "{$arr[$i]} {$arr[$i+1]}<br>";
   }
}
</code>```

Btw, keep in mind that in your array should be even number of names + surnames - otherwise you will not know what is missing - name or surname and for what person it is missing. That's why I've added exception generation in that case.

Body:
I want to do save me some code with if statements so I do a loop here.

How can I do the following without creating a new array? I want to keep relying on the first $arr

This is a simple example, my array is actually much bigger than that :) So please keep that in mind, I have to check on the items of firstname and then do something.

$arr = ['man_firstname', 'man_lastname', 'woman_firstname', 'woman_lastname'];

// just making sure the value from db is set
// otherwise set it to an empty string
foreach ($arr as $item) {
    isset($db[$item]) ? $$item = $db[$item] : $$item = '';
}

// with that loop I have now $man_firstname, $man_lastname, $woman_firstname
// and $woman_lastname  are all set to their db values or are empty

// now I want to echo both first name
// and last name of the man and woman but ONLY WHEN THEIR FIRST NAMES IS NOT EMPTY

foreach (?? as ??) {
    if (!empty(firstname)) {
        // echo both first name and last name
    }
}

// desired results: echo "john doe" only if firstname of the man is set,
// the same with "jenna smith" if her first name is not set then do
// nothing with her array item```

Body:
If I correctly understood your problem you want something like that :

$arr = ['john', 'doe', 'john', '', 'jenna', 'smith', '', 'smith'];

if (count($arr) % 2) {
   throw new Exception('Missing person name / surname !');
}

for ($i=0; $i < count($arr); $i+=2) {
   if ($arr[$i] && $arr[$i+1]) {
      echo "{$arr[$i]} {$arr[$i+1]}<br>";
   }
}

Btw, keep in mind that in your array should be even number of names + surnames - otherwise you will not know what is missing - name or surname and for what person it is missing. That's why I've added exception generation in that case.


问:
(Microsoft Azure custom vision service: Object Detection) How to find bounding box info of training data?
I am using Microsoft custom vision service in object detection to extract the wanted objects. And I would like to make a regression test to compare the results. However, I cannot find a place to export the training picture with the bounding box that user defined by GUI.

The model training is done within the custom vision platform provided by Microsoft (https://www.customvision.ai/). Within this platform we can add the images and then tag the objects. I have tried to export the model, but I am not sure where to find the info of training pictures along with their tag(s) and bounding box(es).

I expect that in this platform, user can export the not only the trained model but also the training data (images with tags and bounding boxes.) But I was not able to find them.

答:
All the data that you are looking for is available through Custom Vision Training API. Currently the latest API is v3.0, its portal is here.

More in details, GetTaggedImages method will give you the associations of images and regions bounding box

Sample result of this method with one of my demos:

With these details, you will be able to get the image and place the boundingBox that was used for training.


问:
What UNIX commands support coloured output?
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

```<code>ls --color=auto
grep --color
phpunit --ansi
</code>```

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

答:
This demo bash script colours directories red in most terminals  - certainly works in xterms and cygwin under Windows. You can adapt the colours by fiddling with the escape codes - Google for LS_COLOR for lists of colour codes:</p>

```<code>#!/bin/bash

color_red()
{
    echo -e "\033[01;31m$1\033[00m"
}

for FILE in $*
do
    if test -d $FILE
    then
        color_red $FILE
    else
        echo $FILE
    fi
done
</code>```

OwnerDisplayName: DavidWinterbottom

ContentLicense: CC BY-SA 2.5

Body:
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

ls --color=auto
grep --color
phpunit --ansi

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

LastEditorDisplayName: Eddie

Body:
This demo bash script colours directories red in most terminals  - certainly works in xterms and cygwin under Windows. You can adapt the colours by fiddling with the escape codes - Google for LS_COLOR for lists of colour codes:

#!/bin/bash

color_red()
{
    echo -e "\033[01;31m$1\033[00m"
}

for FILE in $*
do
    if test -d $FILE
    then
        color_red $FILE
    else
        echo $FILE
    fi
done

OwnerDisplayName: anon


问:
Entity framework Models Access entity from another model
I have a Model of MyQueue and Service I dunno how can I get the ServiceLetter on my Services model properly to render it on my view.

Here is my MyQueue Model.

```<code>public class MyQueue
{
    public int MyQueueId { get; set; }

    public string Name { get; set; }

    public string QueueNumber
    {
        get
        {

     return string.Format("{0}{1:000}", ServiceLetter ?? "?", MyQueueId);
        }
        set { }
    }

    public int ServiceId { get; set; }

    public string ServiceLetter { get; set; }

    public virtual Service Service { get; set; }
}
</code>```

here is my Service Model

```<code>public class Service
{
    public int ServiceId { get; set; }

    public string ServiceName { get; set; }

    public string ServiceLetter { get; set; }
}
</code>```

In my dbo.MyQueues my ServiceLetter data only shows number, I need it to become what ever letter I put on my Service

I want my MyQueue to be like this, ServiceLetter is Letter not Number,

MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter

1 - JohnDoe - A001 - 1 - A

2 - DoeJogn - B002 - 2 - B

3 - JognDog - C002 - 3 - C

答:
You need to create ServiceId as Foreign Key in 'MyQueue'. And when you are accesing 'dbo.MyQueues', then please INCLUDE 'Service'</p>

```<code>dbo.MyQueues.Include(q => q.Service);
</code>```

Body:
I have a Model of MyQueue and Service I dunno how can I get the ServiceLetter on my Services model properly to render it on my view.

Here is my MyQueue Model.

public class MyQueue
{
    public int MyQueueId { get; set; }

    public string Name { get; set; }

    public string QueueNumber
    {
        get
        {

     return string.Format("{0}{1:000}", ServiceLetter ?? "?", MyQueueId);
        }
        set { }
    }

    public int ServiceId { get; set; }

    public string ServiceLetter { get; set; }

    public virtual Service Service { get; set; }
}

here is my Service Model

public class Service
{
    public int ServiceId { get; set; }

    public string ServiceName { get; set; }

    public string ServiceLetter { get; set; }
}

In my dbo.MyQueues my ServiceLetter data only shows number, I need it to become what ever letter I put on my Service

I want my MyQueue to be like this, ServiceLetter is Letter not Number,

MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter

1 - JohnDoe - A001 - 1 - A

2 - DoeJogn - B002 - 2 - B

3 - JognDog - C002 - 3 - C

Body:
You need to create ServiceId as Foreign Key in 'MyQueue'. And when you are accesing 'dbo.MyQueues', then please INCLUDE 'Service'

dbo.MyQueues.Include(q => q.Service);


问:
Why are .innerHTML problems not an issue when using JQuery().html()?
I worked out any single instance of document.getElementById("MyID").innerHTML = "A value" in this Javascript World Clock guide causes Wordpress Admin not to load completely and breaks various areas of the Wordpress admin interface.

I solved it by replacing each instance with jQuery("#MyID").html("A value")) which appears to work fine. What is causing .innerHTML to fail miserably but not JQuery().html()?

答: At a guess I would suspect either browser-specific stuff or document.getElementById("MyID") returns null, causing an exception.


问:
request.getRequestURI always returns "/error"
In a webapp I'm building using Spring Boot & MVC and am trying to deny access to for all URL's except /signin for users that are not logged in. To achieve this I've setup an implementation of HandlerInterceptor where the preHandler should route all non-valid requests to the /signin page.

The setup:

LoginViewController

```<code>package com.controller;

import com.model.UserDao;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/signin")
@SessionAttributes("username")
public class LoginViewController {
    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showLoginForm(){
        return new ModelAndView("login");
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView verifyLogin(HttpServletRequest request, HttpSession session) {
        ModelAndView modelAndView;
        String username = request.getParameter("username");
        // if login fails, set reload login page
        if (userService.verifyUserLogin(username,request.getParameter("password")) == null){
            modelAndView = new ModelAndView("login");
            modelAndView.addObject("login_failed", true);
        } else {
            modelAndView = new ModelAndView("index");
            session.setAttribute("username", username);
        }
        return modelAndView;
    }
}
</code>```

AccessInterceptor

```<code>package com.spring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;

public class AccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
        System.out.println(request.getRequestURI());

        try {
            if (!request.getRequestURI().endsWith("/signin")) {
                if (request.getSession()
                        .getAttribute("username") == null) {
                    response.sendRedirect(request.getContextPath() + "/signin");
                    return false;
                }

            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("Post-handle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("After completion handle");
    }
}
</code>```

WebApplicationConfig

```<code>package com.spring;

import com.spring.interceptor.AccessInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
@EnableWebMvc
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
                new AccessInterceptor()).
                addPathPatterns("/**").
                excludePathPatterns("/signin/**").
                excludePathPatterns("/static/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

}
</code>```

WebApplicationInitializer

```<code>package com.spring;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

public class MyWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext =
                new AnnotationConfigWebApplicationContext();
        rootContext.register(WebApplicationConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext =
                new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(MyWebAppInitializer.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcherServlet", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
        dispatcher.addMapping("*.css");
        dispatcher.addMapping("*.eot");
        dispatcher.addMapping("*.svg");
        dispatcher.addMapping("*.ttf");
        dispatcher.addMapping("*.woff");
        dispatcher.addMapping("*.map");
        dispatcher.addMapping("*.js");
        dispatcher.addMapping("*.ico");
    }

}
</code>```

Now the problem is that the System.out.println(request.getRequestURI()) in AccessInterceptor always prints /error. So the request is always redirected even when calling /signin. Another interesting thing is that no CSS or other static resources are rendered, even with the dispacher mapping configured.

Any Ideas?

答: if you missing your payload, the api url couldn't recognize. at least put something

Body:
In a webapp I'm building using Spring Boot & MVC and am trying to deny access to for all URL's except /signin for users that are not logged in. To achieve this I've setup an implementation of HandlerInterceptor where the preHandler should route all non-valid requests to the /signin page.

The setup:

LoginViewController

package com.controller;

import com.model.UserDao;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/signin")
@SessionAttributes("username")
public class LoginViewController {
    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showLoginForm(){
        return new ModelAndView("login");
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView verifyLogin(HttpServletRequest request, HttpSession session) {
        ModelAndView modelAndView;
        String username = request.getParameter("username");
        // if login fails, set reload login page
        if (userService.verifyUserLogin(username,request.getParameter("password")) == null){
            modelAndView = new ModelAndView("login");
            modelAndView.addObject("login_failed", true);
        } else {
            modelAndView = new ModelAndView("index");
            session.setAttribute("username", username);
        }
        return modelAndView;
    }
}

AccessInterceptor

package com.spring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;

public class AccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
        System.out.println(request.getRequestURI());

        try {
            if (!request.getRequestURI().endsWith("/signin")) {
                if (request.getSession()
                        .getAttribute("username") == null) {
                    response.sendRedirect(request.getContextPath() + "/signin");
                    return false;
                }

            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("Post-handle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("After completion handle");
    }
}

WebApplicationConfig

package com.spring;

import com.spring.interceptor.AccessInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
@EnableWebMvc
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
                new AccessInterceptor()).
                addPathPatterns("/**").
                excludePathPatterns("/signin/**").
                excludePathPatterns("/static/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

}

WebApplicationInitializer

package com.spring;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

public class MyWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext =
                new AnnotationConfigWebApplicationContext();
        rootContext.register(WebApplicationConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext =
                new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(MyWebAppInitializer.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcherServlet", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
        dispatcher.addMapping("*.css");
        dispatcher.addMapping("*.eot");
        dispatcher.addMapping("*.svg");
        dispatcher.addMapping("*.ttf");
        dispatcher.addMapping("*.woff");
        dispatcher.addMapping("*.map");
        dispatcher.addMapping("*.js");
        dispatcher.addMapping("*.ico");
    }

}

Now the problem is that the System.out.println(request.getRequestURI()) in AccessInterceptor always prints /error. So the request is always redirected even when calling /signin. Another interesting thing is that no CSS or other static resources are rendered, even with the dispacher mapping configured.

Any Ideas?


问:
How to conditionally run npm script
I am looking for a cross-platform way of conditionally running a step in my build script.

I have a build step that is expensive, however checking to see if it is necessary is relatively quick.  I have created a script that returns a non-zero error code if it is not necessary to do the build step.  How can I write my npm script to only run the build if the check passes but provide errors if the build step fails?

Example package.json:

```<code>"scripts": {
    "schema:build": "npm run schema:rebuild-check && npm run schema:force-build",
    "schema:rebuild-check": "node tools/schema is-rebuild-necessary",
    "schema:force-build": "npm run schema:validate && npm run schema:generate-index && npm run schema:bundle"
}
</code>```

The problem with the above is that if the rebuild is not necessary my entire build fails.  I can't just swallow the exit code with something like exitzero because I want to know if any of the commands fail in the schema:force-build script.

答:
The problem arises from two things:

1) If an npm script exits with a non-zero code npm will always complain

2) Need to provide an "else" that returns non zero using the || operator

Working solution:

```<code>"schema:build": "node tools/schema is-rebuild-necessary && npm run schema:force-build || echo Skipping schema build",
"schema:force-build": "npm run schema:validate && npm run schema:generate-index && npm run schema:bundle"
</code>```

Title: How to conditionally run npm script

Body:
I am looking for a cross-platform way of conditionally running a step in my build script.

I have a build step that is expensive, however checking to see if it is necessary is relatively quick.  I have created a script that returns a non-zero error code if it is not necessary to do the build step.  How can I write my npm script to only run the build if the check passes but provide errors if the build step fails?

Example package.json:

"scripts": {
    "schema:build": "npm run schema:rebuild-check && npm run schema:force-build",
    "schema:rebuild-check": "node tools/schema is-rebuild-necessary",
    "schema:force-build": "npm run schema:validate && npm run schema:generate-index && npm run schema:bundle"
}

The problem with the above is that if the rebuild is not necessary my entire build fails.  I can't just swallow the exit code with something like exitzero because I want to know if any of the commands fail in the schema:force-build script.

Body:
The problem arises from two things:

1) If an npm script exits with a non-zero code npm will always complain

2) Need to provide an "else" that returns non zero using the || operator

Working solution:

"schema:build": "node tools/schema is-rebuild-necessary && npm run schema:force-build || echo Skipping schema build",
"schema:force-build": "npm run schema:validate && npm run schema:generate-index && npm run schema:bundle"


问:
CSS Scroll Snap with Animation Effect
Precondition

I am trying to make a number list picker that user can scroll on it.
The selected number was supposed to snap to the center of the container.
Once a number was selected, it should be enlarged and changed the color.

Problems

How can I snap the first or latest items to the center of the
container?

Is there a CSS or JavaScript way to detect a number is
snapping to the center then assign selected class on it?

Do not rely on any plugins.

* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
  scroll-snap-type: y mandatory;
}

.cell {
  display: block;
  scroll-snap-align: center;
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #e9e9f2;
  font-size: 2.4rem;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="scrollport">
    <div class="cell">09</div>
    <div class="cell selected">10</div>
    <div class="cell">11</div>
    <div class="cell">12</div>
    <div class="cell">13</div>
    <div class="cell">14</div>
    <div class="cell">15</div>
    <div class="cell">16</div>
  </div>
</div></code>```

Expect Result

答:
Add pseudo elements to .scrollport and style them like .cell

```<code>.scrollport:before,
.scrollport:after {
  content: '';
}
.scrollport:before,
.scrollport:after,
.cell {
  /* ... */
}
</code>```

Also I created a JS function that utilizes David Walsh's debounce function to simulate a scrollend event. I then check for every cell if it's center is around the scrollport's center and set the classes accordingly

"use strict";
console.clear()

{
  const selector = 'scrollport'
  const selected = 'selected'
  const scrollports = document.getElementsByClassName(selector)

  for (const scrollport of scrollports) {
    scrollport.addEventListener('scroll', debounce(check, 250) /* simulate scrollend event */ )
  }

  function check(e) {
    // uses native elementFromPoint for better performance
    const rect = e.target.getBoundingClientRect();
    const centerCell = document.elementFromPoint(rect.left + e.target.offsetWidth / 2, rect.top + e.target.offsetHeight / 2)
    for (const cell of e.target.getElementsByClassName(selected)) {
      cell.classList.remove(selected)
    }
    centerCell.classList.add(selected)

    // Old version for backward compatibility
    // const rect = e.target.getBoundingClientRect();
    // for (const cell of e.target.children) {
    //   const cellRect = cell.getBoundingClientRect();
    //   const bounds = [rect.height/2 - cellRect.height/2, rect.height/2 + cellRect.height/2];
    //   const centerScrollOffset = cellRect.top - rect.top + cell.offsetHeight / 2
    //   if (bounds[0] < centerScrollOffset && centerScrollOffset < bounds[1]) {
    //     cell.classList.add(selected)
    //   } else {
    //     cell.classList.remove(selected)
    //   }
    // }
  }
}
// From: https://davidwalsh.name/javascript-debounce-function
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this,
      args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scrollport:before,
.scrollport:after {
  content: '';
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
  scroll-snap-type: y mandatory;
}

.scrollport:before,
.scrollport:after,
.cell {
  display: block;
  scroll-snap-align: center;
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #e9e9f2;
  font-size: 2.4rem;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}</code>```

09

10

11

12

13

14

15

16

```

Title: CSS Scroll Snap with Animation Effect

Body:
Precondition

I am trying to make a number list picker that user can scroll on it.
The selected number was supposed to snap to the center of the container.
Once a number was selected, it should be enlarged and changed the color.

Problems

How can I snap the first or latest items to the center of the
container?

Is there a CSS or JavaScript way to detect a number is
snapping to the center then assign selected class on it?

Do not rely on any plugins.

* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
  scroll-snap-type: y mandatory;
}

.cell {
  display: block;
  scroll-snap-align: center;
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #e9e9f2;
  font-size: 2.4rem;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}

09

10

11

12

13

14

15

16

Expect Result

Body:
Add pseudo elements to .scrollport and style them like .cell

.scrollport:before,
.scrollport:after {
  content: '';
}
.scrollport:before,
.scrollport:after,
.cell {
  /* ... */
}

Also I created a JS function that utilizes David Walsh's debounce function to simulate a scrollend event. I then check for every cell if it's center is around the scrollport's center and set the classes accordingly

"use strict";
console.clear()

{
  const selector = 'scrollport'
  const selected = 'selected'
  const scrollports = document.getElementsByClassName(selector)

  for (const scrollport of scrollports) {
    scrollport.addEventListener('scroll', debounce(check, 250) /* simulate scrollend event */ )
  }

  function check(e) {
    // uses native elementFromPoint for better performance
    const rect = e.target.getBoundingClientRect();
    const centerCell = document.elementFromPoint(rect.left + e.target.offsetWidth / 2, rect.top + e.target.offsetHeight / 2)
    for (const cell of e.target.getElementsByClassName(selected)) {
      cell.classList.remove(selected)
    }
    centerCell.classList.add(selected)

    // Old version for backward compatibility
    // const rect = e.target.getBoundingClientRect();
    // for (const cell of e.target.children) {
    //   const cellRect = cell.getBoundingClientRect();
    //   const bounds = [rect.height/2 - cellRect.height/2, rect.height/2 + cellRect.height/2];
    //   const centerScrollOffset = cellRect.top - rect.top + cell.offsetHeight / 2
    //   if (bounds[0] < centerScrollOffset && centerScrollOffset < bounds[1]) {
    //     cell.classList.add(selected)
    //   } else {
    //     cell.classList.remove(selected)
    //   }
    // }
  }
}
// From: https://davidwalsh.name/javascript-debounce-function
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this,
      args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scrollport:before,
.scrollport:after {
  content: '';
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
  scroll-snap-type: y mandatory;
}

.scrollport:before,
.scrollport:after,
.cell {
  display: block;
  scroll-snap-align: center;
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #e9e9f2;
  font-size: 2.4rem;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}

<div class="container">
  <div class="scrollport">
    <div class="cell">09</div>
    <div class="cell selected">10</div>
    <div class="cell">11</div>
    <div class="cell">12</div>
    <div class="cell">13</div>
    <div class="cell">14</div>
    <div class="cell">15</div>
    <div class="cell">16</div>
  </div>
</div>


问:
Load tableview from a common class
I have this certain class which handles the loading of a tableview from any viewcontroller. It is given as..

```<code>class TableViewConfig<ItemsType, CellType:UITableViewCell>: NSObject, UITableViewDataSource, UITableViewDelegate {

  var emptyDataSet: Bool {
    didSet {
      if emptyDataSet {
        tableView.tableFooterView = UIView()
      }
    }
  }

  var items: [ItemsType] {
    didSet {
      tableView.dataSource = self
      tableView.delegate = self
      tableView.reloadData()
    }
  }

  // MARK: - Private Properties
  typealias CellClosure = (_ item: ItemsType, _ cell: CellType) -> Void

  // Tableview Config
  private var tableView: UITableView
  private var cellIdentifier: String
  private var configureCellClosure: CellClosure

  // Delegate
  private var indexPathClosure: ((IndexPath?) -> Void)?

  // MARK: - Public Methods
  public func selectedRow(_ callBack: @escaping (IndexPath?) -> Void) {
    indexPathClosure = callBack
  }

  // MARK: - Inialization
  init(_ tableView: UITableView,
       items: [ItemsType],
       cellIdentifier identifier: String,
       configClosure config:@escaping CellClosure) {

    self.tableView = tableView
    self.cellIdentifier = identifier
    self.items = items
    self.configureCellClosure = config
    self.emptyDataSet = false
  }

  // MARK: UITableViewDataSource
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as! CellType
    cell.tag = indexPath.row
    configureCellClosure(items[indexPath.row], cell)
    return cell
  }

  private func item(at indexpath: IndexPath) -> ItemsType {
    return items[indexpath.row]
  }

  // MARK: UITableViewDelegate
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let callback = indexPathClosure {
      callback (indexPath)
    }
  }

}
</code>```

This class will handle the loading of a tableview with data from any viewcontroller.

Now my problem is I want to use this class and show a tableview in my viewcontroller. How can I do that..? Hope someone can help...

答: you have to do something like yourViewController Tableview.delegate = TableViewConfig</p>

Title: Load tableview from a common class

Body:
I have this certain class which handles the loading of a tableview from any viewcontroller. It is given as..

class TableViewConfig<ItemsType, CellType:UITableViewCell>: NSObject, UITableViewDataSource, UITableViewDelegate {

  var emptyDataSet: Bool {
    didSet {
      if emptyDataSet {
        tableView.tableFooterView = UIView()
      }
    }
  }

  var items: [ItemsType] {
    didSet {
      tableView.dataSource = self
      tableView.delegate = self
      tableView.reloadData()
    }
  }

  // MARK: - Private Properties
  typealias CellClosure = (_ item: ItemsType, _ cell: CellType) -> Void

  // Tableview Config
  private var tableView: UITableView
  private var cellIdentifier: String
  private var configureCellClosure: CellClosure

  // Delegate
  private var indexPathClosure: ((IndexPath?) -> Void)?

  // MARK: - Public Methods
  public func selectedRow(_ callBack: @escaping (IndexPath?) -> Void) {
    indexPathClosure = callBack
  }

  // MARK: - Inialization
  init(_ tableView: UITableView,
       items: [ItemsType],
       cellIdentifier identifier: String,
       configClosure config:@escaping CellClosure) {

    self.tableView = tableView
    self.cellIdentifier = identifier
    self.items = items
    self.configureCellClosure = config
    self.emptyDataSet = false
  }

  // MARK: UITableViewDataSource
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as! CellType
    cell.tag = indexPath.row
    configureCellClosure(items[indexPath.row], cell)
    return cell
  }

  private func item(at indexpath: IndexPath) -> ItemsType {
    return items[indexpath.row]
  }

  // MARK: UITableViewDelegate
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let callback = indexPathClosure {
      callback (indexPath)
    }
  }

}

This class will handle the loading of a tableview with data from any viewcontroller.

Now my problem is I want to use this class and show a tableview in my viewcontroller. How can I do that..? Hope someone can help...


问:
New Xamarin.Forms project from existing solution overwrites previously deployed app C#
I have a Xamarin Forms solution with iOS and android projects. I deployed it on Android.

Now, I created new solution and copied previous solutions' projects into the new solution.

Basically I need new instance of an app that has the same code like previous one with different Name only.

However when I deploy new Solutions' android project it overwrites the original one.

How can I clone projects in a way they are not treated as the same project?

答:
Change the application's package name in AndroidManifest.xml.

For iOS, change the Bundle Identifier in info.plist


问:
Ceph delete client.admin accidently
While learning Ceph , I accidently delete client.admin by using

```<code>ceph auth del client.admin
</code>```

Now I get

client.admin authentication error (1) Operation not permitted.Error connecting to cluster: PermissionError

all the time.

Is there a way to recover or recreate a new client.admin?

I've tried

ceph auth import -i /etc/ceph/ceph.client.admin.keyring
 and
ceph add client.admin

It didn't work for me.

答:
try to connect with mon keyring on ceph-node-1

```<code>ceph -n mon. --keyring /var/lib/ceph/mon/ceph-node-1/keyring get-or-create client.admin mon 'allow *' mds 'allow *' mgr 'allow *' osd 'allow *'
</code>```

then update /etc/ceph/ceph.client.admin.keyring

Title: Ceph delete client.admin accidently

Body:
While learning Ceph , I accidently delete client.admin by using

ceph auth del client.admin

Now I get

client.admin authentication error (1) Operation not permitted.Error connecting to cluster: PermissionError

all the time.

Is there a way to recover or recreate a new client.admin?

I've tried

ceph auth import -i /etc/ceph/ceph.client.admin.keyring
 and
ceph add client.admin

It didn't work for me.

Body:
try to connect with mon keyring on ceph-node-1

ceph -n mon. --keyring /var/lib/ceph/mon/ceph-node-1/keyring get-or-create client.admin mon 'allow *' mds 'allow *' mgr 'allow *' osd 'allow *'

then update /etc/ceph/ceph.client.admin.keyring


问:
Hide id property when creating object via wcf?
If I have simple add method like this

```<code>public void AddUser(User user)
{
        user.Id = Guid.NewGuid();
        _userList.Add(user);
}
</code>```

and User class like

```<code>[DataContract]
public class User
{

    [DataMember]
    public Guid Id { get; set; }
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public DateTime DateCreated { get; set; }
}
</code>```

Is it possible to hide user id when adding new object.
I know I can achieve this by parameterized input method (sending each object property as input parameter), but I don't think that fits with wcf model. And what if I have many properties? This is just a simple example.

答:
If you remove the [DataMember] attribute, then the GUID will not be available to WCF as it will not be serialized.
However, would this present a problem when consuming the user objects on either side of the service, if they are tied to a back-end database? Wouldn't you just be creating new user objects all the time?</p>

Body:
If I have simple add method like this

public void AddUser(User user)
{
        user.Id = Guid.NewGuid();
        _userList.Add(user);
}

and User class like

[DataContract]
public class User
{

    [DataMember]
    public Guid Id { get; set; }
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public DateTime DateCreated { get; set; }
}

Is it possible to hide user id when adding new object.
I know I can achieve this by parameterized input method (sending each object property as input parameter), but I don't think that fits with wcf model. And what if I have many properties? This is just a simple example.


问:
How to add devices to Device set in Botium Box
I'm setting Botium box Device set, but I can't choose any Devices. I've set my local Selenium Hub in Device providers. My Selenium hub is running in Docker.

I'm trying to follow this guide: https://botium.atlassian.net/wiki/spaces/BOTIUM/pages/32145510/Run+Selenium+Grid+and+Connect+to+Botium+Box

I can't see any devices provided by auto compete, but I can see Firefox and Chrome in Selenium Grid Console.

答:
The browser devices connected to your Selenium hub have to be configured in the resources/LOCALSELENIUM.json file (file is cached for a few minutes, so after changing wait some minutes or restart server).

The JSON structure is easy, you can find some description in the mentioned document. What's important is that the capabilities element is the actual webdriver capabilities configuration.

```<code>[
    {
        "name": "Google Chrome",
        "value": {
            "type": "DESKTOP",
            "capabilities": {
                "browserName": "chrome"
            }
        }
    },
    {
        "name": "Mozilla Firefox",
        "value": {
            "type": "DESKTOP",
            "capabilities": {
                "browserName": "firefox"
            }
        }
    }
]
</code>```

Body:
The browser devices connected to your Selenium hub have to be configured in the resources/LOCALSELENIUM.json file (file is cached for a few minutes, so after changing wait some minutes or restart server).

The JSON structure is easy, you can find some description in the mentioned document. What's important is that the capabilities element is the actual webdriver capabilities configuration.

[
    {
        "name": "Google Chrome",
        "value": {
            "type": "DESKTOP",
            "capabilities": {
                "browserName": "chrome"
            }
        }
    },
    {
        "name": "Mozilla Firefox",
        "value": {
            "type": "DESKTOP",
            "capabilities": {
                "browserName": "firefox"
            }
        }
    }
]


问:
how many words end in certain character in function calling to different file?
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

```<code>def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count
</code>```

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

```<code>def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """
</code>```

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

答:
Use:</p>

```<code>def count_possible_sentences(file_name):
    count = 0
    with open(file_name) as wordfile:              #Open file for read
        for line in wordfile:                      #Iterate each line
            for word in line.strip().split():      #Get words
                if word.endswith(("!", "?", ".")):  #Check if word ends with
                    count += 1
    return count
</code>```

Body:
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

Body:
Use:

def count_possible_sentences(file_name):
    count = 0
    with open(file_name) as wordfile:              #Open file for read
        for line in wordfile:                      #Iterate each line
            for word in line.strip().split():      #Get words
                if word.endswith(("!", "?", ".")):  #Check if word ends with
                    count += 1
    return count


问:
Fatal Exception: java.lang.ClassCastException: android.support.v7.widget.TintContextWrapper cannot be cast to android.app.Activity
We are facing this issue

Fatal Exception: java.lang.ClassCastException: android.support.v7.widget.TintContextWrapper cannot be cast to android.app.Activity

```<code> btnEdit.setOnClickListener { v ->
                val intent = Intent(v.context, Edit_Logs::class.java)
                v.context.startActivity(intent)
                (v.context as Activity).finish() // Getting Error Here
            }
</code>```

答: you can use ViewHolder's itemView context

Body:
We are facing this issue

Fatal Exception: java.lang.ClassCastException: android.support.v7.widget.TintContextWrapper cannot be cast to android.app.Activity

 btnEdit.setOnClickListener { v ->
                val intent = Intent(v.context, Edit_Logs::class.java)
                v.context.startActivity(intent)
                (v.context as Activity).finish() // Getting Error Here
            }


问:
400 Error while uploading blob on Cloud Storage
I have created a csv file in Cloud Function. Now, I need to upload it on Cloud Storage. I stored it in /tmp file. From there, I have to upload it on Cloud Storage.

Code used -

```<code>def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_file(source_file_name)
    print('File {} uploaded to {}.'.format(source_file_name,destination_blob_name))

final_df.to_csv('/tmp/'+file_name)
with open('/tmp/'+file_name, 'r') as file_obj:
    upload_blob('test-bucket',file_obj,file_name)
</code>```

But, I am facing the following error -

```<code>BadRequest: 400 PUT https://www.googleapis.com/upload/storage/v1/b/test-bucket/o?uploadType=resumable&upload_id=ABC: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>, 308)
</code>```

File is getting stored in the /tmp folder. From there, it is not getting uploaded. What exactly can be the error?

答:
A lot of possible reasons for the 400 error Bad request (not 404). Maybe you should specify the full path and you don't have open the file and pass it in the source_file_name. Here's what I've tried to successfully upload an object (tried it with an mp3 file) to GCS</p>

```<code>from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

if __name__ == '__main__':
    upload_blob ("[bucketname]", "/home/[username]/[filename]", "[filename]")
</code>```

Body:
I have created a csv file in Cloud Function. Now, I need to upload it on Cloud Storage. I stored it in /tmp file. From there, I have to upload it on Cloud Storage.

Code used -

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_file(source_file_name)
    print('File {} uploaded to {}.'.format(source_file_name,destination_blob_name))

final_df.to_csv('/tmp/'+file_name)
with open('/tmp/'+file_name, 'r') as file_obj:
    upload_blob('test-bucket',file_obj,file_name)

But, I am facing the following error -

BadRequest: 400 PUT https://www.googleapis.com/upload/storage/v1/b/test-bucket/o?uploadType=resumable&upload_id=ABC: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>, 308)

File is getting stored in the /tmp folder. From there, it is not getting uploaded. What exactly can be the error?

Body:
A lot of possible reasons for the 400 error Bad request (not 404). Maybe you should specify the full path and you don't have open the file and pass it in the source_file_name. Here's what I've tried to successfully upload an object (tried it with an mp3 file) to GCS

from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

if __name__ == '__main__':
    upload_blob ("[bucketname]", "/home/[username]/[filename]", "[filename]")


问:
Finding missing numbers in a preset range
I am having a problem finding missing values within a preset range.  For example I have:

Column A: 3, 5, 7, 9, 10, 11
I want either VBA or a formula in excel to return
Column B: 1, 2, 4, 6, 8, 12, 13 --> 30

The final number in Column B will vary.  I want it to change based on user discretion.  For my problem I am working with days of the month.  So January, February, and March have different total days.  I've seen a lot of examples, but all are based on a array in the spreedsheet.  What if I want to change the array to 1-30, 1-31, or 1-28 (depending on which month I am looking at)?

答:
You could try:

```<code>Option Explicit

Sub test()

    Dim LastRowA As Long, LastRowB As Long, i As Long, StartValue As Long, EndValue As Long
    Dim rng As Range

    StartValue = 1
    EndValue = 30

    With ThisWorkbook.Worksheets("Sheet1")

        LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row

        Set rng = .Range("A1:A" & LastRowA)

        For i = StartValue To EndValue

            If Application.WorksheetFunction.CountIf(rng, i) = 0 Then

                LastRowB = .Cells(.Rows.Count, "B").End(xlUp).Row

                If LastRowB = 1 And .Range("B" & LastRowB).Value = "" Then
                    .Range("B1").Value = i
                Else
                    .Range("B" & LastRowB + 1).Value = i
                End If

            End If

        Next i

    End With

End Sub
</code>```

Results:

Body:
You could try:

Option Explicit

Sub test()

    Dim LastRowA As Long, LastRowB As Long, i As Long, StartValue As Long, EndValue As Long
    Dim rng As Range

    StartValue = 1
    EndValue = 30

    With ThisWorkbook.Worksheets("Sheet1")

        LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row

        Set rng = .Range("A1:A" & LastRowA)

        For i = StartValue To EndValue

            If Application.WorksheetFunction.CountIf(rng, i) = 0 Then

                LastRowB = .Cells(.Rows.Count, "B").End(xlUp).Row

                If LastRowB = 1 And .Range("B" & LastRowB).Value = "" Then
                    .Range("B1").Value = i
                Else
                    .Range("B" & LastRowB + 1).Value = i
                End If

            End If

        Next i

    End With

End Sub

Results:


问:
Scrolling to the bottom of a page that changes height
I want to scroll to the bottom of a webpage using JS and, looking online, most people say to use

```<code>window.scrollTo(0,document.body.scrollHeight);
</code>```

However the page I want to scroll down changes its height as you reach the bottom (it continuously loads more and more of the page) so its height is not fixed. The eventual height also varies (thus I cannot just scroll to the final height of the page) so I need some way of scrolling until it determines it has reached the bottom (it cannot scroll any further).

答:
Sounds like you need to reach bottom of the page, wait for load and scroll to bottom again. You can't reach the end of the page where you cannot know the end.

```<code>function scroll_and_wait(){
  return new Promise(
    function(resolve, reject){
    setTimeout(function(){
    resolve(window.scrollTo(0,document.body.scrollHeight));
    }, 500);})}

 async function scroller(n){while(n>0){await scroll_and_wait();n=n-1;}}

 scroller(5)
</code>```

Calling scroller function will scroll to to bottom of the page as many times as you specify with 500ms pause for loading.

Body:
I want to scroll to the bottom of a webpage using JS and, looking online, most people say to use

window.scrollTo(0,document.body.scrollHeight);

However the page I want to scroll down changes its height as you reach the bottom (it continuously loads more and more of the page) so its height is not fixed. The eventual height also varies (thus I cannot just scroll to the final height of the page) so I need some way of scrolling until it determines it has reached the bottom (it cannot scroll any further).

Body:
Sounds like you need to reach bottom of the page, wait for load and scroll to bottom again. You can't reach the end of the page where you cannot know the end.

function scroll_and_wait(){
  return new Promise(
    function(resolve, reject){
    setTimeout(function(){
    resolve(window.scrollTo(0,document.body.scrollHeight));
    }, 500);})}

 async function scroller(n){while(n>0){await scroll_and_wait();n=n-1;}}

 scroller(5)

Calling scroller function will scroll to to bottom of the page as many times as you specify with 500ms pause for loading.


问:
Based on input selected redirect to new html page on button click
I am new to javascripts. Based on the input selected from the drop downlist I need to redirect to new html page once i click the next button.</p>

```<code>...
<p>Application Type&nbsp
<select id = "aList" name="selection">
<option value = "">---Select Value---</option>
<option value = "New_req_p2_web.html">External Web Application</option>
<option value = "New_req_p2_web.html">Internal Web Application</option>
<option value = "New_req_p2_mob.html">Mobile Application</option>
<option value = "New_req_p2_net.html">Network</option>
</select>
</p>
<button type="submit" id="next" onclick="WinOpen()">Next</button>
....
<script type="text/javascript">
function WinOpen() {
var url=document.redirect.selection.value
document.location.href=url
}
</script>
...
</code>```

答:
The updated code here, I hope it's useful for you.

Thanks

```<code><p>Application Type&nbsp
<select id="aList" name="selection">
  <option value="">---Select Value---</option>
  <option value="New_req_p2_web.html">External Web Application</option>
  <option value="New_req_p2_web.html">Internal Web Application</option>
  <option value="New_req_p2_mob.html">Mobile Application</option>
  <option value="New_req_p2_net.html">Network</option>
</select>
</p>
<button type="submit" id="next" onClick="WinOpen();">Next</button>

<script type="text/javascript">
  function WinOpen() {
    var url = document.getElementById("aList").value;
    document.location.href = url;
  }
</script>
</code>```

Body:
I am new to javascripts. Based on the input selected from the drop downlist I need to redirect to new html page once i click the next button.

...

Application Type&nbsp
<select id = "aList" name="selection">
<option value = "">---Select Value---</option>
<option value = "New_req_p2_web.html">External Web Application</option>
<option value = "New_req_p2_web.html">Internal Web Application</option>
<option value = "New_req_p2_mob.html">Mobile Application</option>
<option value = "New_req_p2_net.html">Network</option>
</select>

<button type="submit" id="next" onclick="WinOpen()">Next</button>
....

...

Body:
The updated code here, I hope it's useful for you.

Thanks

<p>Application Type&nbsp
<select id="aList" name="selection">
  <option value="">---Select Value---</option>
  <option value="New_req_p2_web.html">External Web Application</option>
  <option value="New_req_p2_web.html">Internal Web Application</option>
  <option value="New_req_p2_mob.html">Mobile Application</option>
  <option value="New_req_p2_net.html">Network</option>
</select>
</p>
<button type="submit" id="next" onClick="WinOpen();">Next</button>

<script type="text/javascript">
  function WinOpen() {
    var url = document.getElementById("aList").value;
    document.location.href = url;
  }
</script>