问:
FileUploader error when uploading images
I'm using nopcommerce and I've added code for photo upload using file uploader but I'm getting this error:

Reason: XHR returned response code 404

```<code>@model ProductDetailsModel
@using Nop.Core.Domain.Seo;
@using Nop.Core.Infrastructure;
@using Nop.Web.Models.Catalog;
@{
    Layout = "~/Views/Shared/_ColumnsOne.cshtml";

    //title
    Html.AddTitleParts(!String.IsNullOrEmpty(Model.MetaTitle) ? Model.MetaTitle : Model.Name);
    //meta
    Html.AddMetaDescriptionParts(Model.MetaDescription);
    Html.AddMetaKeywordParts(Model.MetaKeywords);
    //page class
    Html.AppendPageCssClassParts("html-product-details-page");

    var seoSettings = EngineContext.Current.Resolve<SeoSettings>();

    //canonical URL
    if (seoSettings.CanonicalUrlsEnabled)
    {
        var productUrl = Url.RouteUrl("Product", new { SeName = Model.SeName }, this.Request.Url.Scheme);
        Html.AddCanonicalUrlParts(productUrl);
    }

    //open graph META tags
    if (seoSettings.OpenGraphMetaTags)
    {
        Html.AddHeadCustomParts("<meta property=\"og:type\" content=\"product\" />");
        Html.AddHeadCustomParts("<meta property=\"og:title\" content=\"" + Html.Encode(Model.Name) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:description\" content=\"" + Html.Encode(Nop.Core.Html.HtmlHelper.StripTags(Model.MetaDescription)) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:image\" content=\"" + Model.DefaultPictureModel.ImageUrl + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:url\" content=\"" + Request.Url.AbsoluteUri + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:site_name\" content=\"" + Html.Encode(Model.CurrentStoreName) + "\" />");
    }

    //Twitter META tags
    if (seoSettings.TwitterMetaTags)
    {
        Html.AddHeadCustomParts("<meta property=\"twitter:card\" content=\"summary\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:site\" content=\"" + Html.Encode(Model.CurrentStoreName) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:title\" content=\"" + Html.Encode(Model.Name) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:description\" content=\"" + Html.Encode(Nop.Core.Html.HtmlHelper.StripTags(Model.MetaDescription)) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:image\" content=\"" + Model.DefaultPictureModel.ImageUrl + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:url\" content=\"" + Request.Url.AbsoluteUri + "\" />");
    }

    Html.AddCssFileParts("~/Scripts/fineuploader/fineuploader-4.2.2.min.css");
    Html.AddScriptParts("~/Scripts/fineuploader/jquery.fineuploader-4.2.2.min.js");

    <script type="text/template" id="qq-template-gallery">

        <div class="qq-uploader-selector qq-uploader qq-gallery" qq-drop-area-text="Drop files here">
            <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
                <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
            </div>
            <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
                <span class="qq-upload-drop-area-text-selector"></span>
            </div>
            <div class="qq-upload-button-selector qq-upload-button">
                <div>Upload a file</div>
            </div>
            <span class="qq-drop-processing-selector qq-drop-processing">
                <span>Processing dropped files...</span>
                <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
            </span>
            <ul class="qq-upload-list-selector qq-upload-list" role="region" aria-live="polite" aria-relevant="additions removals">
                <li>
                    <span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
                    <div class="qq-progress-bar-container-selector qq-progress-bar-container">
                        <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
                    </div>
                    <span class="qq-upload-spinner-selector qq-upload-spinner"></span>
                    <div class="qq-thumbnail-wrapper">
                        <img class="qq-thumbnail-selector" qq-max-size="120" qq-server-scale>
                    </div>
                    <button type="button" class="qq-upload-cancel-selector qq-upload-cancel">X</button>
                    <button type="button" class="qq-upload-retry-selector qq-upload-retry">
                        <span class="qq-btn qq-retry-icon" aria-label="Retry"></span>
                        Retry
                    </button>

                    <div class="qq-file-info">
                        <div class="qq-file-name">
                            <span class="qq-upload-file-selector qq-upload-file"></span>
                            <span class="qq-edit-filename-icon-selector qq-edit-filename-icon" aria-label="Edit filename"></span>
                        </div>
                        <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                        <span class="qq-upload-size-selector qq-upload-size"></span>
                        <button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete">
                            <span class="qq-btn qq-delete-icon" aria-label="Delete"></span>
                        </button>
                        <button type="button" class="qq-btn qq-upload-pause-selector qq-upload-pause">
                            <span class="qq-btn qq-pause-icon" aria-label="Pause"></span>
                        </button>
                        <button type="button" class="qq-btn qq-upload-continue-selector qq-upload-continue">
                            <span class="qq-btn qq-continue-icon" aria-label="Continue"></span>
                        </button>
                    </div>
                </li>
            </ul>

            <dialog class="qq-alert-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">Close</button>
                </div>
            </dialog>

            <dialog class="qq-confirm-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">No</button>
                    <button type="button" class="qq-ok-button-selector">Yes</button>
                </div>
            </dialog>

            <dialog class="qq-prompt-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <input type="text">
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">Cancel</button>
                    <button type="button" class="qq-ok-button-selector">Ok</button>
                </div>
            </dialog>
        </div>
    </script>
}
<!--product breadcrumb-->
@section Breadcrumb
{
    @Html.Partial("_ProductBreadcrumb", Model.Breadcrumb)
}
@Html.Widget("productdetails_after_breadcrumb", Model.Id)
<div class="page product-details-page">
    <div class="page-body">
        @Html.Widget("productdetails_top", Model.Id)
        @using (Html.BeginRouteForm("Product", new { SeName = Model.SeName }, FormMethod.Post, new { id = "product-details-form" }))
        {
            <div itemscope itemtype="http://schema.org/Product" data-productid="@Model.Id">
                <div class="product-essential">
                    @Html.Widget("productdetails_before_pictures", Model.Id)
                    <!--product pictures-->
                    @Html.Partial("_ProductDetailsPictures", Model)
                    @Html.Widget("productdetails_after_pictures", Model.Id)
                    <div class="overview">
                        @Html.Partial("_Discontinued", Model)
                        <div class="product-name">
                            <h1 itemprop="name">
                                @Model.Name
                            </h1>
                        </div>
                        @if (!String.IsNullOrEmpty(Model.ShortDescription))
                        {
                            <div class="short-description">
                                @Html.Raw(Model.ShortDescription)
                            </div>
                        }
                        @Html.Widget("productdetails_overview_top", Model.Id)
                        <!--product reviews-->
                        @Html.Partial("_ProductReviewOverview", Model.ProductReviewOverview)
                        <!--manufacturers-->
                        @Html.Partial("_ProductManufacturers", Model.ProductManufacturers)
                        <!--availability-->
                        @Html.Partial("_Availability", Model)
                        <!--SKU, MAN, GTIN, vendor-->
                        @Html.Partial("_SKU_Man_GTIN_Ven", Model)
                        <!--delivery-->
                        @Html.Partial("_DeliveryInfo", Model)
                        <!--sample download-->
                        @Html.Partial("_DownloadSample", Model)
                        <!--attributes-->
                        @{
                            var dataDictAttributes = new ViewDataDictionary();
                            dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format("attributes_{0}", Model.Id);
                            @Html.Partial("_ProductAttributes", Model.ProductAttributes, dataDictAttributes)
                        }
                        <!--gift card-->
                        @{
                            var dataDictGiftCard = new ViewDataDictionary();
                            dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format("giftcard_{0}", Model.Id);
                            @Html.Partial("_GiftCardInfo", Model.GiftCard, dataDictGiftCard)
                        }
                        <!--rental info-->
                        @{
                            var dataDictRental = new ViewDataDictionary();
                            dataDictRental.TemplateInfo.HtmlFieldPrefix = string.Format("rental_{0}", Model.Id);
                            @Html.Partial("_RentalInfo", Model, dataDictRental)
                        }
                        <!--price & add to cart-->
                        @{
                            var dataDictPrice = new ViewDataDictionary();
                            dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format("price_{0}", Model.Id);
                            @Html.Partial("_ProductPrice", Model.ProductPrice, dataDictPrice)

                            @Html.Partial("_ProductTierPrices", Model.TierPrices)

                            var dataDictAddToCart = new ViewDataDictionary();
                            dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
                            @Html.Partial("_AddToCart", Model.AddToCart, dataDictAddToCart)
                        }
                        <!--wishlist, compare, email a friend-->
                        <div class="overview-buttons">
                            @Html.Widget("productdetails_inside_overview_buttons_before", Model.Id)
                            @{
                                var dataDictAddToWishlist = new ViewDataDictionary();
                                dataDictAddToWishlist.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
                                @Html.Partial("_AddToWishlist", Model.AddToCart, dataDictAddToWishlist)
                            }
                            @Html.Partial("_CompareProductsButton", Model)
                            @Html.Partial("_ProductEmailAFriendButton", Model)
                            @Html.Widget("productdetails_inside_overview_buttons_after", Model.Id)
                        </div>
                        @Html.Partial("_ShareButton", Model)
                        @Html.Widget("productdetails_overview_bottom", Model.Id)
                    </div>
                    @if (!String.IsNullOrEmpty(Model.FullDescription))
                    {
                        <div class="full-description" itemprop="description">
                            @Html.Raw(Model.FullDescription)
                        </div>
                    }
                </div>
                @Html.Widget("productdetails_before_collateral", Model.Id)
                <div class="product-collateral">
                    @Html.Partial("_ProductSpecifications", Model.ProductSpecifications)
                    @Html.Partial("_ProductTags", Model.ProductTags)
                </div>
                @Html.Action("ProductsAlsoPurchased", "Product", new { productId = Model.Id })
                @Html.Action("RelatedProducts", "Product", new { productId = Model.Id })
            </div>
        }
        @Html.Widget("productdetails_bottom", Model.Id)

        @Html.Partial("Picture")
        <div id="fine-uploader-gallery"></div>
        <script>
        var galleryUploader = new qq.FineUploader({
            element: document.getElementById("fine-uploader-gallery"),
            template: 'qq-template-gallery',
            request: {
                endpoint: '/server/uploads'
            },
            thumbnails: {
                placeholders: {
                    waitingPath: '/source/placeholders/waiting-generic.png',
                    notAvailablePath: '/source/placeholders/not_available-generic.png'
                }
            },
            validation: {
                allowedExtensions: ['jpeg', 'jpg', 'gif', 'png']
            },
            callbacks: {
                onError: function (id, name, errorReason, xhrOrXdr) {
                    alert(qq.format("Error on file number {} - {}.  Reason: {}", id, name, errorReason));
                }
            },
            cors: {
                //all requests are expected to be cross-domain requests
                expected: false,

                //if you want cookies to be sent along with the request
                sendCredentials: false
            },
            xhrFields: {
                withCredentials: true
            }
        });
        </script>
    </div>

</div>
</code>```

答:
There is a known issue with nopCommerce regarding this. If your app is running under IIS Virtual Directory, Tiny MCE is likely not able to find your image.

Edit the following file:

\Administration\Views\Shared\EditorTemplates\RichEditor.cshtml

Uncomment the lines:

```<code>//allowJbimages = true;
//allowRoxyFileman = false;
</code>```

To:

```<code>allowJbimages = true;
allowRoxyFileman = false;
</code>```

References:
[1] https://github.com/nopSolutions/nopCommerce/issues/142
[2] https://www.nopcommerce.com/boards/t/35370/virtual-directory-not-included-in-the-images-urls.aspx

Body:
I'm using nopcommerce and I've added code for photo upload using file uploader but I'm getting this error:

Reason: XHR returned response code 404

@model ProductDetailsModel
@using Nop.Core.Domain.Seo;
@using Nop.Core.Infrastructure;
@using Nop.Web.Models.Catalog;
@{
    Layout = "~/Views/Shared/_ColumnsOne.cshtml";

    //title
    Html.AddTitleParts(!String.IsNullOrEmpty(Model.MetaTitle) ? Model.MetaTitle : Model.Name);
    //meta
    Html.AddMetaDescriptionParts(Model.MetaDescription);
    Html.AddMetaKeywordParts(Model.MetaKeywords);
    //page class
    Html.AppendPageCssClassParts("html-product-details-page");

    var seoSettings = EngineContext.Current.Resolve<SeoSettings>();

    //canonical URL
    if (seoSettings.CanonicalUrlsEnabled)
    {
        var productUrl = Url.RouteUrl("Product", new { SeName = Model.SeName }, this.Request.Url.Scheme);
        Html.AddCanonicalUrlParts(productUrl);
    }

    //open graph META tags
    if (seoSettings.OpenGraphMetaTags)
    {
        Html.AddHeadCustomParts("<meta property=\"og:type\" content=\"product\" />");
        Html.AddHeadCustomParts("<meta property=\"og:title\" content=\"" + Html.Encode(Model.Name) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:description\" content=\"" + Html.Encode(Nop.Core.Html.HtmlHelper.StripTags(Model.MetaDescription)) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:image\" content=\"" + Model.DefaultPictureModel.ImageUrl + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:url\" content=\"" + Request.Url.AbsoluteUri + "\" />");
        Html.AddHeadCustomParts("<meta property=\"og:site_name\" content=\"" + Html.Encode(Model.CurrentStoreName) + "\" />");
    }

    //Twitter META tags
    if (seoSettings.TwitterMetaTags)
    {
        Html.AddHeadCustomParts("<meta property=\"twitter:card\" content=\"summary\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:site\" content=\"" + Html.Encode(Model.CurrentStoreName) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:title\" content=\"" + Html.Encode(Model.Name) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:description\" content=\"" + Html.Encode(Nop.Core.Html.HtmlHelper.StripTags(Model.MetaDescription)) + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:image\" content=\"" + Model.DefaultPictureModel.ImageUrl + "\" />");
        Html.AddHeadCustomParts("<meta property=\"twitter:url\" content=\"" + Request.Url.AbsoluteUri + "\" />");
    }

    Html.AddCssFileParts("~/Scripts/fineuploader/fineuploader-4.2.2.min.css");
    Html.AddScriptParts("~/Scripts/fineuploader/jquery.fineuploader-4.2.2.min.js");

}

@section Breadcrumb
{
    @Html.Partial("_ProductBreadcrumb", Model.Breadcrumb)
}
@Html.Widget("productdetails_after_breadcrumb", Model.Id)

        @Html.Widget("productdetails_top", Model.Id)
        @using (Html.BeginRouteForm("Product", new { SeName = Model.SeName }, FormMethod.Post, new { id = "product-details-form" }))
        {

                    @Html.Widget("productdetails_before_pictures", Model.Id)

                    @Html.Partial("_ProductDetailsPictures", Model)
                    @Html.Widget("productdetails_after_pictures", Model.Id)

                        @Html.Partial("_Discontinued", Model)

                                @Model.Name

                        @if (!String.IsNullOrEmpty(Model.ShortDescription))
                        {

                                @Html.Raw(Model.ShortDescription)

                        }
                        @Html.Widget("productdetails_overview_top", Model.Id)

                        @Html.Partial("_ProductReviewOverview", Model.ProductReviewOverview)

                        @Html.Partial("_ProductManufacturers", Model.ProductManufacturers)

                        @Html.Partial("_Availability", Model)

                        @Html.Partial("_SKU_Man_GTIN_Ven", Model)

                        @Html.Partial("_DeliveryInfo", Model)

                        @Html.Partial("_DownloadSample", Model)

                        @{
                            var dataDictAttributes = new ViewDataDictionary();
                            dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format("attributes_{0}", Model.Id);
                            @Html.Partial("_ProductAttributes", Model.ProductAttributes, dataDictAttributes)
                        }

                        @{
                            var dataDictGiftCard = new ViewDataDictionary();
                            dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format("giftcard_{0}", Model.Id);
                            @Html.Partial("_GiftCardInfo", Model.GiftCard, dataDictGiftCard)
                        }

                        @{
                            var dataDictRental = new ViewDataDictionary();
                            dataDictRental.TemplateInfo.HtmlFieldPrefix = string.Format("rental_{0}", Model.Id);
                            @Html.Partial("_RentalInfo", Model, dataDictRental)
                        }

                        @{
                            var dataDictPrice = new ViewDataDictionary();
                            dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format("price_{0}", Model.Id);
                            @Html.Partial("_ProductPrice", Model.ProductPrice, dataDictPrice)

                            @Html.Partial("_ProductTierPrices", Model.TierPrices)

                            var dataDictAddToCart = new ViewDataDictionary();
                            dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
                            @Html.Partial("_AddToCart", Model.AddToCart, dataDictAddToCart)
                        }

                            @Html.Widget("productdetails_inside_overview_buttons_before", Model.Id)
                            @{
                                var dataDictAddToWishlist = new ViewDataDictionary();
                                dataDictAddToWishlist.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
                                @Html.Partial("_AddToWishlist", Model.AddToCart, dataDictAddToWishlist)
                            }
                            @Html.Partial("_CompareProductsButton", Model)
                            @Html.Partial("_ProductEmailAFriendButton", Model)
                            @Html.Widget("productdetails_inside_overview_buttons_after", Model.Id)

                        @Html.Partial("_ShareButton", Model)
                        @Html.Widget("productdetails_overview_bottom", Model.Id)

                    @if (!String.IsNullOrEmpty(Model.FullDescription))
                    {

                            @Html.Raw(Model.FullDescription)

                    }

                @Html.Widget("productdetails_before_collateral", Model.Id)

                    @Html.Partial("_ProductSpecifications", Model.ProductSpecifications)
                    @Html.Partial("_ProductTags", Model.ProductTags)

                @Html.Action("ProductsAlsoPurchased", "Product", new { productId = Model.Id })
                @Html.Action("RelatedProducts", "Product", new { productId = Model.Id })

        }
        @Html.Widget("productdetails_bottom", Model.Id)

        @Html.Partial("Picture")

Body:
There is a known issue with nopCommerce regarding this. If your app is running under IIS Virtual Directory, Tiny MCE is likely not able to find your image.

Edit the following file:

\Administration\Views\Shared\EditorTemplates\RichEditor.cshtml

Uncomment the lines:

//allowJbimages = true;
//allowRoxyFileman = false;

To:

allowJbimages = true;
allowRoxyFileman = false;

References:
[1] https://github.com/nopSolutions/nopCommerce/issues/142
[2] https://www.nopcommerce.com/boards/t/35370/virtual-directory-not-included-in-the-images-urls.aspx


来源: stackexchange

问:
syntax error while specifying DOCTYPE
I am getting a syntax error while using the DOCTYPE  ...
actually  i have a base page and loading two iframes in it , and the doctype is specifyed in one of these iframes ..
I have some php codes before starting the html code ...

The firebug error is shown below

Thanks in advance

答:
Delete this \n and should be OK.

You can also insert ?> before DOCTYPE.

Are you have e.g. \\n instead of \n in php code?

ContentLicense: CC BY-SA 2.5

Title: syntax error while specifying DOCTYPE


问:
render video tracks of existing participants
So I connect to a room, which might already have existing participants sharing their videos. However when I try to iterate through all the participants and add their respective videos...it doesn't work. For some reason, even though the participant count is not 0.
How do I get the video tracks of all the existing participants in a room  and render them?

So basically this is the workflow:

User 1 and 2 enters room and shares their videos

User 3 enters room, and wants to show the video of the existing participants on screen(e.g. user 1 and 2 who logged in before him)
How do I do that? )

Here is my code for the didConnect() delegate which fires when one enters a room.the addVideoTrack function renders the video for any new participants, so its working fine, but I want to do it for previously existing participants.

```<code>    func didConnect(to room: TVIRoom) {
    connectedParticipants = room.participants
    for participant in connectedParticipants {

        for videoTrack in participant.videoTracks {
            addVideoTrack(videoTrack:videoTrack)
        }

    }

    changeRoomLabel(messageText: "Room: \(room.name)")
}
</code>```

答:
Twilio developer evangelist here.

When you connect to the room and find the participants, you may not have connected to their media streams yet. Instead, you should implement the TVIParticipantDelegate. As you can see in the Twilio Video quickstart application (which only handles one external participant, but is a good example), when connecting to a room set the controller as the participant's delegate:

```<code>func didConnect(to room: TVIRoom) {
    if (room.participants.count > 0) {
        self.participant = room.participants[0]
        self.participant?.delegate = self
    }
}
</code>```

Then, the example implements the TVIParticipantDelegate participant:addedVideoTrack to render the video once it is added to the participant:

```<code>extension ViewController : TVIParticipantDelegate {
    func participant(_ participant: TVIParticipant, addedVideoTrack videoTrack: TVIVideoTrack) {
        logMessage(messageText: "Participant \(participant.identity) added video track")

        if (self.participant == participant) {
            setupRemoteVideoView()
            videoTrack.addRenderer(self.remoteView!)
        }
    }
}
</code>```

And the other delegate methods here.

Let me know if that helps at all.

ContentLicense: CC BY-SA 3.0

Body:
So I connect to a room, which might already have existing participants sharing their videos. However when I try to iterate through all the participants and add their respective videos...it doesn't work. For some reason, even though the participant count is not 0.
How do I get the video tracks of all the existing participants in a room  and render them?

So basically this is the workflow:

User 1 and 2 enters room and shares their videos

User 3 enters room, and wants to show the video of the existing participants on screen(e.g. user 1 and 2 who logged in before him)
How do I do that? )

Here is my code for the didConnect() delegate which fires when one enters a room.the addVideoTrack function renders the video for any new participants, so its working fine, but I want to do it for previously existing participants.

    func didConnect(to room: TVIRoom) {
    connectedParticipants = room.participants
    for participant in connectedParticipants {

        for videoTrack in participant.videoTracks {
            addVideoTrack(videoTrack:videoTrack)
        }

    }

    changeRoomLabel(messageText: "Room: \(room.name)")
}

Body:
Twilio developer evangelist here.

When you connect to the room and find the participants, you may not have connected to their media streams yet. Instead, you should implement the TVIParticipantDelegate. As you can see in the Twilio Video quickstart application (which only handles one external participant, but is a good example), when connecting to a room set the controller as the participant's delegate:

func didConnect(to room: TVIRoom) {
    if (room.participants.count > 0) {
        self.participant = room.participants[0]
        self.participant?.delegate = self
    }
}

Then, the example implements the TVIParticipantDelegate participant:addedVideoTrack to render the video once it is added to the participant:

extension ViewController : TVIParticipantDelegate {
    func participant(_ participant: TVIParticipant, addedVideoTrack videoTrack: TVIVideoTrack) {
        logMessage(messageText: "Participant \(participant.identity) added video track")

        if (self.participant == participant) {
            setupRemoteVideoView()
            videoTrack.addRenderer(self.remoteView!)
        }
    }
}

And the other delegate methods here.

Let me know if that helps at all.


问:
Blockchain and HyperLedger Fabric difference
While I am trying to understand the blockchain technology, I came across HyperLedger Fabric. As per the documentation, it is an implementation of blockchain technology.

What does that mean? Is block chain just a concept and HyperLedger Fabric, an implementation of that concept?

UPDATED:
Where does the hyperledger fabric store the transactions? I understand that its a p2p architecture and every peer has a copy of the transactions, but usually these transactions is a growing set. Does every peer has a copy of growing transactions? I am not clear on this yet. Does the community recommend any database?

答:
Blockchain and HyperLedger Fabric difference

Blockchain is a Technology to store data ~A almost absolute permanent Database, a write once database, which cannot rewrite/edit later

HyperLedger Fabric in the other way, using Blockchain as its data storage or Database + another logic that is depend on the each framework/platform policies. Or We can call it smart contract.

Where does the hyperledger fabric store the transactions?
It store in its blackchain nodes.

Does every peer has a copy of growing transactions?
Almost every peer have a copy of all transaction histories, by design blockchain need at least 50% of the nodes to approve the transactions therefore another 50% will have a copy of the new transaction after a while.

I am not clear on this yet. Does the community recommend any database?
I am not quite sure about this question.

ContentLicense: CC BY-SA 4.0


问:
Multiple Variable Arguments to Application.OnTime
I am working on a data acquisition frontend for Excel 2010.
I can't figure out the syntax for passing multiple local variable arguments to Application.OnTime.

http://markrowlinson.co.uk/articles.php?id=10 provides a good example for a single variable as an argument, but the explanation on how to extrapolate this to multiple variables is not clear to me.

Does anyone have a concise explanation of the correct nesting of " and ' characters when passing multiple local variable arguments?

Edit: Code example would be like this: Application.OnTime Now + TimeSerial(0, 0, 5), "'runScheduledReport """ & iArg1 & "","" & iArg2 & "" "" & iArg3 & "" ""'".
I understand that we're using the double quote as an escape character within the string, but can't really figure out the ordering of the strings being passed.

答:
Just wanted to add an additional example which I found helpful, with reference to this post on MrExcel.

Application.OnTime with multiple arguments of different types (String and Integer)

```<code>Dim testName As String
Dim counter As Integer

...

' String then Integer argument
Application.OnTime Now + TimeValue("00:00:02"), "'TestSub """ & testName & """, " & counter & " '"

' Integer then String argument
Application.OnTime Now + TimeValue("00:00:02"), "'SubTest " & counter & ", """ & testName & """ '"
</code>```

The only difference from this answer is the inclusion of the counter Integer, which is handled slightly differently from a String.

Body:
Just wanted to add an additional example which I found helpful, with reference to this post on MrExcel.

Application.OnTime with multiple arguments of different types (String and Integer)

Dim testName As String
Dim counter As Integer

...

' String then Integer argument
Application.OnTime Now + TimeValue("00:00:02"), "'TestSub """ & testName & """, " & counter & " '"

' Integer then String argument
Application.OnTime Now + TimeValue("00:00:02"), "'SubTest " & counter & ", """ & testName & """ '"

The only difference from this answer is the inclusion of the counter Integer, which is handled slightly differently from a String.


问:
Where is memcached stored?
I understand memcached provides you quicker access to data that is stored in short-term memory, but whose memory is it using. Is it on the server? Is it on another database that is different than regular SQL dbs. Is it on the browser?</p>

答:
It is stored in main memory (RAM) of a machine (typically a separate m/c or a cluster of m/c with more memory - memcache server or cluster).

Memcached (the actual service of memcache) is an in-memory key-value store. The speed come from the fact that all the data is available in RAM, While a typical DB will store data in persistent storage. Also, the key-value ensures O(1) access to every data.

Hope it helps!

Title: Where is memcached stored?


问:
Is it possible to see the source code of the violating files in Hudson with Violations and Pylint?
I'm using Hudson CI with a Python project. I've installed the Violations plugin and configured it to run the code against pylint. This works, but I only see a list of violations without linking to the source code. Is it possible to setup Violations and pylint to load and highlight the violating source files (something similar to the Cobertura Coverage Reports)?

Better yet, can Violations integrate with pep8.py?

答:
I ran into a similar problem with pylint and violations. For me, the problem was that pylint writes absolute file names to the results file, while the violations plugin expects paths relative to the workspace directory. Running this sed one-liner on the pylint output file fixed my problem:

sed -i s#.*workspace/## pylint-hudson.txt

I also filed a bug against Hudson.


问:
Variation of indices of an array or matrix
If I use this syntax:

```<code>mX=[1:5];
A=rand(5,1);
C(mX)=sum(A(1:mX));
</code>```

Why doesn't the content of C(mX) vary with varying mX?

Instead of doing

```<code>C(1)=A(1)
C(2)=A(1)+A(2), etc
</code>```

it does:

```<code>C(1)=A(1)
C(2)=A(1)
C(3)=A(1), etc
</code>```

Is there any way to vary C(mX) without resorting to a loop?

答:
You can do this by cumsum like so:

```<code>mX=[1:5];
A=rand(5,1);
C = cumsum(A(mX));
</code>```

Body:
If I use this syntax:

mX=[1:5];
A=rand(5,1);
C(mX)=sum(A(1:mX));

Why doesn't the content of C(mX) vary with varying mX?

Instead of doing

C(1)=A(1)
C(2)=A(1)+A(2), etc

it does:

C(1)=A(1)
C(2)=A(1)
C(3)=A(1), etc

Is there any way to vary C(mX) without resorting to a loop?

Body:
You can do this by cumsum like so:

mX=[1:5];
A=rand(5,1);
C = cumsum(A(mX));


问:
Replace columns from a lookup table value
I have two tables, one with values and another with lookup values. I want to replace table 1 with values from table 2 but haven't found an elegant way of doing this.

Table 1 (main)

```<code>name       age       country       last_visited
 x1        a1          UK            2016
 x2        a3          US            2017
 x3        a1          China         2015
</code>```

Table 2 (lookup)

```<code>code      value    date_updated
 x1        Dom       2017
 a1        25        2017
 x2        Peter     2017
 x3        Alice     2017
 a3        26        2017
</code>```

Final Table (What I want)

```<code>name       age       country       last_visited
 Dom       25          UK            2016
 Peter     26          US            2017
 Alice     25          China         2015
</code>```

I have tried joining table 1 to table 2 but then this involved me later replacing / dropping columns and I have to do this individually for each column. I have only given a small portion of columns where i have lookup values above but in reality I have about 8 columns that contain lookup values in the same table. How do I achieve this?

```<code> val unsanitised_data = table1.join(table2, table1.col("name") === table2.col("code"), "left").drop("last_visited", "name", "code")
</code>```

Now I need to rename "value" to name and do the same thing for age and other columns again. Is this the best way to do this?

答:
A simple join and select functions should solve your issue

```<code>df1.join(df2, df1("name")=== df2("code"), "left").select($"value".as("name"), $"age", $"country", $"last_visited")
  .join(df2,df1("age")=== df2("code"), "left").select($"name", $"value".as("age"), $"country", $"last_visited")
  .show(false)
</code>```

Edited

If you have too many columns and doesn't need columns of second table then you can do

```<code>df1.join(df2, df1("name")=== df2("code"), "left").withColumn("name", col("value")).drop(df2.columns: _*)
  .join(df2,df1("age")=== df2("code"), "left").withColumn("age", col("value")).drop(df2.columns: _*)
  .show(false)
</code>```

Body:
I have two tables, one with values and another with lookup values. I want to replace table 1 with values from table 2 but haven't found an elegant way of doing this.

Table 1 (main)

name       age       country       last_visited
 x1        a1          UK            2016
 x2        a3          US            2017
 x3        a1          China         2015

Table 2 (lookup)

code      value    date_updated
 x1        Dom       2017
 a1        25        2017
 x2        Peter     2017
 x3        Alice     2017
 a3        26        2017

Final Table (What I want)

name       age       country       last_visited
 Dom       25          UK            2016
 Peter     26          US            2017
 Alice     25          China         2015

I have tried joining table 1 to table 2 but then this involved me later replacing / dropping columns and I have to do this individually for each column. I have only given a small portion of columns where i have lookup values above but in reality I have about 8 columns that contain lookup values in the same table. How do I achieve this?

 val unsanitised_data = table1.join(table2, table1.col("name") === table2.col("code"), "left").drop("last_visited", "name", "code")

Now I need to rename "value" to name and do the same thing for age and other columns again. Is this the best way to do this?

Body:
A simple join and select functions should solve your issue

df1.join(df2, df1("name")=== df2("code"), "left").select($"value".as("name"), $"age", $"country", $"last_visited")
  .join(df2,df1("age")=== df2("code"), "left").select($"name", $"value".as("age"), $"country", $"last_visited")
  .show(false)

Edited

If you have too many columns and doesn't need columns of second table then you can do

df1.join(df2, df1("name")=== df2("code"), "left").withColumn("name", col("value")).drop(df2.columns: _*)
  .join(df2,df1("age")=== df2("code"), "left").withColumn("age", col("value")).drop(df2.columns: _*)
  .show(false)


问:
Automation testing using wd library
I am working with wd library for automation testing that includes mocha as well.

Here is my code

```<code>require('colors');
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
chai.should();

var header = require('../pages/header.js');

var wd;
try {
  wd = require('wd');
} catch( err ) {
  wd = require('../../lib/main');
}
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

describe('mocha spec examples', function() {
  this.timeout(10000);

  // returning promises and chai-as-promised is the best way
  describe("using promises and chai-as-promised", function() {
    var browser;

    before(function() {
      browser = wd.promiseChainRemote();
      return browser
        .init({browserName:'chrome'})

        .setWindowSize(1366, 1024, function(err){
       });
    });

    beforeEach(function() {
      return browser.get("http://admc.io/wd/test-pages/guinea-pig.html");
     // return browser.get("http://google.com.au");
    });

    after(function() {
    });

it("Validate the Location of Header image", function() {

         return console.log(browser.elementByClassName('i_am_a_class')
                .parentElement.getAttribute("outerHTML"));
                //.getAttribute("outerHTML")
                //.then(console.log.bind(console));
    });

  });
});
</code>```

I am able to get the element by class name, but I need to get the parent element of the element found as well.

答:
You need XPath and use /.. to get parent.

```<code>it("Validate the Location of Header image", function() {
    return console.log(browser.elementByXpath('//*[@class="i_am_a_class"]/..').getAttribute("outerHTML"));
</code>```

Title: Automation testing using wd library

Body:
I am working with wd library for automation testing that includes mocha as well.

Here is my code

require('colors');
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
chai.should();

var header = require('../pages/header.js');

var wd;
try {
  wd = require('wd');
} catch( err ) {
  wd = require('../../lib/main');
}
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

describe('mocha spec examples', function() {
  this.timeout(10000);

  // returning promises and chai-as-promised is the best way
  describe("using promises and chai-as-promised", function() {
    var browser;

    before(function() {
      browser = wd.promiseChainRemote();
      return browser
        .init({browserName:'chrome'})

        .setWindowSize(1366, 1024, function(err){
       });
    });

    beforeEach(function() {
      return browser.get("http://admc.io/wd/test-pages/guinea-pig.html");
     // return browser.get("http://google.com.au");
    });

    after(function() {
    });

it("Validate the Location of Header image", function() {

         return console.log(browser.elementByClassName('i_am_a_class')
                .parentElement.getAttribute("outerHTML"));
                //.getAttribute("outerHTML")
                //.then(console.log.bind(console));
    });

  });
});

I am able to get the element by class name, but I need to get the parent element of the element found as well.

Body:
You need XPath and use /.. to get parent.

it("Validate the Location of Header image", function() {
    return console.log(browser.elementByXpath('//*[@class="i_am_a_class"]/..').getAttribute("outerHTML"));


问:
Regular Expressions - Exclude characters
I am trying to use regulare expressions with a formvalidator.net to validate a form but I am struggling to under stand regular expressions,I have had a look at some websites but it is still baffling.

Basically I want to validate a field so that when a user enter something it will chack that the word or entry doesnt contain certain characters. So for example I don't want '!name' or 'this ! name' to be accepted.

using regexp for testing I have created this expression ([a-zA-Z\+\&\,\.\-\(\)\d][^<>%$!]+) which excludes those characters but in my form validator it will still accept '!name' or 'this ! name'

Can anyone point me in the right direction? I feel like I'm typing stuff in and gettign nowhere.

Ian

答:
Basically I think you want to either decide what characters you don't want OR what characters you do. Not both.

I think this is what your after:

```<code>^[^<>%$!]+$
</code>```

See it working here

Body:
Basically I think you want to either decide what characters you don't want OR what characters you do. Not both.

I think this is what your after:

^[^<>%$!]+$

See it working here


问:
Is filterrific still being worked on?
I'm trying to get a PR reviewed and it's going nowhere. I'm asking on SO to see if anybody here might know, is Filterrific still being worked on? There are a few PR's, lots of issues, and the author has yet to respond.</p>

答:
I am using filterrific gem myself. I have also experienced bad respond on issues & seems like the author is not so active himself.

Gem authors are also not obligated to give support but if they do its always a plus.

But to be fare author himself has used a lot of times to create good documents. At first when I was setting up the gem, I also had issue but if you read his documents carefully (read here), you will understand the most.

I also recommend you to take a look at his demo app source code (found here)

By looking at the codes you will always set together stuff to create your own scope.

You can also follow all questions related to filterrific gem on SO (here)

Title: Is filterrific still being worked on?


问:
How to make UIImagePickerController StatusBar lightContent style?

When I present the ImagePickerController the statusBar text color is still black, how to make like this?

答:
Using the answers above the following worked for me:

Implement
UINavigationControllerDelegate, UIImagePickerControllerDelegate to your UIViewController
and set

```<code>imagePickerController.delegate = self;
</code>```

Add the following method:

```<code>-(void) navigationController: (UINavigationController *) navigationController willShowViewController: (UIViewController *) viewController animated: (BOOL) animated {
    navigationController.navigationBar.barStyle = UIBarStyleBlack;
}
</code>```

Body:
Using the answers above the following worked for me:

Implement
UINavigationControllerDelegate, UIImagePickerControllerDelegate to your UIViewController
and set

imagePickerController.delegate = self;

Add the following method:

-(void) navigationController: (UINavigationController *) navigationController willShowViewController: (UIViewController *) viewController animated: (BOOL) animated {
    navigationController.navigationBar.barStyle = UIBarStyleBlack;
}


问:
Collapse all methods in Visual Studio Code
In Visual Studio Professional, we have a shortcut key, Ctrl + M Ctrl  + O to collapse all methods and properties in a class. How can I do a similar thing in Visual Studio Code?

I know there are shortcut keys like Ctrl + Shift + [, but this does not meet the needs.

Is it possible to get the Visual Studio Professional-like behaviour in Visual Studio Code?

答:
The beauty of Visual Studio Code is

Ctrl + Shift + P

Hit it and search anything you want.

In your case, hit Ctrl + Shift + P and type fold all.


问:
JQuery wrong ID in an inner click
I'm trying to make a colorpicker. Where you got a few colorcubes with the class colorcube.
When clicking, it opens a colorpicker with a few list items who all have a different color.
When clicking on a list items it should return de color/text to de colorcube.

The first colorpick after the document is ready works. But after that it doesnt work properly, because it remembers al the previous colorcube ID's so al the other cube's will also change :(

Is there a way to clear cache or something like that?

```<code>$('.colorcube').click(function() {
    var colorcubeid = $(this).attr("id");
    $('#choicecolor').show();

    $(".li_color").click(function() {
        var colorid = "#" + this.id;
        var colorli = $(colorid).text();
        $('#' + colorcubeid).text(colorli);
        $('#' + colorcubeid).css({ 'background-color': '' + colorli + '' });
        $('#choicecolor').hide();
        savecolor();
    });

});
</code>```

答:
I am trying to untangle why you need the nested click functions. Seems like you should be able to un-nest them. You may have to add a bit of jquery to get the 'colorcubeid' in the second function.

I believe what is happening is that the 'colorcubeid' variable is in the scope of the inner click function and is never being updated.

Bob

Title: JQuery wrong ID in an inner click

Body:
I'm trying to make a colorpicker. Where you got a few colorcubes with the class colorcube.
When clicking, it opens a colorpicker with a few list items who all have a different color.
When clicking on a list items it should return de color/text to de colorcube.

The first colorpick after the document is ready works. But after that it doesnt work properly, because it remembers al the previous colorcube ID's so al the other cube's will also change :(

Is there a way to clear cache or something like that?

$('.colorcube').click(function() {
    var colorcubeid = $(this).attr("id");
    $('#choicecolor').show();

    $(".li_color").click(function() {
        var colorid = "#" + this.id;
        var colorli = $(colorid).text();
        $('#' + colorcubeid).text(colorli);
        $('#' + colorcubeid).css({ 'background-color': '' + colorli + '' });
        $('#choicecolor').hide();
        savecolor();
    });

});


问:
Apache's StringUtils.isBlank(str) vs. Guava's Strings.isNullOrEmpty(str): Should you routinely check for whitespace?
Is there any advantage in using

```<code>StringUtils.isBlank(str)
</code>```

from Apache commons-lang.

vs

```<code>Strings.isNullOrEmpty(String string)
</code>```

from Google Guava?

I want to replace hundreds of cases of they following usage in a Java project:

```<code>if(str == null || str.isEmpty())
</code>```

Guava's isNullOrEmpty seems to be a direct replacement for the usage above in my project.

But more people seem to use Apache's isBlank method based on my reading of S.O. questions.

The only difference seems to be that StringUtils.isBlank(str) also checks for whitespace in addition to checking whether the string is null or empty.

Normally is it a good idea to check a String for whitespace or could that produce a different result in your code than Guava's simpler check?

答:
StringUtils.isBlank(str) is very much different than Strings.isNullOrEmpty(String string)

the first code sample will only check if the string is empty or not, it will include white spaces as well and return true

```<code>StringUtils.isBlank(null)      = true
StringUtils.isBlank("")         = true
StringUtils.isBlank(" ")        = true
StringUtils.isBlank("bob")      = false
StringUtils.isBlank("  bob  ")  = false
</code>```

where as Strings.isNullOrEmpty(String string) Returns true if the given string is null or is the empty string

Body:
Is there any advantage in using

StringUtils.isBlank(str)

from Apache commons-lang.

vs

Strings.isNullOrEmpty(String string)

from Google Guava?

I want to replace hundreds of cases of they following usage in a Java project:

if(str == null || str.isEmpty())

Guava's isNullOrEmpty seems to be a direct replacement for the usage above in my project.

But more people seem to use Apache's isBlank method based on my reading of S.O. questions.

The only difference seems to be that StringUtils.isBlank(str) also checks for whitespace in addition to checking whether the string is null or empty.

Normally is it a good idea to check a String for whitespace or could that produce a different result in your code than Guava's simpler check?

Body:
StringUtils.isBlank(str) is very much different than Strings.isNullOrEmpty(String string)

the first code sample will only check if the string is empty or not, it will include white spaces as well and return true

StringUtils.isBlank(null)      = true
StringUtils.isBlank("")         = true
StringUtils.isBlank(" ")        = true
StringUtils.isBlank("bob")      = false
StringUtils.isBlank("  bob  ")  = false

where as Strings.isNullOrEmpty(String string) Returns true if the given string is null or is the empty string


Title: How to assemble two different array in one array of php

Body:
$arr1 = Array ( [0] => 5 [days] => 5 )
        Array ( [0] => 6 [days] => 6 )
        Array ( [0] => 7 [days] => 7 )
        Array ( [0] => 8 [days] => 8 )
        Array ( [0] => 9 [days] => 9 )
        Array ( [0] => 10 [days] => 10 )
        Array ( [0] => 11 [days] => 11 )
        Array ( [0] => 12 [days] => 12 )
        Array ( [0] => 13 [days] => 13 )
        Array ( [0] => 14 [days] => 14 )
        Array ( [0] => 15 [days] => 15 )
        Array ( [0] => 16 [days] => 16 )
        Array ( [0] => 17 [days] => 17 )
        Array ( [0] => 18 [days] => 18 )
        Array ( [0] => 19 [days] => 19 )
        Array ( [0] => 20 [days] => 20 )
        Array ( [0] => 21 [days] => 21 )
        Array ( [0] => 22 [days] => 22 )
        Array ( [0] => 23 [days] => 23 )
        Array ( [0] => 24 [days] => 24 )
        Array ( [0] => 25 [days] => 25 )
        Array ( [0] => 26 [days] => 26 )
        Array ( [0] => 27 [days] => 27 )
        Array ( [0] => 28 [days] => 28 )
        Array ( [0] => 29 [days] => 29 )
        Array ( [0] => 30 [days] => 30 )
        Array ( [0] => 31 [days] => 31 );

$arr2 = Array ( [0] => 1 [day] => 1
                [1] => 1 [days] => 1 )
        Array ( [0] => 2 [day] => 2 [1] => 2 [days] => 2 ) Array ( [0] => 3 [day] => 3 [1] => 3 [days] => 3 ) Array ( [0] => 4 [day] => 4 [1] => 4 [days] => 4 );

i want to ascending-ly marge $arr1 and $arr2 and the output i expect

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31

help me How can i do like that?

Body:
try this code

<?php
$arr1 = Array(0=>Array ( 0 => 5 ,'days' => 5 ) ,
        1=>Array ( 0 => 6 ,'days' => 6 ),
        2=>Array ( 0 => 7 ,'days' => 7 ),
        3=>Array ( 0 => 8 ,'days' => 8 ),
        4=>Array ( 0 => 9, 'days' => 9 ),
        5=>Array ( 0 => 10, 'days' => 10 ),
        6=>Array ( 0 => 11, 'days' => 11 ),
        7=>Array ( 0 => 12, 'days' => 12 ),
        8=>Array ( 0 => 13, 'days' => 13 ),
        9=>Array ( 0 => 14, 'days' => 14 ),
        10=>Array ( 0 => 15, 'days' => 15 ),
        11=>Array ( 0 => 16, 'days' => 16 ),
        12=>Array ( 0 => 17, 'days' => 17 ),
        13=>Array ( 0 => 18, 'days' => 18 ),
        14=>Array ( 0 => 19, 'days' => 19 ),
        15=>Array ( 0 => 20, 'days' => 20 ),
        16=>Array ( 0 => 21, 'days' => 21 ),
        17=>Array ( 0 => 22, 'days' => 22 ),
        18=>Array ( 0 => 23, 'days' => 23 ),
        19=>Array ( 0 => 24, 'days' => 24 ),
        20=>Array ( 0 => 25, 'days' => 25 ),
        21=>Array ( 0 => 26, 'days' => 26 ),
        22=>Array ( 0 => 27, 'days' => 27 ),
        23=>Array ( 0 => 28, 'days' => 28 ),
        24=>Array ( 0 => 29, 'days' => 29 ),
        25=>Array ( 0 => 30, 'days' => 30 ),
        26=>Array ( 0 => 31 ,'days' => 31 ));

$arr2 = Array(0=>Array( 0 => 1, 'day' => 1, 1 => 1, 'days' => 1 ) ,
    1=> Array ( 0 => 2, 'day' => 2, 1 => 2, 'days' => 2 ) ,
    3=>Array ( 0 => 3, 'day' => 3, 1 => 3 ,'days' => 3 ) ,
    4=>Array ( 0 => 4 ,'day' => 4, 1 => 4 ,'days' => 4 ));

foreach ($arr2 as $key => $value) {
            $arr2[$key]=array_unique($value);
}
foreach ($arr1 as $key => $value) {
        $arr1[$key]=array_unique($value);
}
$new=array_merge($arr2,$arr1);
foreach ($new as $key => $value) {
    foreach ($value as $key1 => $value1) {
        echo $value[0].",";
    }
}
?>


问:
What's the right way to add haml to a rails application?
While looking for a way to add haml as the templating engine to my rails app I came upon two distinct ways to do it.

The first one is to just add 'gem "haml-rails"' to the Gemfile.

The second one is to add this code to config/application.rb:

```<code>config.generators do |g|
  g.template_engine :haml
end
</code>```

Is there a reason to prefer one over the other?

答:
You add your gems into the Gemfile in order to specify external dependencies.

Without adding haml to your Gemfile, Bundler will not know about it and your Haml templates won't render on machines that do not have haml installed.

Just follow the instructions of the documentation... http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#plugin

Or is there a reason to deviate from the recommended way?

Body:
While looking for a way to add haml as the templating engine to my rails app I came upon two distinct ways to do it.

The first one is to just add 'gem "haml-rails"' to the Gemfile.

The second one is to add this code to config/application.rb:

config.generators do |g|
  g.template_engine :haml
end

Is there a reason to prefer one over the other?


问:
React native: which navigator is more flexible?
I'm considering a navigator for a new react-native project

I think the best 2 options are react navigation and react native navigation

Which one is more flexible in terms of defining custom navbars (for example a  toggle searchbar) and overriding the default back button handler (for example: to prompt a 'save changes?' warning)?

答:
I would say react-navigation is a better choice, in terms of its flexible api.

Also check out this post from Eric Vicenti, if you are trying to choose the way to go in terms of navigation and navigation animations;

https://medium.com/@ericvicenti/playing-with-react-navigation-and-airbnbs-native-navigation-4e49fc765489


问:
Product Variation is not showing on the cart page
After updating WooCommerce 2.6.4 into WooCommerce 3.0.+, some of the product variations are not showing on the cart page. But some product variation is showing on the cart page. My WordPress version is 4.7.5 and WooCommerce version is 3.0.7.

How to solve this problem?

答:
Override the cart.php in your child theme.. Issue must be the old cart.php template on your child theme.

replace this

```
if (!$_product->is_visible()) {
echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' ';
} else {
echo apply_filters( 'woocommerce_cart_item_name', sprintf( '%s', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key );
}

// Meta data
echo WC()->cart->get_item_data($cart_item);

// Backorder notification
if ($_product->backorders_require_notification() && $_product->is_on_backorder($cart_item['quantity'])) {
echo '' . esc_html__('Available on backorder', 'woocommerce') . '</p>';
}
```

Body:
Override the cart.php in your child theme.. Issue must be the old cart.php template on your child theme.

replace this

if (!$_product->is_visible()) {
echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' ';
} else {
echo apply_filters( 'woocommerce_cart_item_name', sprintf( '%s', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key );
}

// Meta data
echo WC()->cart->get_item_data($cart_item);

// Backorder notification
if ($_product->backorders_require_notification() && $_product->is_on_backorder($cart_item['quantity'])) {
echo '' . esc_html__('Available on backorder', 'woocommerce') . '
';
}


Title: Compare two dataframes and delete not same dates

Body:
I have two dataframes and want to compare them and delete the days in the df2 which are not the same as in df1. I tried to use:

df2[~df2.Date.isin(df1.Date)]

but this does not work and getting an empty dataframe. df2 should look like df1. The dataframe's looks like the following:

df1
        Date
0    20-12-16
1    21-12-16
2    22-12-16
3    23-12-16
4    27-12-16
5    28-12-16
6    29-12-16
7    30-12-16
8    02-01-17
9    03-01-17
10   04-01-17
11   05-01-17
12   06-01-17

df2

         Date
0    20-12-16
1    21-12-16
2    22-12-16
3    23-12-16
4    24-12-16
5    25-12-16
6    26-12-16
7    27-12-16
8    28-12-16
9    29-12-16
10   30-12-16
11   31-12-16
12   01-01-17
13   02-01-17
14   03-01-17
15   04-01-17
16   05-01-17
17   06-01-17

Body:
It seems dtypes are different. For comparing need same.

Check it by:

print (df1.Date.dtype)
print (df2.Date.dtype)

and then convert if necessary:

df1['Date'] = pd.to_datetime(df1['Date'])
df2['Date'] = pd.to_datetime(df2['Date'])

I add another 2 solutions - first with numpy.in1d and second with merge, because need default inner join:

 df = df2[np.in1d(df2.Date, df1.Date)]
print (df)
         Date
0  2016-12-20
1  2016-12-21
2  2016-12-22
3  2016-12-23
7  2016-12-27
8  2016-12-28
9  2016-12-29
10 2016-12-30
13 2017-01-02
14 2017-01-03
15 2017-01-04
16 2017-01-05
17 2017-01-06

df = df1.merge(df2, on='Date')
print (df)
         Date
0  2016-12-20
1  2016-12-21
2  2016-12-22
3  2016-12-23
7  2016-12-27
8  2016-12-28
9  2016-12-29
10 2016-12-30
13 2017-01-02
14 2017-01-03
15 2017-01-04
16 2017-01-05
17 2017-01-06

Sample:

d1 = {'Date': ['20-12-16', '21-12-16', '22-12-16', '23-12-16', '27-12-16', '28-12-16', '29-12-16', '30-12-16', '02-01-17', '03-01-17', '04-01-17', '05-01-17', '06-01-17']}
d2 = {'Date': ['20-12-16', '21-12-16', '22-12-16', '23-12-16', '24-12-16', '25-12-16', '26-12-16', '27-12-16', '28-12-16', '29-12-16', '30-12-16', '31-12-16', '01-01-17', '02-01-17', '03-01-17', '04-01-17', '05-01-17', '06-01-17']}
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

print (df1.Date.dtype)
object

print (df2.Date.dtype)
object

df1['Date'] = pd.to_datetime(df1['Date'], format='%d-%m-%y')
df2['Date'] = pd.to_datetime(df2['Date'], format='%d-%m-%y')


问:
How to add a collections of parameters to an SqlCommand before query execution in C#?
I have this code where I want to add a collections of Parameters to an SqlCommand.

```<code>public void AddParameters(Dictionary<string, object> parameters)
{
    if (parameters == null)
        return;

    foreach(KeyValuePair<string, object> keyValue in parameters)
    {
        sqlCommand.Parameters.AddWithValue(keyValue.Key, keyValue.Value);
    }
}
</code>```

I want to make it more efficienty without using a loop because I can have a very large collection of parameters. Is there any way to add the entire collection with a single function?

答:
I don't like several things

why you need a public method to add parameters to a private SqlCommand which should not be a field at all but which should be created where you are using it. This is too error-prone.

You are optimizing wrong things. Don't care about micro seconds but code safety. Using AddWithValue isn't safe and can cause performance(or other) problems because the type of the parameter must be derived from the value

If at all you could use such a method but with little benefit:

```<code>void AddParameters(params SqlParameter[] parameters)
{
    if (parameters == null || parameters.Length == 0)
        return;

    sqlCommand.Parameters.AddRange(parameters);
}
</code>```

The params keyword allows to use it in this way:

```<code>SqlParameter pararmeter = new SqlParameter("@Column", SqlDbType.Int);
pararmeter.Value = 1234;
AddParameters(pararmeter);
</code>```

Body:
I have this code where I want to add a collections of Parameters to an SqlCommand.

public void AddParameters(Dictionary<string, object> parameters)
{
    if (parameters == null)
        return;

    foreach(KeyValuePair<string, object> keyValue in parameters)
    {
        sqlCommand.Parameters.AddWithValue(keyValue.Key, keyValue.Value);
    }
}

I want to make it more efficienty without using a loop because I can have a very large collection of parameters. Is there any way to add the entire collection with a single function?

Body:
I don't like several things

why you need a public method to add parameters to a private SqlCommand which should not be a field at all but which should be created where you are using it. This is too error-prone.

You are optimizing wrong things. Don't care about micro seconds but code safety. Using AddWithValue isn't safe and can cause performance(or other) problems because the type of the parameter must be derived from the value

If at all you could use such a method but with little benefit:

void AddParameters(params SqlParameter[] parameters)
{
    if (parameters == null || parameters.Length == 0)
        return;

    sqlCommand.Parameters.AddRange(parameters);
}

The params keyword allows to use it in this way:

SqlParameter pararmeter = new SqlParameter("@Column", SqlDbType.Int);
pararmeter.Value = 1234;
AddParameters(pararmeter);


问:
How to get indices of top N values of an array in C
I got the c-code from following link

How to get the indices of top N values of an array?

I have added input stimulus part to the above link code and developed the following c-model

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
  double *arr =malloc(sizeof(double)*10);
  int N=10;
  int n =5;
  int *top =malloc(sizeof(int)*10);
  arr[0] = 0.00623;
  arr[1] = 0.745;
  arr[2] = 0.440;
  arr[3] = 0.145;
  arr[4] = 0.645;
  arr[5] = 0.741;
  arr[6] = 0.542;
  arr[7] = 0.445;
  arr[8] = 0.146;
  arr[9] = 0.095;
  top[0] = 100;
  top[1] = 100;
  top[2] = 100;
  top[3] = 100;
  top[4] = 100;
  int top_count = 0;
  int i;
  for (i=0;i<N;++i) {

    // invariant: arr[top[0]] >= arr[top[1]] >= .... >= arr[top[top_count-1]]
    // are the indices of the top_count larger values in arr[0],...,arr[i-1]
    // top_count = max(i,n);
    int k;

    for (k=top_count;k>0 && arr[i]>arr[top[k-1]];k--){

    }
    // i should be inserted in position k

    if (k>=n) continue; // element arr[i] is not in the top n
    // shift elements from k to top_count
    int j=top_count;
    if (j>n-1) { // top array is already full
      j=n-1;

    } else { // increase top array
      top_count++;
    }

    for (;j>k;j--) {
      top[j]=top[j-1];
    }
    // insert i
    top[k] = i;
    printf("top[%0d] = %0d\n",k,top[k]);

  }
  return top_count;
}
</code>```

After executing the code, I am getting following output

```<code>top[0] = 0
top[0] = 1
top[1] = 2
top[2] = 3
top[1] = 4
top[1] = 5
top[3] = 6
top[4] = 7
</code>```

The index is wrong for top[2]. It should be top[2] =4. I am not able to decode why it is giving problem for only top[2]?

答:
This is just a matter of output...

You output your latestly inserted values right while yet sorting. You get output top[2] = 2 somewhere in your process, but later on, you shift the 2 out of the array by inserting new values before:

```<code>for (;j > k; j--)
{
    top[j] = top[j-1]; // moves the 2 out with further iterations!
}
</code>```

What you have to do is output the sorted array afterwards:

```<code>} // for (i = 0; i < N; ++i)

// sorting finished now, so NOW output:

for (i = 0; i < n; ++i)
{
    printf("top[%0d] = %0d (%f)\n", i, top[i], arr[top[i]]);
}
</code>```

And you'll see that your sorting actually worked as a charm...

Body:
I got the c-code from following link

How to get the indices of top N values of an array?

I have added input stimulus part to the above link code and developed the following c-model

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
  double *arr =malloc(sizeof(double)*10);
  int N=10;
  int n =5;
  int *top =malloc(sizeof(int)*10);
  arr[0] = 0.00623;
  arr[1] = 0.745;
  arr[2] = 0.440;
  arr[3] = 0.145;
  arr[4] = 0.645;
  arr[5] = 0.741;
  arr[6] = 0.542;
  arr[7] = 0.445;
  arr[8] = 0.146;
  arr[9] = 0.095;
  top[0] = 100;
  top[1] = 100;
  top[2] = 100;
  top[3] = 100;
  top[4] = 100;
  int top_count = 0;
  int i;
  for (i=0;i<N;++i) {

    // invariant: arr[top[0]] >= arr[top[1]] >= .... >= arr[top[top_count-1]]
    // are the indices of the top_count larger values in arr[0],...,arr[i-1]
    // top_count = max(i,n);
    int k;

    for (k=top_count;k>0 && arr[i]>arr[top[k-1]];k--){

    }
    // i should be inserted in position k

    if (k>=n) continue; // element arr[i] is not in the top n
    // shift elements from k to top_count
    int j=top_count;
    if (j>n-1) { // top array is already full
      j=n-1;

    } else { // increase top array
      top_count++;
    }

    for (;j>k;j--) {
      top[j]=top[j-1];
    }
    // insert i
    top[k] = i;
    printf("top[%0d] = %0d\n",k,top[k]);

  }
  return top_count;
}

After executing the code, I am getting following output

top[0] = 0
top[0] = 1
top[1] = 2
top[2] = 3
top[1] = 4
top[1] = 5
top[3] = 6
top[4] = 7

The index is wrong for top[2]. It should be top[2] =4. I am not able to decode why it is giving problem for only top[2]?

Body:
This is just a matter of output...

You output your latestly inserted values right while yet sorting. You get output top[2] = 2 somewhere in your process, but later on, you shift the 2 out of the array by inserting new values before:

for (;j > k; j--)
{
    top[j] = top[j-1]; // moves the 2 out with further iterations!
}

What you have to do is output the sorted array afterwards:

} // for (i = 0; i < N; ++i)

// sorting finished now, so NOW output:

for (i = 0; i < n; ++i)
{
    printf("top[%0d] = %0d (%f)\n", i, top[i], arr[top[i]]);
}

And you'll see that your sorting actually worked as a charm...


问:
How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'
I'm using Bootstrap V4 and the following error is logged in the console;

Error: Bootstrap tooltips require Tether
  (http://github.hubspot.com/tether/)

I have tried to remove the error by installing Tether but it hasn't worked. I have 'installed' Tether by including the following lines of code;

```<code><link rel="stylesheet" href="http://www.atlasestateagents.co.uk/css/tether.min.css">
<script src="http://www.atlasestateagents.co.uk/javascript/tether.min.js"></script>
</code>```

Have I 'installed' tether correctly?

Can anyone help me remove this error?

If you wish to view the error on my site, please click here and load your console.

答:
If you use require.js AMD loader:</p>

```<code>// path config
requirejs.config({
  paths: {
    jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js',
    tether: '//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min',
    bootstrap: '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min',
  },
  shim: {
    bootstrap: {
      deps: ['jquery']
    }
  }
});

//async loading
requirejs(['tether'], function (Tether) {
  window.Tether = Tether;
  requirejs(['bootstrap']);
});
</code>```

Body:
I'm using Bootstrap V4 and the following error is logged in the console;

Error: Bootstrap tooltips require Tether
  (http://github.hubspot.com/tether/)

I have tried to remove the error by installing Tether but it hasn't worked. I have 'installed' Tether by including the following lines of code;

<link rel="stylesheet" href="http://www.atlasestateagents.co.uk/css/tether.min.css">

Have I 'installed' tether correctly?

Can anyone help me remove this error?

If you wish to view the error on my site, please click here and load your console.

Body:
If you use require.js AMD loader:

// path config
requirejs.config({
  paths: {
    jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js',
    tether: '//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min',
    bootstrap: '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min',
  },
  shim: {
    bootstrap: {
      deps: ['jquery']
    }
  }
});

//async loading
requirejs(['tether'], function (Tether) {
  window.Tether = Tether;
  requirejs(['bootstrap']);
});


问:
Get the rows from previous month
I am trying this query

```<code>SELECT *
FROM flexible_products
WHERE YEAR(updated_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
AND MONTH(updated_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
</code>```

for my current work. What I want to do is to get all rows from the previous month,

Like for example, we have today July 04, 2017, I would like to get rows from January to June, which is not the outcome of the above query.

What is the best way to this in MySQL?

答:
The following query will return all records updated on or after January 1 of the current year but stictly before the first of the current month.

```<code>SELECT *
FROM flexible_products
WHERE updated_at >= DATE_FORMAT(NOW(), '%Y') AND
      updated_at < DATE_FORMAT(NOW() ,'%Y-%m-01')
</code>```

Follow the link below for a running demo:

Rextester

Title: Get the rows from previous month

Body:
I am trying this query

SELECT *
FROM flexible_products
WHERE YEAR(updated_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
AND MONTH(updated_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))

for my current work. What I want to do is to get all rows from the previous month,

Like for example, we have today July 04, 2017, I would like to get rows from January to June, which is not the outcome of the above query.

What is the best way to this in MySQL?

Body:
The following query will return all records updated on or after January 1 of the current year but stictly before the first of the current month.

SELECT *
FROM flexible_products
WHERE updated_at >= DATE_FORMAT(NOW(), '%Y') AND
      updated_at < DATE_FORMAT(NOW() ,'%Y-%m-01')

Follow the link below for a running demo:

Rextester


问:
Tensorflow textsum error of Versioning
I am trying to convert the training text file to bin file for training the textsum of tensorflow. But I encountered the following error:

```<code>$ python textsum/data_convert_example.py --command text_to_binary --in_file data/tt.txt --out_file data/bin_data_train
Traceback (most recent call last):
  File "textsum/data_convert_example.py", line 12, in <module>
    import tensorflow as tf
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 104, in <module>
    from tensorflow.python.platform import test
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/test.py", line 57, in <module>
    import mock                # pylint: disable=g-import-not-at-top,unused-import
  File "/usr/local/lib/python2.7/dist-packages/mock/__init__.py", line 2, in <module>
    import mock.mock as _mock
  File "/usr/local/lib/python2.7/dist-packages/mock/mock.py", line 71, in <module>
    _v = VersionInfo('mock').semantic_version()
  File "/usr/local/lib/python2.7/dist-packages/pbr/version.py", line 461, in semantic_version
    self._semantic = self._get_version_from_pkg_resources()
  File "/usr/local/lib/python2.7/dist-packages/pbr/version.py", line 448, in _get_version_from_pkg_resources
    result_string = packaging.get_version(self.package)
  File "/usr/local/lib/python2.7/dist-packages/pbr/packaging.py", line 755, in get_version
    name=package_name))
Exception: Versioning for this project requires either an sdist tarball, or access to an upstream git repository. It's also possible that there is a mismatch between the package name in setup.cfg and the argument given to pbr.version.VersionInfo. Project name mock was given, but was not able to be found.
</code>```

Kindly help me. I am using tensorflow 1.2.0 with python 2.7.2.

答:
You must have a problem with your install.

Please try the following commands:

pip install --upgrade mock
pip install --upgrade distribute

If it does not work, you should give us more details about how you installed tensorflow (pip? conda? clone & setup.py?) and try to reinstall from scratch.

Hope it helps

Title: Tensorflow textsum error of Versioning

Body:
I am trying to convert the training text file to bin file for training the textsum of tensorflow. But I encountered the following error:

$ python textsum/data_convert_example.py --command text_to_binary --in_file data/tt.txt --out_file data/bin_data_train
Traceback (most recent call last):
  File "textsum/data_convert_example.py", line 12, in <module>
    import tensorflow as tf
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 104, in <module>
    from tensorflow.python.platform import test
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/test.py", line 57, in <module>
    import mock                # pylint: disable=g-import-not-at-top,unused-import
  File "/usr/local/lib/python2.7/dist-packages/mock/__init__.py", line 2, in <module>
    import mock.mock as _mock
  File "/usr/local/lib/python2.7/dist-packages/mock/mock.py", line 71, in <module>
    _v = VersionInfo('mock').semantic_version()
  File "/usr/local/lib/python2.7/dist-packages/pbr/version.py", line 461, in semantic_version
    self._semantic = self._get_version_from_pkg_resources()
  File "/usr/local/lib/python2.7/dist-packages/pbr/version.py", line 448, in _get_version_from_pkg_resources
    result_string = packaging.get_version(self.package)
  File "/usr/local/lib/python2.7/dist-packages/pbr/packaging.py", line 755, in get_version
    name=package_name))
Exception: Versioning for this project requires either an sdist tarball, or access to an upstream git repository. It's also possible that there is a mismatch between the package name in setup.cfg and the argument given to pbr.version.VersionInfo. Project name mock was given, but was not able to be found.

Kindly help me. I am using tensorflow 1.2.0 with python 2.7.2.


问:
Why is my Python script too slow in comparison with Matlab?
I'm considering making the switch from Matlab to Python (NumPy). So, as a learning task, I have tried to rewrite a simple stochastic model on Python. The python script returns the right answer, but works too slow! It takes 3 minutes for Python instead 3 seconds like Matlab. What am I doing wrong?

Matlab:

```<code>clear all; clc;
tic

T = 0.05;
Tmax = 3600;
t = T:T:Tmax;
N = length(t);
G = [0 0;
    0 T];

F = [1 T;
    0 1];

Dksi = 13*1;
Deta = 10*1;
Band = 0.1:0.1:3;
RMS_Omega = nan(1, length(Band));
for i = 1:length(Band)
    K = nan(2, 1);
    K(1) = 8/3 * Band(i) * T;
    K(2) = 32/9 * Band(i)^2 * T;

    ksi = sqrt(Dksi) * randn(1, N);
    eta = sqrt(Deta) * randn(1, N);

    Xest = [0; 0];
    Xextr = F*Xest;

    Xist = [0; 0];

    ErrOmega = nan(1, N); Omega = nan(1, N);
    for k = 1:N
        Xist = F*Xist + G*[0; ksi(k)];
        omega_meas = Xist(1) + eta(k);
        Xest = Xextr + K*(omega_meas - Xextr(1));
        Xextr = F*Xest;
        ErrOmega(k) = Xest(1) - Xist(1);
        Omega(k) = Xist(1);
    end

    RMS_Omega(i) = sqrt(mean(ErrOmega.^2));
end

figure(1)
hold on
plot(Band, RMS_Omega);
hold off
xlabel('Bandwidth, Hz'); ylabel('RMS \omega, Hz');
toc
</code>```

Python:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import time as time

tbeg = time.time()

T = 0.005
Tmax = 3600.0

t = np.linspace(T, Tmax, int(Tmax/T))
N = len(t)

G = np.array([[0, 0],
              [0, T]])

F = np.array([[1, T],
              [0, 1]])

Dksi = 13.0
Deta = 10.0

Band = np.linspace(0.1, 3.0, 30)
Band_for_plot = 2

RMS_Omega = np.array([None for i in range(0, len(Band))])

for i, BW in enumerate(Band):
    K = np.array([[8/3 * BW * T],
                  [32/9 * BW*BW *T]])

    ksi = math.sqrt(Dksi) * np.random.randn(N)
    eta = math.sqrt(Deta) * np.random.randn(N)

    Xest = np.array([[0],
                     [0]])
    Xextr = F.dot(Xest)

    Xist = np.array([[0],
                     [0]])

    ErrOmega = np.array([None for j in range(0, N)])
    Omega    = np.array([None for j in range(0, N)])

    for k in range(0, N):
        Xist = F.dot(Xist) + G.dot(np.array([[0],
                                             [ksi[k]]]))
        omega_meas = Xist[0] + eta[k]
        Xest = Xextr + K * (omega_meas - Xextr[0])
        Xextr = F.dot(Xest)
        ErrOmega[k] = Xest[0] - Xist[0]
        Omega[k] = Xist[0]

    RMS_Omega[i] = math.sqrt(np.mean(ErrOmega**2))

elapsed = time.time() - tbeg
print(elapsed, u'sec')
</code>```

答:
Having dealt with similar issues, i learnt to avoid making the translation of codes. Despite it can save time in writing, it does not in the running (weight the usage/time of writing).

for loops in Python are normally slower than Matlab, but offers plenty of tools and libraries that can help to built a good code, so make use of them. The comments in the question are already a good help!

Body:
I'm considering making the switch from Matlab to Python (NumPy). So, as a learning task, I have tried to rewrite a simple stochastic model on Python. The python script returns the right answer, but works too slow! It takes 3 minutes for Python instead 3 seconds like Matlab. What am I doing wrong?

Matlab:

clear all; clc;
tic

T = 0.05;
Tmax = 3600;
t = T:T:Tmax;
N = length(t);
G = [0 0;
    0 T];

F = [1 T;
    0 1];

Dksi = 13*1;
Deta = 10*1;
Band = 0.1:0.1:3;
RMS_Omega = nan(1, length(Band));
for i = 1:length(Band)
    K = nan(2, 1);
    K(1) = 8/3 * Band(i) * T;
    K(2) = 32/9 * Band(i)^2 * T;

    ksi = sqrt(Dksi) * randn(1, N);
    eta = sqrt(Deta) * randn(1, N);

    Xest = [0; 0];
    Xextr = F*Xest;

    Xist = [0; 0];

    ErrOmega = nan(1, N); Omega = nan(1, N);
    for k = 1:N
        Xist = F*Xist + G*[0; ksi(k)];
        omega_meas = Xist(1) + eta(k);
        Xest = Xextr + K*(omega_meas - Xextr(1));
        Xextr = F*Xest;
        ErrOmega(k) = Xest(1) - Xist(1);
        Omega(k) = Xist(1);
    end

    RMS_Omega(i) = sqrt(mean(ErrOmega.^2));
end

figure(1)
hold on
plot(Band, RMS_Omega);
hold off
xlabel('Bandwidth, Hz'); ylabel('RMS \omega, Hz');
toc

Python:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import time as time

tbeg = time.time()

T = 0.005
Tmax = 3600.0

t = np.linspace(T, Tmax, int(Tmax/T))
N = len(t)

G = np.array([[0, 0],
              [0, T]])

F = np.array([[1, T],
              [0, 1]])

Dksi = 13.0
Deta = 10.0

Band = np.linspace(0.1, 3.0, 30)
Band_for_plot = 2

RMS_Omega = np.array([None for i in range(0, len(Band))])

for i, BW in enumerate(Band):
    K = np.array([[8/3 * BW * T],
                  [32/9 * BW*BW *T]])

    ksi = math.sqrt(Dksi) * np.random.randn(N)
    eta = math.sqrt(Deta) * np.random.randn(N)

    Xest = np.array([[0],
                     [0]])
    Xextr = F.dot(Xest)

    Xist = np.array([[0],
                     [0]])

    ErrOmega = np.array([None for j in range(0, N)])
    Omega    = np.array([None for j in range(0, N)])

    for k in range(0, N):
        Xist = F.dot(Xist) + G.dot(np.array([[0],
                                             [ksi[k]]]))
        omega_meas = Xist[0] + eta[k]
        Xest = Xextr + K * (omega_meas - Xextr[0])
        Xextr = F.dot(Xest)
        ErrOmega[k] = Xest[0] - Xist[0]
        Omega[k] = Xist[0]

    RMS_Omega[i] = math.sqrt(np.mean(ErrOmega**2))

elapsed = time.time() - tbeg
print(elapsed, u'sec')


问:
How to make custom shape (arrow on the sides pointing outwards) of a button?
I want to make my button look like the following. Can you please tell me, how to make a drawable xml file for the following?

like this image

答:
You can do this by creating a drawable XML file inside your drawable

background.xml

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="27dp"
    android:height="24dp"
    android:viewportHeight="628.0"
    android:viewportWidth="726.0">
    <path
        android:fillColor="#00ffffff"
        android:pathData="m723,314c-60,103.9 -120,207.8 -180,311.8 -120,0 -240,0 -360,0C123,521.8 63,417.9 3,314 63,210.1 123,106.2 183,2.2c120,0 240,0 360,0C603,106.2 663,210.1 723,314Z"
        android:strokeColor="#ffffff"
        android:strokeWidth="20" />
</vector>
</code>```

Then in your layout file you can add the background like below

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#652ef0"
    android:orientation="vertical"
    tools:context="com.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/background"
        android:gravity="center"
        android:text="Hello World!" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:gravity="center"
        android:text="Hello World 2!" />
</LinearLayout>
</code>```

This will give you output something like this

Body:
You can do this by creating a drawable XML file inside your drawable

background.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="27dp"
    android:height="24dp"
    android:viewportHeight="628.0"
    android:viewportWidth="726.0">
    <path
        android:fillColor="#00ffffff"
        android:pathData="m723,314c-60,103.9 -120,207.8 -180,311.8 -120,0 -240,0 -360,0C123,521.8 63,417.9 3,314 63,210.1 123,106.2 183,2.2c120,0 240,0 360,0C603,106.2 663,210.1 723,314Z"
        android:strokeColor="#ffffff"
        android:strokeWidth="20" />
</vector>

Then in your layout file you can add the background like below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#652ef0"
    android:orientation="vertical"
    tools:context="com.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/background"
        android:gravity="center"
        android:text="Hello World!" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:gravity="center"
        android:text="Hello World 2!" />
</LinearLayout>

This will give you output something like this


答:
If i understand you correctly you can do this</p>

```<code>WHERE updated_at <= '2017-07-01' AND updated_at >= '2017-01-01'
</code>```

Title: Get the rows from previous month

Body:
If i understand you correctly you can do this

WHERE updated_at <= '2017-07-01' AND updated_at >= '2017-01-01'


问:
How do I get permitAll in Spring Security to NOT throw AuthenticationCredentialsNotFoundException in @Controller object?
I have a controller that has many actions and it specifies a default class-level @PreAuthorize annotation, but one of the actions I want to let anyone in (the "show" action).

```<code>@RequestMapping("/show/{pressReleaseId}")
@PreAuthorize("permitAll")
public ModelAndView show(@PathVariable long pressReleaseId) {
    ModelAndView modelAndView = new ModelAndView(view("show"));

    modelAndView.addObject("pressRelease",
        sysAdminService.findPressRelease(pressReleaseId));

    return modelAndView;
}
</code>```

Unfortunately, Spring Security throws this exception:

```<code>org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:321)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:195)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
</code>```

How can I get Spring Security to NOT throw this exception? I just want to let anyone in - non-authenticated users and authenticated users - Everyone.

My only solution is to put this method into another controller altogether with no @PreAuthorize at all... which will work, but that's stupid. I want to keep all my press release actions in the same controller.

Thanks for the help!

答:
I guess you don't have anonymouse authentication filter enabled.

If you use namespace configuration and auto-config = "true", it should be enabled by default. If you don't use auto-config, you can enable anonymous filter as <security:anonymous />.

Body:
I have a controller that has many actions and it specifies a default class-level @PreAuthorize annotation, but one of the actions I want to let anyone in (the "show" action).

@RequestMapping("/show/{pressReleaseId}")
@PreAuthorize("permitAll")
public ModelAndView show(@PathVariable long pressReleaseId) {
    ModelAndView modelAndView = new ModelAndView(view("show"));

    modelAndView.addObject("pressRelease",
        sysAdminService.findPressRelease(pressReleaseId));

    return modelAndView;
}

Unfortunately, Spring Security throws this exception:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:321)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:195)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)

How can I get Spring Security to NOT throw this exception? I just want to let anyone in - non-authenticated users and authenticated users - Everyone.

My only solution is to put this method into another controller altogether with no @PreAuthorize at all... which will work, but that's stupid. I want to keep all my press release actions in the same controller.

Thanks for the help!


问:
MSVCP140.dll despite /MT runtime library setting
I tried to run a program I wrote on a remote computer. As I knew there might be a dll problem, I set the runtime library option to /MT, so I can rely on static linking.

However, I still receive the error message on my remote computer, stating that MSCVP140.dll is missing. Isn't this what the /MT flag should take care of?

I even tried to install the redistributable, but no luck. I'm still stuck with the error.

Another thing I tried was placing a MSVCP140.dll I downloaded in the folder, but that way my program is simply crashing on startup. I suspect that the MSCVP140.dll version is not the expected one, so I'm not relying on the validity of this test.

Any ideas?

答: Try to open your exe with depends.exe and find the dependancies in the machine it crashes. Probably the MSVCP140 might have other dependancies. Copy all dependancy dlls into same folder and give a try.</p>


问:
How to consistently skip (or not skip) x axis labels in R base graphics
I want to create a figure where for various reasons I need to specify the axis labels myself. But when I specify my labels (some have one digit, some two digits) R suppresses every other two-digit label because it decides there isn't enough room to show them all, but it leaves all of the one-digit labels, leaving the axis looking lopsided.

Is there a way to suppress labels consistently across the whole axis, based on whether any of them need to be skipped? Note: I have a lot of plots with varying scales, so I was looking for something I could use for all of them - I don't want to render all the labels for every plot, or to skip every other label in every plot. Suppressing labels will be desirable for some plots and not for others. I just want to skip every other label consistently, if that's what R chooses to do for the particular plot.

(Here is an example figure of what I mean. What I want is for the "6%" label to also be suppressed in the x axis.)
Example code:

```<code>library(labeling)

df <- data.frame("estimate" = c(9.81, 14.29, 12.94),
             "lower" = c(4.54, 6.25, 5.12),
             "upper" = c(12.85, 20.12, 15.84))
ticks <- extended(min(df$lower), max(df$upper), m = 5, only.loose = TRUE,
              Q=c(2, 5, 10))

png("examplePlot.png", width = 1200, height = 900, pointsize = 10, res = 300)
bars <- barplot(df$estimate, horiz = TRUE, col = "white", border = NA,
            xlim = c(min(ticks), max(ticks)), xaxt = "n", main = "Example")
arrows(df$lower, bars, df$upper, bars, code = 3, angle = 90, length = 0.03)
points(df$estimate, bars, pch = 20)

tickLabels <- paste(ticks, "%", sep = "")
axis(1, at=ticks, labels = tickLabels, cex.axis=1)
axis(2, at = bars, labels = c("c", "b", "a"), lwd = 0, las = 2)
dev.off()
</code>```

答:
This depends on the size of the plot, so you'll have to plot each label separately:

```<code>axis(1, lwd.ticks = 1, labels = FALSE, at = ticks) # plot line and ticks
i <- seq(1,length(ticks),2) # which labels to plot
for(ii in i)
  axis(1, at = ticks[ii], labels = tickLabels[ii], cex.axis = 1, lwd = 0)
</code>```

Body:
I want to create a figure where for various reasons I need to specify the axis labels myself. But when I specify my labels (some have one digit, some two digits) R suppresses every other two-digit label because it decides there isn't enough room to show them all, but it leaves all of the one-digit labels, leaving the axis looking lopsided.

Is there a way to suppress labels consistently across the whole axis, based on whether any of them need to be skipped? Note: I have a lot of plots with varying scales, so I was looking for something I could use for all of them - I don't want to render all the labels for every plot, or to skip every other label in every plot. Suppressing labels will be desirable for some plots and not for others. I just want to skip every other label consistently, if that's what R chooses to do for the particular plot.

(Here is an example figure of what I mean. What I want is for the "6%" label to also be suppressed in the x axis.)
Example code:

library(labeling)

df <- data.frame("estimate" = c(9.81, 14.29, 12.94),
             "lower" = c(4.54, 6.25, 5.12),
             "upper" = c(12.85, 20.12, 15.84))
ticks <- extended(min(df$lower), max(df$upper), m = 5, only.loose = TRUE,
              Q=c(2, 5, 10))

png("examplePlot.png", width = 1200, height = 900, pointsize = 10, res = 300)
bars <- barplot(df$estimate, horiz = TRUE, col = "white", border = NA,
            xlim = c(min(ticks), max(ticks)), xaxt = "n", main = "Example")
arrows(df$lower, bars, df$upper, bars, code = 3, angle = 90, length = 0.03)
points(df$estimate, bars, pch = 20)

tickLabels <- paste(ticks, "%", sep = "")
axis(1, at=ticks, labels = tickLabels, cex.axis=1)
axis(2, at = bars, labels = c("c", "b", "a"), lwd = 0, las = 2)
dev.off()

Body:
This depends on the size of the plot, so you'll have to plot each label separately:

axis(1, lwd.ticks = 1, labels = FALSE, at = ticks) # plot line and ticks
i <- seq(1,length(ticks),2) # which labels to plot
for(ii in i)
  axis(1, at = ticks[ii], labels = tickLabels[ii], cex.axis = 1, lwd = 0)


问:
How to merge SaveChanges and multiple SQL commands into a single sp_executesql in Entity Framework 6
I have the following code inside my DbContext class:

```<code>public partial class MyEntities : DbContext
{
    public override int SaveChanges()
    {
        Database.ExecuteSqlCommand("INSERT INTO Schema1.View ([Key],[Value]) VALUES('Flag', '1')"); //session #1?
        base.SaveChanges(); //session #2? :(
    }
}
</code>```

When I checked it with Profiler, I see this:

I intend to have only one session (meaning I can't have sp_reset_connection between the INSERT INTO and the sp_executesql commands - that is generated by the SaveChanges call)

So I tried the following:

```<code>      using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
      {
        Database.ExecuteSqlCommand("INSERT INTO Schema1.View ([Key],[Value]) VALUES('Flag', '1')"); //session #1?
        //Database.ExecuteSqlCommand(TransactionalBehavior.EnsureTransaction,"INSERT INTO Schema1.View ([Key],[Value]) VALUES('Flag', '1')"); //session #1?
        base.SaveChanges(); //session #2? :(
        scope.Complete();
      }
</code>```

It didn't change anything.

I tried this also:

```<code>using (var tr = Database.Connection.BeginTransaction())
{
...
}
</code>```

It throws an exception that the connection is closed.

What else should I try? Can I inject my INSERT into the SaveChanges code?

答:
I believe wrapping the custom SQL command(s) and base SaveChanges call in database transaction is the correct way of doing what you need.

However, instead of using BeginTransaction method of the underlying DbConnection which also requires manually opening/closing it, you should use the Database.BeginTransaction method which will do the connection management for you:

```<code>using (var tr = Database.BeginTransaction())
{
    //...
    tr.Commit();
}
</code>```

Body:
I have the following code inside my DbContext class:

public partial class MyEntities : DbContext
{
    public override int SaveChanges()
    {
        Database.ExecuteSqlCommand("INSERT INTO Schema1.View ([Key],[Value]) VALUES('Flag', '1')"); //session #1?
        base.SaveChanges(); //session #2? :(
    }
}

When I checked it with Profiler, I see this:

I intend to have only one session (meaning I can't have sp_reset_connection between the INSERT INTO and the sp_executesql commands - that is generated by the SaveChanges call)

So I tried the following:

      using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
      {
        Database.ExecuteSqlCommand("INSERT INTO Schema1.View ([Key],[Value]) VALUES('Flag', '1')"); //session #1?
        //Database.ExecuteSqlCommand(TransactionalBehavior.EnsureTransaction,"INSERT INTO Schema1.View ([Key],[Value]) VALUES('Flag', '1')"); //session #1?
        base.SaveChanges(); //session #2? :(
        scope.Complete();
      }

It didn't change anything.

I tried this also:

using (var tr = Database.Connection.BeginTransaction())
{
...
}

It throws an exception that the connection is closed.

What else should I try? Can I inject my INSERT into the SaveChanges code?

Body:
I believe wrapping the custom SQL command(s) and base SaveChanges call in database transaction is the correct way of doing what you need.

However, instead of using BeginTransaction method of the underlying DbConnection which also requires manually opening/closing it, you should use the Database.BeginTransaction method which will do the connection management for you:

using (var tr = Database.BeginTransaction())
{
    //...
    tr.Commit();
}


问:
Random Graph Partitioning
I'm trying to test some models of graph partitioning (these come from the real world, where a graph slowly self-partitions). To do this, I need to be able to uniformly randomly partition this graph into contiguous components (we are given the graph is initially connected, as well). Were the contiguity criterion not required I believe this would be the problem of randomly partitioning a set, which can be combinatorially analyzed. Does anyone know of any way to randomly partition graphs into subgraphs (i.e. randomly sample one partition), or, if no such method is known, to randomly sample a set of elements? The method of randomizing the number of partitions and then randomizing membership won't work because there are different numbers of possible partitions for each partition size.</p>

答: You have to differentiate edge-cut partitioning and vertex-cut partitioning, where you divide the graph along the edges or vertices. This significantly impacts your problem as the number of different vertex-cuts is much larger than the number of edge-cuts. The reason is that you exclusively assign edges to partitions in vertex-cut - as opposed to edge-cut where you assign vertices to partitions - and there are much more edges than vertices (e.g. O(n^2) edges for n vertices). Hence, the combinatorially larger vertex-cut leads to a larger number of subgraphs that have to be checked for connectivity. A naive method for randomization is to enumerate all partitionings, iteratively select one partitioning, and check connectivity of all subgraphs in the selected partitioning. Then you just take the first one. In this case, all solutions have equal probability (uniformly random).</p>

Title: Random Graph Partitioning