问:
How this website detectes my selenium spider and how to get it through?

Environment: Selenium + ChromeDriver

I am using selenium to get some data on a website which can only be acquired by Ajex requests. But got information like "
Verification failed, please refresh the page and re-query". And when I did the exactly same thing on chrome, I got a Slider verification instead. So my question is, why I even didn't see a Slider verification while using selenium but got the information of "Verification failed"? And I can't find any clue in the JS codes of the website either because I didn't find any piece of code related to the information.

Related JS codes are as follows:

function getData(t, e) {
    $.ajax({
        url: "/api/pricehistory/getUrlPriceHistory",
        type: "POST",
        data: {
            url: t,
            nvcVal: window.getNVCVal()
        },
        success: function(t) {
            e && e(t)
        }
    })
}
function loadGoodsData() {
    function t(t) {
        var e = (new Date).getTime()
          , a = t.pv
          , i = "";
        i = a < 10 && e - new Date(t.update_time.replace(/-/g, "/")) < 864e5 ? "优惠新上" : a + "人看过",
        t.pvText = i;
        var o = formatTime(t.update_time, e);
        t.upTime = o;
        var c, n, s = t.description, r = s, d = /<a[^<>]+>[^<>]+<\/a>/gi, l = r.match(d);
        c = n = 0;
        var p;
        r = r.replace(d, "%#" + c++ + "%"),
        r = r.replace(/<[^>]+>/gi, ""),
        p = ZTools.subWideCharStr(r, 180, '... 查看全部'),
        p = p.replace(/%#(\d+)%/gi, function() {
            return l[n++]
        }),
        p = p.replace(/%(#)?(\d+)?.../g, "..."),
        s = s.replace(/
/gi, "

"),
        t.multi_image && t.multi_image.length > 0 && p.indexOf('查看全部') == -1 && (p += '查看全部'),
        t.descSummary = p,
        t.descText = s
    }
    var e = /^https?:\/\/[^\s<>]*$/i
      , a = $("#ipt").val() || "https://item.jd.com/44125207975.html";
    $(".price-search .notice").hide(),
    $(".J-product-info").hide(),
    $(".J-news").hide(),
    $(".J-history").hide(),
    e.test(a) ? getData(a, function(e) {
        if (e && 1 === e.RC)
            if (e.data && 200 == e.data.code || 100 == e.data.code)
                if (e.data.info && e.data.pcinfo) {
                    var a = {};
                    a.title = e.data.info.title || "暂未获取到商品标题",
                    a.pic = e.data.info.pic || ZTools.defaults.defaultPic,
                    a.pic = ZTools.imageUrlAdapter(a.pic, 240, 150, 1),
                    a.buylink = e.data.info.buylink,
                    a.price = e.data.info.price,
                    a.shop = e.data.info.shop,
                    a.trend = e.data.pcinfo.trend,
                    e.data.info.title && (a.couponlink = "http://" + (g_domain || "www.miaomiaozhe.com") + "/search?filter=coupon&q=" + e.data.info.title);
                    var i = window.template("tpl_goods_prl_info", a);
                    if ($(".product").html(i),
                    $(".J-product-info").show(),
                    loadPricetrend({
                        pcinfo: e.data.pcinfo,
                        wrap: ".prod-info .pricetrend"
                    }),
                    e.data.live.length > 0) {
                        var o = e.data.live[0];
                        t(o);
                        var c = window.template("tpl_live_list", o);
                        $("#news-list").html(c),
                        $(".J-news").show()
                    }
                    if (e.data.live.length > 1) {
                        for (var o = e.data.live, n = "", s = 1; s < o.length; s++)
                            t(o[s]),
                            n += window.template("tpl_live_list", o[s]);
                        $("#history-list").html(n),
                        $(".J-history").show()
                    }
                } else
                    $(".price-search .notice.no-result").show();
            else
                e.data && 800 == e.data.code || 900 == e.data.code ? $(".price-search .notice.failed").show() : getNC().then(function() {
                    _nvc_nc.upLang("cn", {
                        _startTEXT: "请按住滑块，拖动到最右边校验后查看",
                        _yesTEXT: "验证通过",
                        _error300: '哎呀，出错了，点击刷新再来一次',
                        _errorNetwork: '网络不给力，请点击刷新'
                    }),
                    _nvc_nc.reset()
                });
        else
            $(".price-search .notice.no-result").show()
    }) : $(".price-search .notice.no-result").show()
}
$(function() {
    window.NVC_Opt = {
        appkey: "FFFF0N0N000000006AFF",
        scene: "nvc_activity",
        isH5: !1,
        popUp: !0,
        renderTo: "#captcha",
        trans: {
            key1: "code0",
            nvcCode: 400
        },
        language: "cn",
        customWidth: 300,
        nvcCallback: function(t) {
            loadGoodsData()
        }
    };
    var t = new Date
      , e = t.getTime() - 60 * t.getMinutes() * 1e3 - 1e3 * t.getSeconds() - t.getMilliseconds()
      , a = document.createElement("script");
    a.src = "//g.alicdn.com/sd/nvc/1.1.112/guide.js?t=" + e,
    document.body.appendChild(a);
    var i = document.createElement("div");
    i.id = "captcha",
    $(".price-search").append(i);
    var o = $("#ipt").attr("placeholder");
    $("#ipt").on({
        focus: function() {
            $(this).attr("placeholder") && $(this).attr("placeholder", ""),
            $(this).addClass("focus"),
            $(this).select()
        },
        blur: function() {
            $(this).attr("placeholder") || $(this).attr("placeholder", o),
            $(this).removeClass("focus")
        },
        keydown: function(t) {
            13 == t.which && (loadGoodsData(),
            t && t.stopPropagation())
        }
    }),
    $("#search-btn").on({
        click: function() {
            loadGoodsData()
        }
    })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel price-search">
    <input type="text" placeholder="请输入商品链接，如https://item.jd.com/44125207975.html" class="ipt" id="ipt" value="">
    <span class="btn" id="search-btn">历史价格查询</span>
    <p class="notice no-result hide" style="display: none;">抱歉，没有查到此商品的历史价格</p>
   <p class="notice failed hide" style="display: block;">验证失败，请刷新页面重新查询</p>
<div id="captcha"></div></div></code>```

my spider source codes are as follows:

```<code>from selenium import webdriver
from time import sleep

chrome_opt = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 1}
chrome_opt.add_experimental_option("prefs", prefs)
chrome_opt.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_opt.add_argument('user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"')
driver = webdriver.Chrome(chrome_options=chrome_opt)
driver.get("https://www.miaomiaozhe.com")
driver.find_element_by_class_name('pl').click()
good2 = "https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.7.e748471bIRN6jQ&id=554640570620&skuId=4341085905022&areaId=420100&user_id=2928380385&cat_id=2&is_b=1&rn=6ba9712cf53485a574d73191e05d0cbf"
goodURL = "https://detail.tmall.com/item.htm?id=569343149791&spm=875.7931836/B.2017081.2.66144265gU7Lgd&scm=1007.12144.81309.73299_0_0&pvid=10ae9600-6e84-4ad0-8e1e-a8379cea71c3&utparam=%7B%22x_hestia_source%22:%2273299%22,%22x_object_type%22:%22item%22,%22x_mt%22:9,%22x_src%22:%2273299%22,%22x_pos%22:1,%22x_pvid%22:%2210ae9600-6e84-4ad0-8e1e-a8379cea71c3%22,%22x_object_id%22:569343149791%7D"
driver.find_element_by_id('ipt').send_keys(good2)
driver.find_element_by_id('search-btn').click()
print(driver.current_url)
driver.close
</code>```

答:
I have found the problem. The website is watching some JS parameters embeded in the selenium chromedriver. Feasible solution are as follows:

hanging another module like pyppeteer.

hanging another module like pyppeteer.

Using agent like mitmproxy.

Using firefoxdriver instead.

Body:
Environment: Selenium + ChromeDriver

I am using selenium to get some data on a website which can only be acquired by Ajex requests. But got information like "
Verification failed, please refresh the page and re-query". And when I did the exactly same thing on chrome, I got a Slider verification instead. So my question is, why I even didn't see a Slider verification while using selenium but got the information of "Verification failed"? And I can't find any clue in the JS codes of the website either because I didn't find any piece of code related to the information.

Related JS codes are as follows:

function getData(t, e) {
    $.ajax({
        url: "/api/pricehistory/getUrlPriceHistory",
        type: "POST",
        data: {
            url: t,
            nvcVal: window.getNVCVal()
        },
        success: function(t) {
            e && e(t)
        }
    })
}
function loadGoodsData() {
    function t(t) {
        var e = (new Date).getTime()
          , a = t.pv
          , i = "";
        i = a < 10 && e - new Date(t.update_time.replace(/-/g, "/")) < 864e5 ? "优惠新上" : a + "人看过",
        t.pvText = i;
        var o = formatTime(t.update_time, e);
        t.upTime = o;
        var c, n, s = t.description, r = s, d = /<a[^<>]+>[^<>]+<\/a>/gi, l = r.match(d);
        c = n = 0;
        var p;
        r = r.replace(d, "%#" + c++ + "%"),
        r = r.replace(/<[^>]+>/gi, ""),
        p = ZTools.subWideCharStr(r, 180, '... 查看全部'),
        p = p.replace(/%#(\d+)%/gi, function() {
            return l[n++]
        }),
        p = p.replace(/%(#)?(\d+)?.../g, "..."),
        s = s.replace(/
/gi, "

"),
        t.multi_image && t.multi_image.length > 0 && p.indexOf('查看全部') == -1 && (p += '查看全部'),
        t.descSummary = p,
        t.descText = s
    }
    var e = /^https?:\/\/[^\s<>]*$/i
      , a = $("#ipt").val() || "https://item.jd.com/44125207975.html";
    $(".price-search .notice").hide(),
    $(".J-product-info").hide(),
    $(".J-news").hide(),
    $(".J-history").hide(),
    e.test(a) ? getData(a, function(e) {
        if (e && 1 === e.RC)
            if (e.data && 200 == e.data.code || 100 == e.data.code)
                if (e.data.info && e.data.pcinfo) {
                    var a = {};
                    a.title = e.data.info.title || "暂未获取到商品标题",
                    a.pic = e.data.info.pic || ZTools.defaults.defaultPic,
                    a.pic = ZTools.imageUrlAdapter(a.pic, 240, 150, 1),
                    a.buylink = e.data.info.buylink,
                    a.price = e.data.info.price,
                    a.shop = e.data.info.shop,
                    a.trend = e.data.pcinfo.trend,
                    e.data.info.title && (a.couponlink = "http://" + (g_domain || "www.miaomiaozhe.com") + "/search?filter=coupon&q=" + e.data.info.title);
                    var i = window.template("tpl_goods_prl_info", a);
                    if ($(".product").html(i),
                    $(".J-product-info").show(),
                    loadPricetrend({
                        pcinfo: e.data.pcinfo,
                        wrap: ".prod-info .pricetrend"
                    }),
                    e.data.live.length > 0) {
                        var o = e.data.live[0];
                        t(o);
                        var c = window.template("tpl_live_list", o);
                        $("#news-list").html(c),
                        $(".J-news").show()
                    }
                    if (e.data.live.length > 1) {
                        for (var o = e.data.live, n = "", s = 1; s < o.length; s++)
                            t(o[s]),
                            n += window.template("tpl_live_list", o[s]);
                        $("#history-list").html(n),
                        $(".J-history").show()
                    }
                } else
                    $(".price-search .notice.no-result").show();
            else
                e.data && 800 == e.data.code || 900 == e.data.code ? $(".price-search .notice.failed").show() : getNC().then(function() {
                    _nvc_nc.upLang("cn", {
                        _startTEXT: "请按住滑块，拖动到最右边校验后查看",
                        _yesTEXT: "验证通过",
                        _error300: '哎呀，出错了，点击刷新再来一次',
                        _errorNetwork: '网络不给力，请点击刷新'
                    }),
                    _nvc_nc.reset()
                });
        else
            $(".price-search .notice.no-result").show()
    }) : $(".price-search .notice.no-result").show()
}
$(function() {
    window.NVC_Opt = {
        appkey: "FFFF0N0N000000006AFF",
        scene: "nvc_activity",
        isH5: !1,
        popUp: !0,
        renderTo: "#captcha",
        trans: {
            key1: "code0",
            nvcCode: 400
        },
        language: "cn",
        customWidth: 300,
        nvcCallback: function(t) {
            loadGoodsData()
        }
    };
    var t = new Date
      , e = t.getTime() - 60 * t.getMinutes() * 1e3 - 1e3 * t.getSeconds() - t.getMilliseconds()
      , a = document.createElement("script");
    a.src = "//g.alicdn.com/sd/nvc/1.1.112/guide.js?t=" + e,
    document.body.appendChild(a);
    var i = document.createElement("div");
    i.id = "captcha",
    $(".price-search").append(i);
    var o = $("#ipt").attr("placeholder");
    $("#ipt").on({
        focus: function() {
            $(this).attr("placeholder") && $(this).attr("placeholder", ""),
            $(this).addClass("focus"),
            $(this).select()
        },
        blur: function() {
            $(this).attr("placeholder") || $(this).attr("placeholder", o),
            $(this).removeClass("focus")
        },
        keydown: function(t) {
            13 == t.which && (loadGoodsData(),
            t && t.stopPropagation())
        }
    }),
    $("#search-btn").on({
        click: function() {
            loadGoodsData()
        }
    })
});

    <input type="text" placeholder="请输入商品链接，如https://item.jd.com/44125207975.html" class="ipt" id="ipt" value="">
    历史价格查询

抱歉，没有查到此商品的历史价格

验证失败，请刷新页面重新查询

my spider source codes are as follows:

from selenium import webdriver
from time import sleep

chrome_opt = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 1}
chrome_opt.add_experimental_option("prefs", prefs)
chrome_opt.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_opt.add_argument('user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"')
driver = webdriver.Chrome(chrome_options=chrome_opt)
driver.get("https://www.miaomiaozhe.com")
driver.find_element_by_class_name('pl').click()
good2 = "https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.7.e748471bIRN6jQ&id=554640570620&skuId=4341085905022&areaId=420100&user_id=2928380385&cat_id=2&is_b=1&rn=6ba9712cf53485a574d73191e05d0cbf"
goodURL = "https://detail.tmall.com/item.htm?id=569343149791&spm=875.7931836/B.2017081.2.66144265gU7Lgd&scm=1007.12144.81309.73299_0_0&pvid=10ae9600-6e84-4ad0-8e1e-a8379cea71c3&utparam=%7B%22x_hestia_source%22:%2273299%22,%22x_object_type%22:%22item%22,%22x_mt%22:9,%22x_src%22:%2273299%22,%22x_pos%22:1,%22x_pvid%22:%2210ae9600-6e84-4ad0-8e1e-a8379cea71c3%22,%22x_object_id%22:569343149791%7D"
driver.find_element_by_id('ipt').send_keys(good2)
driver.find_element_by_id('search-btn').click()
print(driver.current_url)
driver.close


来源: stackexchange

问:
Is it possible to create an animated gif from a youtube or vimeo location using php?
Just a thought on whether this would be possible really, I thought it would be really cool if I could create animated gifs for embedded videos on the fly. Has anyone seen this done before?</p>

答:
I'm not a professional programmer but I have this idea that u can just segment the video into frames, then use the frames to compose the gifs. Since u are going to be using PHP, u will have to create an extension that creates frames from videos (which is not so simple but possible, in C).

 I wish I could program well in C. I could undertake to create such an extension.

ContentLicense: CC BY-SA 3.0


问:
How to access BlueStacks' localhost from Windows?
After some research I managed to access Windows' localhost from Bluestacks. If I open Google Chrome in BlueStacks and type 10.0.2.2:/... I can access Windows' localhost.

How do I do this the other way around? Is there a way to connect to Bluestacks' localhost from Windows?

答:
Check your IP within your network with ipconfig (type ipconfig in console)

There should be something like this: (here: VirtualBox)

```<code>Ethernet adapter VirtualBox Host-Only Network:

        Connection-specific DNS Suffix  . :
        Autoconfiguration IP Address. . . : 169.254.106.123
        Subnet Mask . . . . . . . . . . . : 255.255.0.0
        Default Gateway . . . . . . . . . :
</code>```

169.254.106.123 is your address you are looking for.

ping it to see that it works, run a server and you will be able to connect to it.

ContentLicense: CC BY-SA 4.0

Body:
Check your IP within your network with ipconfig (type ipconfig in console)

There should be something like this: (here: VirtualBox)

Ethernet adapter VirtualBox Host-Only Network:

        Connection-specific DNS Suffix  . :
        Autoconfiguration IP Address. . . : 169.254.106.123
        Subnet Mask . . . . . . . . . . . : 255.255.0.0
        Default Gateway . . . . . . . . . :

169.254.106.123 is your address you are looking for.

ping it to see that it works, run a server and you will be able to connect to it.


问:
How to properly use the try catch in perl that error.pm provides?
I have found that there is the module Error that provides try and catch functionality like in java.  But I am confused at how you can print the exception that returns.

I would like to understand how to do the following

```<code>try {
    // do something that will fail!

} catch (Error e) {
    // Print out the exception that occurred
    System.out.println(e.getMessage());
}
</code>```

How do I get the print of the error with the stack trace?

答:
Unfortunately TryCatch has been broken with the new version 0.006020 of Devel::Declare and there seems to be no intention of fixing it. The perl core developers team also complained about the funky stuff TryCatch was relying on to make it work.

Instead there is a new implementation called Nice::Try, which is a perfect replacement.

There is no need to have semi colon on the last brace like Try::Tiny.

You can also do exception variable assignment like

```<code>  try
  {
    # something
  }
  catch( $e )
  {
    # catch this in $e
  }
</code>```

It also works using class exception like

```<code>  try
  {
    # something
  }
  catch( Exception $e )
  {
    # catch this in $e
  }
</code>```

And it also supports finally. Its features set make it quite unique.

Full disclosure: I have developed this module when TryCatch got broken.

Body:
I have found that there is the module Error that provides try and catch functionality like in java.  But I am confused at how you can print the exception that returns.

I would like to understand how to do the following

try {
    // do something that will fail!

} catch (Error e) {
    // Print out the exception that occurred
    System.out.println(e.getMessage());
}

How do I get the print of the error with the stack trace?

Body:
Unfortunately TryCatch has been broken with the new version 0.006020 of Devel::Declare and there seems to be no intention of fixing it. The perl core developers team also complained about the funky stuff TryCatch was relying on to make it work.

Instead there is a new implementation called Nice::Try, which is a perfect replacement.

There is no need to have semi colon on the last brace like Try::Tiny.

You can also do exception variable assignment like

  try
  {
    # something
  }
  catch( $e )
  {
    # catch this in $e
  }

It also works using class exception like

  try
  {
    # something
  }
  catch( Exception $e )
  {
    # catch this in $e
  }

And it also supports finally. Its features set make it quite unique.

Full disclosure: I have developed this module when TryCatch got broken.


问:
C++ treating object* as int*
I have some code that accepts a pointer to an object, and this has been working fine thus far, however, after some cleanup (I code messy, and then clean up when most of the bugs are gone), a function that accepts a pointer, is now treating the pointer passed to it as an int*.

I have checked that I am indeed passing a pointer, and can't seem to figure this one out. Why is this happening?

Here's some code below (highly trimmed down, and I am not sure if I'm allowed to even show a small amount of this code, but I need to figure this out, so sorry if it doesn't make a lot of sense). I've removed sensitive parts of the code, and frankly, parts I feel I'd be in trouble for posting. But the erroneous part of the code was included.

```<code>template <class T>
class TreeStructure {
    class TreeNode {

        public:
            T data;
            TreeNode<T> * parent;
            TreeNode<T> * left;
            TreeNode<T> * right;
            inline TreeNode(T d) : data(d), parent(0x0), left(0x0), right(0x0) {}
            inline TreeNode(T d,TreeNode<T>* p) : data(d), parent(p), left(0x0), right(0x0) {}
            inline TreeNode(T d,TreeNode<T>* p,TreeNode<T>* l,TreeNode<T>* r) : data(d), parent(p), left(l), right(r) {}
    };

    TreeNode<T>* root;

    // Recursive CRUD operations, used as helpers to public CRUD operations, _delete shown
    inline void _delete(TreeNode<T>* c) {
        if(c != 0x0) {
            _delete(c->left);  // This is where things go wrong, _delete compains of no valid conversion from 'int*' to 'TreeStructure::TreeNode<T>* [with T = int]'
            _delete(c->right);
            delete c;
            _size--;
            // Irrelevant operations down here
        }
    }

    public:
        inline bool remove(T d) {
            // Check if 'd' is in tree, return false if not, get pointer to containing node if so
            TreeNode<T>* node; // This is where we get the reference to the node. Code returns if data isn't found, so if we're here, we know we have a node.
            // _delete is never called if 'd' isn't in the tree, so we can assume its set to a node since we got this far
            _delete(node); // This call is fine, but the recursive calls in _delete fail
        }

};
</code>```

When I call remove(), and remove() in turn calls _delete(), which complains that the node is an int* when it is a TreeNode<int>*. And I know that whatever is passed to _delete() is a TreeNode<int>*, and even when recursively called, is guarded against NULL (noop if null). Why is this happening and how do I solve the issue?

答:
The compiler doesn't understand what TreeNode<T> is because it doesn't name a type; TreeNode is not a template.  Use TreeNode everywhere you have TreeNode<T>.

TreeNode implicitly gets T from its outer template class, so specifying it in this way isn't even necessary.  To put it another way, TreeStructure<int>::TreeNode and TreeStructure<std::string>::TreeNode are already different types.

I'm not sure why you get the specific error you get, but I would assume that somewhere in the mess of errors the compiler spit out is it complaining that TreeNode is not a template and so the <T> suffix doesn't make sense.  It's a longstanding tradition that C and C++ compilers try to forge ahead even after encountering an error and try to make things work.  I think the theory is that the more errors it can raise at once, the fewer compiler invocations you need to make because you could fix multiple errors each run.  In practice, however, it means the compiler is making bad assumptions and then generating errors predicated on those assumptions, so it can also generate a lot of noise.

In C and C++ programming, always pay attention to the first error.  Everything after that is likely to be useless noise.

Title: C++ treating object* as int*

Body:
I have some code that accepts a pointer to an object, and this has been working fine thus far, however, after some cleanup (I code messy, and then clean up when most of the bugs are gone), a function that accepts a pointer, is now treating the pointer passed to it as an int*.

I have checked that I am indeed passing a pointer, and can't seem to figure this one out. Why is this happening?

Here's some code below (highly trimmed down, and I am not sure if I'm allowed to even show a small amount of this code, but I need to figure this out, so sorry if it doesn't make a lot of sense). I've removed sensitive parts of the code, and frankly, parts I feel I'd be in trouble for posting. But the erroneous part of the code was included.

template <class T>
class TreeStructure {
    class TreeNode {

        public:
            T data;
            TreeNode<T> * parent;
            TreeNode<T> * left;
            TreeNode<T> * right;
            inline TreeNode(T d) : data(d), parent(0x0), left(0x0), right(0x0) {}
            inline TreeNode(T d,TreeNode<T>* p) : data(d), parent(p), left(0x0), right(0x0) {}
            inline TreeNode(T d,TreeNode<T>* p,TreeNode<T>* l,TreeNode<T>* r) : data(d), parent(p), left(l), right(r) {}
    };

    TreeNode<T>* root;

    // Recursive CRUD operations, used as helpers to public CRUD operations, _delete shown
    inline void _delete(TreeNode<T>* c) {
        if(c != 0x0) {
            _delete(c->left);  // This is where things go wrong, _delete compains of no valid conversion from 'int*' to 'TreeStructure::TreeNode<T>* [with T = int]'
            _delete(c->right);
            delete c;
            _size--;
            // Irrelevant operations down here
        }
    }

    public:
        inline bool remove(T d) {
            // Check if 'd' is in tree, return false if not, get pointer to containing node if so
            TreeNode<T>* node; // This is where we get the reference to the node. Code returns if data isn't found, so if we're here, we know we have a node.
            // _delete is never called if 'd' isn't in the tree, so we can assume its set to a node since we got this far
            _delete(node); // This call is fine, but the recursive calls in _delete fail
        }

};

When I call remove(), and remove() in turn calls _delete(), which complains that the node is an int* when it is a TreeNode<int>*. And I know that whatever is passed to _delete() is a TreeNode<int>*, and even when recursively called, is guarded against NULL (noop if null). Why is this happening and how do I solve the issue?


问:
What's the magic of JavaScript multiply by 1?
I've encountered this code:

const currency = "TWD";

function priceMathCeil(_int) {
  if (currency === "TWD") {
    return _int * 1;
  } else {
    return _int;
  }
}
```

I know this code looks useless, but JavaScript has so many pitfalls like 0.1 + 0.2 = 0.30000000000000004 something like that.

So I was wondering if I'm missing anything about multiply by 1 in JavaScript?

答:
That's not a pitfall... that's how computers work.  Look into floating point math.

As for the * 1, I suspect it's leftover from a previous currency rate change.  The only other thing would be forcing the type by using this operator, but I can't see why someone would do that only in the case of a certain currency.

Body:
I've encountered this code:

const currency = "TWD";

function priceMathCeil(_int) {
  if (currency === "TWD") {
    return _int * 1;
  } else {
    return _int;
  }
}

I know this code looks useless, but JavaScript has so many pitfalls like 0.1 + 0.2 = 0.30000000000000004 something like that.

So I was wondering if I'm missing anything about multiply by 1 in JavaScript?


问:
Count rows only if the count matches
How can I achieve something like this?

```<code>select count(distinct a.name)
from table_a as a
where (
    select count(*)
    from table_b as b
    where b.id = a.id
  ) = (
    select count(*)
    from table_c as c
    where c.id = a.id
);
</code>```

I want to count rows only if the count in the two different tables related to first are having the same count of IDs. Assume that we are using PostgreSQL.

答:
i've attempted to mock up the situation you described.

CREATE TABLE a (name VARCHAR, id INT8);
CREATE TABLE b (id INT8);
CREATE TABLE c (id INT8);
INSERT
  INTO a
VALUES ('none', 1),
       ('equal', 2),
       ('more_b', 3),
       ('more_c', 4),
       ('no_b', 5),
       ('no_c', 6);
INSERT INTO b VALUES (2), (3), (3), (4), (6);
INSERT INTO c VALUES (2), (3), (4), (4), (5);
SELECT name
  FROM (
          WITH b_agg AS (
                        SELECT a.id,
                               name,
                               CASE
                               WHEN b.id IS NULL THEN 0
                               ELSE count(*)
                               END AS smart_count
                          FROM a LEFT JOIN b ON a.id = b.id
                      GROUP BY a.id, a.name, b.id
                     ),
               c_agg AS (
                        SELECT a.id,
                               name,
                               CASE
                               WHEN c.id IS NULL THEN 0
                               ELSE count(*)
                               END AS smart_count
                          FROM a LEFT JOIN c ON a.id = c.id
                      GROUP BY a.id, a.name, c.id
                     )
        SELECT a.name,
               a.id,
               b_agg.smart_count AS b_count,
               c_agg.smart_count AS c_count
          FROM a JOIN b_agg ON a.id = b_agg.id JOIN c_agg ON a.id = c_agg.id
       ) AS t
 WHERE b_count = c_count;
DROP TABLE a;
DROP TABLE b;
DROP TABLE c;
```

<p>when run, this produces</p>

``` name
-------
 equal
 none
(2 rows)
```

Title: Count rows only if the count matches

Body:
How can I achieve something like this?

select count(distinct a.name)
from table_a as a
where (
    select count(*)
    from table_b as b
    where b.id = a.id
  ) = (
    select count(*)
    from table_c as c
    where c.id = a.id
);

I want to count rows only if the count in the two different tables related to first are having the same count of IDs. Assume that we are using PostgreSQL.

Body:
i've attempted to mock up the situation you described.

CREATE TABLE a (name VARCHAR, id INT8);
CREATE TABLE b (id INT8);
CREATE TABLE c (id INT8);
INSERT
  INTO a
VALUES ('none', 1),
       ('equal', 2),
       ('more_b', 3),
       ('more_c', 4),
       ('no_b', 5),
       ('no_c', 6);
INSERT INTO b VALUES (2), (3), (3), (4), (6);
INSERT INTO c VALUES (2), (3), (4), (4), (5);
SELECT name
  FROM (
          WITH b_agg AS (
                        SELECT a.id,
                               name,
                               CASE
                               WHEN b.id IS NULL THEN 0
                               ELSE count(*)
                               END AS smart_count
                          FROM a LEFT JOIN b ON a.id = b.id
                      GROUP BY a.id, a.name, b.id
                     ),
               c_agg AS (
                        SELECT a.id,
                               name,
                               CASE
                               WHEN c.id IS NULL THEN 0
                               ELSE count(*)
                               END AS smart_count
                          FROM a LEFT JOIN c ON a.id = c.id
                      GROUP BY a.id, a.name, c.id
                     )
        SELECT a.name,
               a.id,
               b_agg.smart_count AS b_count,
               c_agg.smart_count AS c_count
          FROM a JOIN b_agg ON a.id = b_agg.id JOIN c_agg ON a.id = c_agg.id
       ) AS t
 WHERE b_count = c_count;
DROP TABLE a;
DROP TABLE b;
DROP TABLE c;

when run, this produces

 name
-------
 equal
 none
(2 rows)


问:
How to access a AR scene in Xcode (Swift)?
For older Xcode versions, I was able to get a scene by accessing the .scnassets folder.

```<code>let scene = SCNScene(named: "art.scnassets/ship.scn")!
</code>```

However, the newer Xcode version no longer has this folder and replaced it with:
Experience.rcproject

How do I access a scene from this .rcproject?

答:
I found a solution.</p>

```<code>let boxAnchor = try! Expereience.loadBox()
//you replace .loadBox() to .loadWhatever() you named your scene

arView.scene.anchors.append(boxAnchor)
</code>```

Body:
For older Xcode versions, I was able to get a scene by accessing the .scnassets folder.

let scene = SCNScene(named: "art.scnassets/ship.scn")!

However, the newer Xcode version no longer has this folder and replaced it with:
Experience.rcproject

How do I access a scene from this .rcproject?

Body:
I found a solution.

let boxAnchor = try! Expereience.loadBox()
//you replace .loadBox() to .loadWhatever() you named your scene

arView.scene.anchors.append(boxAnchor)


问:
Converting a large number of MP3 files to videos for YouTube, each using same the JPEG image
I am looking for a way to convert large number of MP3 files to videos, each using the same image. Efficient processing time is important.

I tried the following:

```<code>ffmpeg -i image.jpg -i audio.mp3 -vcodec libx264 video.mp4
</code>```

VLC media player played the resulting video file with the correct sound, but a blank screen.

Microsoft Media Player played the sound and showed the intended image. I uploaded the video to YouTube and received the message:

"The video has failed to process. Please make sure you are uploading a supported file type."

How can I make this work?

答:
Create video:

```<code>ffmpeg -framerate 6 -loop 1 -i input.jpg -c:v libx264 -vf format=yuv420p -t 00:10:00 video.mp4
</code>```

The duration (-t) should be ≥ the MP3 with the longest duration.

Now stream copy the same video for each MP3:

```<code>ffmpeg -i video.mp4 -i audio.mp3 -map 0:v -map 1:a -c copy -movflags +faststart -shortest output.mp4
</code>```

Some notes regarding compatibility:

MP3 in MP4 does not have universal support, but will be fine in YouTube. If your target players do not like it then add -c:a aac after -c copy to output AAC audio.

If your target player does not like it then increase the -framerate value or add the -r output option with an appropriate value, such as -r 15. Again, YouTube should be able to handle it.

Body:
I am looking for a way to convert large number of MP3 files to videos, each using the same image. Efficient processing time is important.

I tried the following:

ffmpeg -i image.jpg -i audio.mp3 -vcodec libx264 video.mp4

VLC media player played the resulting video file with the correct sound, but a blank screen.

Microsoft Media Player played the sound and showed the intended image. I uploaded the video to YouTube and received the message:

"The video has failed to process. Please make sure you are uploading a supported file type."

How can I make this work?

Body:
Create video:

ffmpeg -framerate 6 -loop 1 -i input.jpg -c:v libx264 -vf format=yuv420p -t 00:10:00 video.mp4

The duration (-t) should be ≥ the MP3 with the longest duration.

Now stream copy the same video for each MP3:

ffmpeg -i video.mp4 -i audio.mp3 -map 0:v -map 1:a -c copy -movflags +faststart -shortest output.mp4

Some notes regarding compatibility:

MP3 in MP4 does not have universal support, but will be fine in YouTube. If your target players do not like it then add -c:a aac after -c copy to output AAC audio.

If your target player does not like it then increase the -framerate value or add the -r output option with an appropriate value, such as -r 15. Again, YouTube should be able to handle it.


问:
How to replace underscore(_) with space (' ') in angular view?
I'm displaying array keys in header of a table and I have underscore in my keys. I want to replace underscore with space in html table. I do not want to do it in component as I have other requirements.</p>

```<code><table>
   <thead>
       <tr>
           <th *ngFor="let header of printFields">{{header}}</th>
       </tr>
   </thead>
   <tbody>
       <tr *ngFor="let ab of printData">
           <td *ngIf="ab.Bill_Number">{{ab.Bill_Number}}</td>
           <td>.....</td>
           <td>.....</td>
       </tr>
   </tbody>
</table>
</code>```

答:
this case angular 6: </p>

```<code> underscore(selectkpi){
    this.selectedUnderKpi = selectkpi.replace(' ', '_');
    var a = this.selectedUnderKpi.
    console.log("ini = ",a);
  }
</code>```

Body:
I'm displaying array keys in header of a table and I have underscore in my keys. I want to replace underscore with space in html table. I do not want to do it in component as I have other requirements.

           {{header}}

           {{ab.Bill_Number}}
           .....
           .....

Body:
this case angular 6:

 underscore(selectkpi){
    this.selectedUnderKpi = selectkpi.replace(' ', '_');
    var a = this.selectedUnderKpi.
    console.log("ini = ",a);
  }


问:
How to replace parameter of a json file by a shell script?
Let's say 123.json with below content:

```<code>{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "76"
  }
}
</code>```

If I want to use a shell script to change the parameter of X_serial by the original number +1 which is 77 in this example.
I have tried the below script to take out the parameter of X_serial:

```<code>grep "X_serial" 123.json | awk {print"$3"}
</code>```

which outputs 76. But then I don't know how to make it into 77 and then put it back to the parameter of X_serial.

答:
You need to install powerful JSON querying processor like jq processor. you can can easily install from here

once you install jq processor, try following command to extract the variable from JSON key value

```<code>value=($(jq -r '.X_serial' yourJsonFile.json))
</code>```

you can modify the $value as you preferred operations

Body:
Let's say 123.json with below content:

{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "76"
  }
}

If I want to use a shell script to change the parameter of X_serial by the original number +1 which is 77 in this example.
I have tried the below script to take out the parameter of X_serial:

grep "X_serial" 123.json | awk {print"$3"}

which outputs 76. But then I don't know how to make it into 77 and then put it back to the parameter of X_serial.

Body:
You need to install powerful JSON querying processor like jq processor. you can can easily install from here

once you install jq processor, try following command to extract the variable from JSON key value

value=($(jq -r '.X_serial' yourJsonFile.json))

you can modify the $value as you preferred operations


问:
How to automatically mark through a quiz with jquery
I have been trying to write a code that automatically brings the answer to the summer of correct and incorrect options checked ??
Here is my code i tried looping through the whole question and nesting my loop to add 1 to sum if the option checked is correct</p>

```<code><!-- HTML CODE--->
<ol class="question">
  <li id="question1">
     <input type="radio" name="grp1" id="grp1" value="1"> Okeke </input>
     <input type="radio" name="grp1" id="grp1" value="0"> Lolaoluwa </input>
     <input type="radio" name="grp1" id="grp1" value="0"> Offisong </input>
     <input type="radio" name="grp1" id="grp1" value="0"> Offong </input>
  </li>
  <li id="question2">
    <input type="radio" name="grp2" id="grp2" value="1"> Marvellous </input>
    <input type="radio" name="grp2" id="grp2" value="1"> Johnpaul </input>
    <input type="radio" name="grp2" id="grp2" value="0"> Emmanuel </input>
    <input type="radio" name="grp2" id="grp2" value="0"> Abigail </input>
   </li>
   <li id="question3">
     <input type="radio" name="grp3" id="grp3" value="0"> Phoebe </input>
     <input type="radio" name="grp3" id="grp3" value="0"> Ross </input>
     <input type="radio" name="grp3" id="grp3" value="1"> Chandler </input>
     <input type="radio" name="grp3" id="grp3" value="0"> Joey </input>
   </li>
   <button onclick="box()" > Click me</button>
</ol>

 <!-- js CODE--->
function box() {
     var things $("ol.question li").eq(i);
     for (var i = 1; i < 3 ; i++) {
          $("ol.question li").eq(i);
                for (var j = 1 ; j < 4; j++){
                     var textNode = $("input[type='radio']").eq(j);
                 sum =0;
                   if(textNode.checked == true){
                       sum = sum + textNode.checked().value();
                       alert(sum);
                   }
               }
        }
     }
</code>```

答:
You need to traverse through
 and see which radio button is checked and compare its value with 1 if value is 1 increment sum+1 .

Demo code :

function box() {
  let sum = 0;
  //traverse through li-> radio button which is checked
  $('li input[type=radio]:checked').each(function() {
  //if value of checked is 1
    if ($(this).val() == 1) {
      sum = sum + 1; //increment sum
    }
  });
  //print on console
  console.log("Total score - " + sum)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="question">
  <li id="question1">
    <input type="radio" name="grp1" id="grp1" value="1" /> Okeke
    <input type="radio" name="grp1" id="grp1" value="0" /> Lolaoluwa
    <input type="radio" name="grp1" id="grp1" value="0" /> Offisong
    <input type="radio" name="grp1" id="grp1" value="0" /> Offong
  </li>
  <li id="question2">
    <input type="radio" name="grp2" id="grp2" value="1" /> Marvellous
    <input type="radio" name="grp2" id="grp2" value="1" /> Johnpaul
    <input type="radio" name="grp2" id="grp2" value="0" /> Emmanuel
    <input type="radio" name="grp2" id="grp2" value="0" /> Abigail
  </li>
  <li id="question3">
    <input type="radio" name="grp3" id="grp3" value="0" /> Phoebe
    <input type="radio" name="grp3" id="grp3" value="0" /> Ross
    <input type="radio" name="grp3" id="grp3" value="1" /> Chandler
    <input type="radio" name="grp3" id="grp3" value="0" /> Joey
  </li>
  <button onclick="box()"> Click me</button>
</ol></code>```

Body:
I have been trying to write a code that automatically brings the answer to the summer of correct and incorrect options checked ??
Here is my code i tried looping through the whole question and nesting my loop to add 1 to sum if the option checked is correct

     <input type="radio" name="grp1" id="grp1" value="1"> Okeke </input>
     <input type="radio" name="grp1" id="grp1" value="0"> Lolaoluwa </input>
     <input type="radio" name="grp1" id="grp1" value="0"> Offisong </input>
     <input type="radio" name="grp1" id="grp1" value="0"> Offong </input>

    <input type="radio" name="grp2" id="grp2" value="1"> Marvellous </input>
    <input type="radio" name="grp2" id="grp2" value="1"> Johnpaul </input>
    <input type="radio" name="grp2" id="grp2" value="0"> Emmanuel </input>
    <input type="radio" name="grp2" id="grp2" value="0"> Abigail </input>

     <input type="radio" name="grp3" id="grp3" value="0"> Phoebe </input>
     <input type="radio" name="grp3" id="grp3" value="0"> Ross </input>
     <input type="radio" name="grp3" id="grp3" value="1"> Chandler </input>
     <input type="radio" name="grp3" id="grp3" value="0"> Joey </input>

   <button onclick="box()" > Click me</button>

function box() {
     var things $("ol.question li").eq(i);
     for (var i = 1; i < 3 ; i++) {
          $("ol.question li").eq(i);
                for (var j = 1 ; j < 4; j++){
                     var textNode = $("input[type='radio']").eq(j);
                 sum =0;
                   if(textNode.checked == true){
                       sum = sum + textNode.checked().value();
                       alert(sum);
                   }
               }
        }
     }

Body:
You need to traverse through <li> and see which radio button is checked and compare its value with 1 if value is 1 increment sum+1 .

Demo code :

function box() {
  let sum = 0;
  //traverse through li-> radio button which is checked
  $('li input[type=radio]:checked').each(function() {
  //if value of checked is 1
    if ($(this).val() == 1) {
      sum = sum + 1; //increment sum
    }
  });
  //print on console
  console.log("Total score - " + sum)
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="question">
  <li id="question1">
    <input type="radio" name="grp1" id="grp1" value="1" /> Okeke
    <input type="radio" name="grp1" id="grp1" value="0" /> Lolaoluwa
    <input type="radio" name="grp1" id="grp1" value="0" /> Offisong
    <input type="radio" name="grp1" id="grp1" value="0" /> Offong
  </li>
  <li id="question2">
    <input type="radio" name="grp2" id="grp2" value="1" /> Marvellous
    <input type="radio" name="grp2" id="grp2" value="1" /> Johnpaul
    <input type="radio" name="grp2" id="grp2" value="0" /> Emmanuel
    <input type="radio" name="grp2" id="grp2" value="0" /> Abigail
  </li>
  <li id="question3">
    <input type="radio" name="grp3" id="grp3" value="0" /> Phoebe
    <input type="radio" name="grp3" id="grp3" value="0" /> Ross
    <input type="radio" name="grp3" id="grp3" value="1" /> Chandler
    <input type="radio" name="grp3" id="grp3" value="0" /> Joey
  </li>
  <button onclick="box()"> Click me</button>
</ol>


答:
How about:

```<code>df1.reindex(longweekend.index - pd.to_timedelta('1D')) ['open']
</code>```

You can also do fancy things like:

```<code>before_after = np.where(longweekend.Day=='Friday',
                        - pd.to_timedelta('1D'),     # Friday - day before
                        pd.to_timedelta('1D')        # Monday - day after
                        )

 df1.reindex(longweekend.index + before_after)['open']
</code>```

Title: Getting previous working days data from list of dates in pandas

Body:
I have the following dataframes:

longweekend
Out[20]:
               Day
Date
2011-04-22  Friday
2011-08-15  Monday
2011-11-07  Monday
2012-02-20  Monday
2012-04-06  Friday
           ...
2020-05-25  Monday
2020-10-02  Friday
2020-11-16  Monday
2020-11-30  Monday
2020-12-25  Friday

[63 rows x 1 columns]

And :

df1
Out[29]:
                   High          Low  ...      Volume    Adj Close
Date                                  ...
1999-12-31  1472.420044  1458.189941  ...   374050000  1469.250000
2000-01-03  1478.000000  1438.359985  ...   931800000  1455.219971
2000-01-04  1455.219971  1397.430054  ...  1009000000  1399.420044
2000-01-05  1413.270020  1377.680054  ...  1085500000  1402.109985
2000-01-06  1411.900024  1392.099976  ...  1092300000  1403.449951
                ...          ...  ...         ...          ...
2020-05-26  3021.719971  2988.169922  ...  5837060000  2991.770020
2020-05-27  3036.250000  2969.750000  ...  6371230000  3036.129883
2020-05-28  3068.669922  3023.399902  ...  5402670000  3029.729980
2020-05-29  3049.169922  2998.610107  ...  7275080000  3044.310059
2020-06-01  3062.179932  3031.540039  ...  2501351434  3055.729980

[5136 rows x 6 columns]

How can i get the open fromdf1 of the dates from longweekend 1 working day before. For example the first date in longweekend is 2011-04-22 thus what is the open value in df1 of 1 day before so thursday 2011-04-21. Or the next one where it is monday thus what is the value of open of Friday which is 2011-08-12

Body:
How about:

df1.reindex(longweekend.index - pd.to_timedelta('1D')) ['open']

You can also do fancy things like:

before_after = np.where(longweekend.Day=='Friday',
                        - pd.to_timedelta('1D'),     # Friday - day before
                        pd.to_timedelta('1D')        # Monday - day after
                        )

 df1.reindex(longweekend.index + before_after)['open']


问:
Dapper - Multi Mapping with a single return value
Below is the code I'm using to return a paged list of objects:

```<code>string query2 = @"
        select count(*) as TotalCount from blogposts p where p.Deleted = 0 and p.PublishDate <= @date
        select * from (
            select p.*,
            row_number() over(order by publishdate desc) as rownum
            from blogposts as p
            where p.Deleted = 0 and p.PublishDate <= @date
        ) seq
        where seq.rownum between @x and @y";

using (var cn = new SqlConnection(connectionString))
{
    cn.Open();
    using (var multi = cn.QueryMultiple(query2, new { x= lower, y = upper, date = DateTime.UtcNow }))
    {
        var totalCount = multi.Read<int>().Single();
        var posts = multi.Read<PostModel>().ToList();
        return new PagedList<PostModel>(posts, page, pageSize, x => totalCount);
    }
}
</code>```

Although this works, it means that I have to define my criteria twice, once for the count query and once for the resultset query. Rather than resort to string concatenation, I can execute just one query:

```<code>        string query = @"
                select * from (select p.*,
                row_number() over(order by publishdate desc) as rownum,
                count(*) over() as TotalCount
                from blogposts as p) seq
                where seq.rownum between @x and @y";
</code>```

However, I don't seem able to map this using Dapper. I can't use the same method as above because there aren't multiple results. I've tried using multi mapping but this expects to return an IEnumerable.

How would I map to the following?

```<code>    public class PostList
    {
        public IEnumerable<PostModel> Posts;
        public int TotalCount { get; set; }
    }
</code>```

Thanks

Ben

答:
Well ... you wouldn't ...

You would have to amend your PostModel to include a TotalCount property ... which is really ugly. Or execute a dynamic and remap it in a Select which is also ugly.

You see, you are returning count(*) N times with count(*) over() ... it is a hack, using this hack is not necessarily faster. I have measured it being slower than running a double query in some of my scenarios, in particular you can shortcut some indexes in the select count(*) since you are not selecting all the columns. Additionally the hack disables certain paging optimisations, for example you can not add select top N to the query.

My recommendation around paging queries would be to get indexing right, it is key. Measure perf and see if this hack actually helps (when the correct indexing is in place).

I follow about the concerns around string concatenation, but you can always define general helper methods for that.

Body:
Below is the code I'm using to return a paged list of objects:

string query2 = @"
        select count(*) as TotalCount from blogposts p where p.Deleted = 0 and p.PublishDate <= @date
        select * from (
            select p.*,
            row_number() over(order by publishdate desc) as rownum
            from blogposts as p
            where p.Deleted = 0 and p.PublishDate <= @date
        ) seq
        where seq.rownum between @x and @y";

using (var cn = new SqlConnection(connectionString))
{
    cn.Open();
    using (var multi = cn.QueryMultiple(query2, new { x= lower, y = upper, date = DateTime.UtcNow }))
    {
        var totalCount = multi.Read<int>().Single();
        var posts = multi.Read<PostModel>().ToList();
        return new PagedList<PostModel>(posts, page, pageSize, x => totalCount);
    }
}

Although this works, it means that I have to define my criteria twice, once for the count query and once for the resultset query. Rather than resort to string concatenation, I can execute just one query:

        string query = @"
                select * from (select p.*,
                row_number() over(order by publishdate desc) as rownum,
                count(*) over() as TotalCount
                from blogposts as p) seq
                where seq.rownum between @x and @y";

However, I don't seem able to map this using Dapper. I can't use the same method as above because there aren't multiple results. I've tried using multi mapping but this expects to return an IEnumerable.

How would I map to the following?

    public class PostList
    {
        public IEnumerable<PostModel> Posts;
        public int TotalCount { get; set; }
    }

Thanks

Ben


问:
React State with object
I am trying to update my state from my react dynamically, this is my current state.

```<code>this.state = {
      title: "",
      image: "",
      imageFile: "",
      formTitle: "",
      formMessage: "",
      formImage: "",
      Item: {
        name: "Name",
        price: "",
        quantity: "",
        discount: "",
        shipping: "",
        image: "",
        formType: ""
      }
    }
</code>```

How do I update in my Textbox dynamically instead of one by one?

```<code> setItemName = (name) => {
    this.setState({
      Item: {
        ...this.state.Item,
        name
      }
    });
  };
</code>```

this is my attempt at solving this

and this is my Textbox using material UI

```<code><TextField
                      className="my-24"
                      label="Item Name"
                      autoFocus
                      id="itemName"
                      name="itemName"
                      width={1}
                      value={this.state.Item.name}
                      onChange={this.setItemName}
                      variant="outlined"
                    />

</code>```

Thanks!!

答:
And nevermind,

I solve this,

This is my code for reference:

```<code>setItemValue = (field,value) => {
    console.log(field,value)
    this.setState(prevState => ({
      Item: {                   // object that we want to update
          ...prevState.Item,    // keep all other key-value pairs
          [field] : value       // update the value of specific key
      }
  }))
</code>```

Title: React State with object

Body:
I am trying to update my state from my react dynamically, this is my current state.

this.state = {
      title: "",
      image: "",
      imageFile: "",
      formTitle: "",
      formMessage: "",
      formImage: "",
      Item: {
        name: "Name",
        price: "",
        quantity: "",
        discount: "",
        shipping: "",
        image: "",
        formType: ""
      }
    }

How do I update in my Textbox dynamically instead of one by one?

 setItemName = (name) => {
    this.setState({
      Item: {
        ...this.state.Item,
        name
      }
    });
  };

this is my attempt at solving this

and this is my Textbox using material UI

<TextField
                      className="my-24"
                      label="Item Name"
                      autoFocus
                      id="itemName"
                      name="itemName"
                      width={1}
                      value={this.state.Item.name}
                      onChange={this.setItemName}
                      variant="outlined"
                    />

Thanks!!

Body:
And nevermind,

I solve this,

This is my code for reference:

setItemValue = (field,value) => {
    console.log(field,value)
    this.setState(prevState => ({
      Item: {                   // object that we want to update
          ...prevState.Item,    // keep all other key-value pairs
          [field] : value       // update the value of specific key
      }
  }))


答:
It's not a good idea to use line-oriented tools for parsing/manipulating JSON data. Use jq instead, for example:

```<code>$ jq '.LINE.X_serial |= "\(tonumber + 1)"' 123.json
{
  "LINE": {
    "A_serial": "1234",
    "B_serial": "2345",
    "C_serial": "3456",
    "X_serial": "77"
  }
}
</code>```

This simply updates .LINE.X_serial by converting its value to a number, increasing the result by one, and converting it back to a string.

Title: How to replace parameter of a json file by a shell script?

Body:
It's not a good idea to use line-oriented tools for parsing/manipulating JSON data. Use jq instead, for example:

$ jq '.LINE.X_serial |= "\(tonumber + 1)"' 123.json
{
  "LINE": {
    "A_serial": "1234",
    "B_serial": "2345",
    "C_serial": "3456",
    "X_serial": "77"
  }
}

This simply updates .LINE.X_serial by converting its value to a number, increasing the result by one, and converting it back to a string.


问:
Use Wordpress or another CMS within a web application?
Apologies for the broad question, but I don't know where to start. I have a php web application for members with various functions and features. On the dashboard, I need to implement some dynamic news - the kind of news that that non-developer can write and publish without any interference with the source code.

Can I implement Wordpress into my existing app so that authors can login, write then publish so that my dashboard can display the latest posts?

At its most basic level, I'm thinking:

a new subfolder for Wordpress with its own separate database.

a plugin to display the latest posts content only

an iframe on my dashboard to display the output of that plugin

But all that seems like a very hacky workaround. Is there a more native way of doing this? Or is there another CMS library that could achieve the same result?

答:
Looks like you want Dynamic News Feature in your existing PHP Web Application.
And you want to build that specific feature in Wordpress.

I don't think it's a good idea to use Wordpress CMS for small features like this.
IF you already have full functional PHP Web Application then I would recommend to use same Web Application to build Dynamic News Feature which will allow users on the site to post.
I don't think that's very complex.

IF you want to get into Wordpress ecosystem then you will need to convert your PHP Web Application into Wordpress and then you can build additional functionality.

I think that's the ideal way to go. Let me know if more questions. Thanks.


问:
Remove elements from 2d Numpy array based on a list
Thank you in advance for taking a look at my post.

I have a 2d np.array called actions with shape (2,x) which contains ints

I have another 1d np.array keys with elements of the same type to the first dimension of actions:  actions[0]. I want to remove from actions all array elements which are in keys. I tried diff = actions[:, not actions[0] == kids_keys]but it returns a 3d array of (1,2,x) shape.

How can I get a (2,x) diff array back ?

For example:

```<code>actions = [[121122, 211122, 221122, ... 455544, 545544][0, 0.35, 0.75, ... 1, -0.25]]
keys = [211122 221122]
# The operation I am looking for:
actions - keys = [[121122, ... 455544, 545544][0, ... 1, -0.25]]

</code>```

The error: The dimmentions of the diff array become (2,1,80) for some reason I dont know!

答:
The following will filter out columns of actions that have a first row entry in the set keys:

```<code>import numpy as np
x = 10
actions = np.random.randint(5, size=(2,x))
print(actions)
keys = np.array([1,2,3])
print(keys)
filtered_actions = actions[:,~np.sum([actions[0,:] == key for key in keys], dtype=bool, axis=0)]
print(filtered_actions)
</code>```

Body:
Thank you in advance for taking a look at my post.

I have a 2d np.array called actions with shape (2,x) which contains ints

I have another 1d np.array keys with elements of the same type to the first dimension of actions:  actions[0]. I want to remove from actions all array elements which are in keys. I tried diff = actions[:, not actions[0] == kids_keys]but it returns a 3d array of (1,2,x) shape.

How can I get a (2,x) diff array back ?

For example:

actions = [[121122, 211122, 221122, ... 455544, 545544][0, 0.35, 0.75, ... 1, -0.25]]
keys = [211122 221122]
# The operation I am looking for:
actions - keys = [[121122, ... 455544, 545544][0, ... 1, -0.25]]

The error: The dimmentions of the diff array become (2,1,80) for some reason I dont know!

Body:
The following will filter out columns of actions that have a first row entry in the set keys:

import numpy as np
x = 10
actions = np.random.randint(5, size=(2,x))
print(actions)
keys = np.array([1,2,3])
print(keys)
filtered_actions = actions[:,~np.sum([actions[0,:] == key for key in keys], dtype=bool, axis=0)]
print(filtered_actions)


问:
Passing argument to a flask GET function
I'm trying to write a simple messaging function and, despite searching, having trouble coming up with a workable solution. On the get function, the code retrieves stored messages and passes this to be rendered.

The post function stores the message which all works fine, however I'm trying to redirect the user back to the original page they came from to display the new message, hence trying to pass the receiving user variable to the get function.

My code so far below. I'm new to flask so would appreciate any other pointers as well. Thanks in advance!

```<code>@app.route("/messaging", methods=["GET", "POST"])
@login_required
def messaging():
    if request.method == "GET":

        clicked_user = request.args.get('user')
        messages = db.execute("SELECT * FROM messages WHERE (m_sending_user = :self_user AND m_receiving_user = :other_user) OR (m_sending_user = :other_user AND m_receiving_user = :self_user)",
                        self_user = session["user_id"],
                        other_user = clicked_user)

        return render_template("messaging.html", messages=messages, clicked_user=clicked_user)

    if request.method == "POST":

        receiving_user = request.form.get("recipient")

        db.execute("INSERT INTO messages (m_sending_user, m_receiving_user, message) VALUES (:m_sending_user, :m_receiving_user, :message)",
                        m_sending_user = session["user_id"],
                        m_receiving_user = receiving_user,
                        message = request.form.get("reply"))

        flash("Sent!")
        return render_template("messaging.html")
</code>```

答:
If you send data in GET request, it will be visible in URL parameter. Rather, you can use session object to store variable. More on session object can be found in the [official documentation on session object].(https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions)

You can use url_for with redirect method to redirect user to the original template.

Here I have shown a basic example:

messaging.html:

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Post request redirect</title>
  </head>
  <body>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}

    {% if clicked_user %}
      Clicked user: {{ clicked_user }}
    {% endif %}

    {% if messages %}
      Messages: {{ messages }}
    {% endif %}

    <h3>Send a Message</h3>
    <form action='{{url_for("messaging")}}' method="post">
      Recipient:
      <input type="text" name="recipient">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
</code>```

app.py:

```<code>from flask import Flask, render_template, redirect, url_for, session, request, flash

app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

@app.route("/messaging", methods=["GET", "POST"])
def messaging():
    if request.method == "GET":
        data = {
            "shovon": "some messages for shovon",
            "arsho": "other messages for arsho"
        }
        receiving_user = None
        messages = None
        if 'receiving_user' in session:
            receiving_user = session["receiving_user"]
        messages = data.get(receiving_user)
        return render_template("messaging.html", messages=messages, clicked_user=receiving_user)

    if request.method == "POST":
        receiving_user = request.form.get("recipient")
        session["receiving_user"] = receiving_user
        flash("Sent!")
        return redirect(url_for("messaging"))
</code>```

Output:

Before form submission:

After form submission:

N.B.: Here I have mocked the database queries with static dictionary search.

Body:
I'm trying to write a simple messaging function and, despite searching, having trouble coming up with a workable solution. On the get function, the code retrieves stored messages and passes this to be rendered.

The post function stores the message which all works fine, however I'm trying to redirect the user back to the original page they came from to display the new message, hence trying to pass the receiving user variable to the get function.

My code so far below. I'm new to flask so would appreciate any other pointers as well. Thanks in advance!

@app.route("/messaging", methods=["GET", "POST"])
@login_required
def messaging():
    if request.method == "GET":

        clicked_user = request.args.get('user')
        messages = db.execute("SELECT * FROM messages WHERE (m_sending_user = :self_user AND m_receiving_user = :other_user) OR (m_sending_user = :other_user AND m_receiving_user = :self_user)",
                        self_user = session["user_id"],
                        other_user = clicked_user)

        return render_template("messaging.html", messages=messages, clicked_user=clicked_user)

    if request.method == "POST":

        receiving_user = request.form.get("recipient")

        db.execute("INSERT INTO messages (m_sending_user, m_receiving_user, message) VALUES (:m_sending_user, :m_receiving_user, :message)",
                        m_sending_user = session["user_id"],
                        m_receiving_user = receiving_user,
                        message = request.form.get("reply"))

        flash("Sent!")
        return render_template("messaging.html")

Body:
If you send data in GET request, it will be visible in URL parameter. Rather, you can use session object to store variable. More on session object can be found in the [official documentation on session object].(https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions)

You can use url_for with redirect method to redirect user to the original template.

Here I have shown a basic example:

messaging.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Post request redirect</title>
  </head>
  <body>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}

    {% if clicked_user %}
      Clicked user: {{ clicked_user }}
    {% endif %}

    {% if messages %}
      Messages: {{ messages }}
    {% endif %}

    <h3>Send a Message</h3>
    <form action='{{url_for("messaging")}}' method="post">
      Recipient:
      <input type="text" name="recipient">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

app.py:

from flask import Flask, render_template, redirect, url_for, session, request, flash

app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

@app.route("/messaging", methods=["GET", "POST"])
def messaging():
    if request.method == "GET":
        data = {
            "shovon": "some messages for shovon",
            "arsho": "other messages for arsho"
        }
        receiving_user = None
        messages = None
        if 'receiving_user' in session:
            receiving_user = session["receiving_user"]
        messages = data.get(receiving_user)
        return render_template("messaging.html", messages=messages, clicked_user=receiving_user)

    if request.method == "POST":
        receiving_user = request.form.get("recipient")
        session["receiving_user"] = receiving_user
        flash("Sent!")
        return redirect(url_for("messaging"))

Output:

Before form submission:

After form submission:

N.B.: Here I have mocked the database queries with static dictionary search.


问:
It is possible to push a docker image inside a docker container?
I have a docker-in-docker container, which we'll call "dind". And a large image, which we'll call "LI".

Dind is responsible for make some docker runs calls. I need to run LI inside Dind. Normally, I push LI to a registry and pull it inside Dind. But I have a bad internet network. it takes a whole life to do this...

So, I was thinking if it is possible to push a docker image inside a docker container.

答:
you have a image A and you need to run an image B in image A (as per my understanding)
you have a bad network-

your docker file should look like:

from image A
  docker pull image B

build this image and keep it as Image C

Image C should be your image for all the run which already has the Image B updated.
Pull and Push Image when the connectivity is strong and you should be good.


问:
Gif inside button (HTML, CSS)
I am searching for a way to display/play a gif inside of a button.
The button should have a gif inside it, that starts playing on hover.</p>

答:
Well, you need to use CSS

```<code><style>
.button {
background: url('gifname.gif');
border: none;
background-repeat: no-repeat;
object-fit: cover;
}
</style>
<button class="button">
</code>```

I hope that solves your problem

Title: Gif inside button (HTML, CSS)

Body:
Well, you need to use CSS

<style>
.button {
background: url('gifname.gif');
border: none;
background-repeat: no-repeat;
object-fit: cover;
}
</style>
<button class="button">

I hope that solves your problem


问:
applying cache() and count() to Spark Dataframe in Databricks is very slow [pyspark]
I have a spark dataframe in Databricks cluster with 5 million rows. And what I want is to cache this spark dataframe and then apply .count() so for the next operations to run extremely fast. I have done it in the past with 20,000 rows and it works. However, in my trial to do this I came into the following paradox:

Dataframe creation

Step 1: Read 8 millions rows from Azure Data Lake storage account

read_avro_data=spark.read.format("avro").load(list_of_paths) #list_of_paths[0]='abfss://storage_container_name@storage_account_name.dfs.core.windows.net/folder_1/folder_2/0/2020/06/02/00/00/27.avro'
avro_decoded=read_avro_data.withColumn('Body_decoded', sql_function.decode(read_avro_data.Body, charset="UTF-8")).select("Body_decoded")
datalake_spark_dataframe=datalake_spark_dataframe.union(avro_decoded.withColumn("Body_decoded", sql_function.from_json("Body_decoded", schema)).select(*['Body_decoded.{}'.format(x) for x in columns_selected]))

datalake_spark_dataframe.printSchema()
"root
 |-- id: string (nullable = true)
 |-- BatteryPercentage: float (nullable = true)
 |-- SensorConnected: integer (nullable = false)
 |-- TemperatureOutside: float (nullable = true)
 |-- ReceivedOn: string (nullable = true)"

datalake_spark_dataframe.rdd.getNumPartitions() # 635 partitions
```

<p>This dataframe has 8 million rows. With 8 million rows my application runs pretty good, but I wanted to stress test my application in a big-data environment. Because 8 million rows is not Big-Data. Thus I replicated my 8 millions rows Spark Dataframe 287 times ~ 2.2 billion rows. To make the replication I did the following:</p>

<p><em>Step 2: Replicate the 8 million rows dataframe</em></p>

```datalake_spark_dataframe_new=datalake_spark_dataframe
for i in range(287):
  print(i)
  datalake_spark_dataframe_new=datalake_spark_dataframe_new.union(datalake_spark_dataframe)
  print("done on iteration: {0}".format(i))

datalake_spark_dataframe_new.rdd.getNumPartitions() #182880
```

<p>Having the final 2.2 billion rows dataframe, I made a time-window GroupBy of my data, ending up with some millions of rows. I have written approximately that the grouped dataset has 5 million rows in the top of my question.</p>

<p><em>Step 3: GroupBy the 2.2 billion rows dataframe by a time window of 6 hours & Apply the .cache() and .count()</em></p>

```%sql set spark.sql.shuffle.partitions=100
```

```import pyspark.sql.functions as sql_function
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatType, BooleanType, DateType, DoubleType, ArrayType

datalake_spark_dataframe_downsampled=datalake_spark_dataframe_new.withColumn(timestamp_column, sql_function.to_timestamp(timestamp_column, "yyyy-MM-dd HH:mm"))
datalake_spark_dataframe_downsampled=datalake_spark_dataframe_downsampled.groupBy("id", sql_function.window("ReceivedOn","{0} minutes".format(time_interval)))\
                                                                         .agg(
                                                                              sql_function.mean("BatteryPercentage").alias("BatteryPercentage"),
                                                                              sql_function.mean("SensorConnected").alias("OuterSensorConnected"),
                                                                              sql_function.mean("TemperatureOutside").alias("averageTemperatureOutside"))

columns_to_drop=['window']
datalake_spark_dataframe_downsampled=datalake_spark_dataframe_downsampled.drop(*columns_to_drop)

# From 2.2 billion rows down to 5 million rows after the GroupBy...
datalake_spark_dataframe_downsampled.repartition(100)
datalake_spark_dataframe_downsampled.cache()
datalake_spark_dataframe_downsampled.count() # job execution takes for ever

datalake_spark_dataframe_downsampled.rdd.getNumPartitions() #100 after re-partition
```

<p><em>Spark UI before showing the .count()</em>
<img src="https://i.stack.imgur.com/0Yxzc.png" alt="enter image description here"></p>

<p><em>Spark UI during the count execution</em>
<img src="https://i.stack.imgur.com/6PEm7.png" alt="enter image description here"></p>

<p>When I apply the following commands to my spark Dataframe it takes more than 3 hours to complete this task, which in the end fails.</p>

<p>I want to add that before and after the re-partitioning, the job had the same behavior in time execution. So, I did the re-partitioning in case the default values were making the job to run very slow. Thus, I was keep adding partitions in case the job would execute faster.</p>

<pre class="lang-py prettyprint-override"><code>%sql set spark.sql.shuffle.partitions=1000000
datalake_spark_dataframe_downsampled.repartition(1000000)

datalake_spark_dataframe_downsampled.cache()
datalake_spark_dataframe_downsampled.count()
</code>```

Below is the output of the spark job:

The error I get:

My cluster resources:

As you can see it's not a matter of RAM or CPU cores, as I have plenty of them.
Why the job splits only to 5 stages even after I apply re-partitioning? and How can I split the jobs so the .cache() and .count() commands run faster based on my 48 vCPU cores?

Screenshots provided per job execution
Execution on 80 million rows (8m * 10 iterations = 80m rows)

答:
I think you have used very huge shuffle partition number 1000000 that why it is taking more time to complete job.

I will follow below logic to calculate shuffle partition based on data size. for example

Say 5 millions of data is comes around 20 GB of data.

shuffle stage input = 20 GB

so total number of shuffle partitions are 20000MB/200MB = 100,

let assume only 50 cores in cluster in that case shuffle partition value is 50 or  200 cores in cluster in that case shuffle partition value will be 200.

Choosing high value as shuffle partition value there will be lot of shuffling data & hence task will take more time to complete or sometime it might fail.

spark.sql.shuffle.partitions=50 // 50 or 100 for better option.

Body:
I have a spark dataframe in Databricks cluster with 5 million rows. And what I want is to cache this spark dataframe and then apply .count() so for the next operations to run extremely fast. I have done it in the past with 20,000 rows and it works. However, in my trial to do this I came into the following paradox:

Dataframe creation

Step 1: Read 8 millions rows from Azure Data Lake storage account

read_avro_data=spark.read.format("avro").load(list_of_paths) #list_of_paths[0]='abfss://storage_container_name@storage_account_name.dfs.core.windows.net/folder_1/folder_2/0/2020/06/02/00/00/27.avro'
avro_decoded=read_avro_data.withColumn('Body_decoded', sql_function.decode(read_avro_data.Body, charset="UTF-8")).select("Body_decoded")
datalake_spark_dataframe=datalake_spark_dataframe.union(avro_decoded.withColumn("Body_decoded", sql_function.from_json("Body_decoded", schema)).select(*['Body_decoded.{}'.format(x) for x in columns_selected]))

datalake_spark_dataframe.printSchema()
"root
 |-- id: string (nullable = true)
 |-- BatteryPercentage: float (nullable = true)
 |-- SensorConnected: integer (nullable = false)
 |-- TemperatureOutside: float (nullable = true)
 |-- ReceivedOn: string (nullable = true)"

datalake_spark_dataframe.rdd.getNumPartitions() # 635 partitions

This dataframe has 8 million rows. With 8 million rows my application runs pretty good, but I wanted to stress test my application in a big-data environment. Because 8 million rows is not Big-Data. Thus I replicated my 8 millions rows Spark Dataframe 287 times ~ 2.2 billion rows. To make the replication I did the following:

Step 2: Replicate the 8 million rows dataframe

datalake_spark_dataframe_new=datalake_spark_dataframe
for i in range(287):
  print(i)
  datalake_spark_dataframe_new=datalake_spark_dataframe_new.union(datalake_spark_dataframe)
  print("done on iteration: {0}".format(i))

datalake_spark_dataframe_new.rdd.getNumPartitions() #182880

Having the final 2.2 billion rows dataframe, I made a time-window GroupBy of my data, ending up with some millions of rows. I have written approximately that the grouped dataset has 5 million rows in the top of my question.

Step 3: GroupBy the 2.2 billion rows dataframe by a time window of 6 hours & Apply the .cache() and .count()

%sql set spark.sql.shuffle.partitions=100

import pyspark.sql.functions as sql_function
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatType, BooleanType, DateType, DoubleType, ArrayType

datalake_spark_dataframe_downsampled=datalake_spark_dataframe_new.withColumn(timestamp_column, sql_function.to_timestamp(timestamp_column, "yyyy-MM-dd HH:mm"))
datalake_spark_dataframe_downsampled=datalake_spark_dataframe_downsampled.groupBy("id", sql_function.window("ReceivedOn","{0} minutes".format(time_interval)))\
                                                                         .agg(
                                                                              sql_function.mean("BatteryPercentage").alias("BatteryPercentage"),
                                                                              sql_function.mean("SensorConnected").alias("OuterSensorConnected"),
                                                                              sql_function.mean("TemperatureOutside").alias("averageTemperatureOutside"))

columns_to_drop=['window']
datalake_spark_dataframe_downsampled=datalake_spark_dataframe_downsampled.drop(*columns_to_drop)

# From 2.2 billion rows down to 5 million rows after the GroupBy...
datalake_spark_dataframe_downsampled.repartition(100)
datalake_spark_dataframe_downsampled.cache()
datalake_spark_dataframe_downsampled.count() # job execution takes for ever

datalake_spark_dataframe_downsampled.rdd.getNumPartitions() #100 after re-partition

Spark UI before showing the .count()

Spark UI during the count execution

When I apply the following commands to my spark Dataframe it takes more than 3 hours to complete this task, which in the end fails.

I want to add that before and after the re-partitioning, the job had the same behavior in time execution. So, I did the re-partitioning in case the default values were making the job to run very slow. Thus, I was keep adding partitions in case the job would execute faster.

%sql set spark.sql.shuffle.partitions=1000000
datalake_spark_dataframe_downsampled.repartition(1000000)

datalake_spark_dataframe_downsampled.cache()
datalake_spark_dataframe_downsampled.count()

Below is the output of the spark job:

The error I get:

My cluster resources:

As you can see it's not a matter of RAM or CPU cores, as I have plenty of them.
Why the job splits only to 5 stages even after I apply re-partitioning? and How can I split the jobs so the .cache() and .count() commands run faster based on my 48 vCPU cores?

Screenshots provided per job execution
Execution on 80 million rows (8m * 10 iterations = 80m rows)


问:
Updated pip successfully, but got an error message after
Recently updated pip from 20.1 to 20.1.1. It all went well except for some reason I got an error message after it. I ran pip --version to see if it was changed to 20.1.1 and it did. Should I be concerned about the error message though? I'm on Windows 10 if that makes any difference.

```<code>
C:\Users\Isabella>pip install --upgrade pip
Collecting pip
  Downloading pip-20.1.1-py2.py3-none-any.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 726 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1
    Uninstalling pip-20.1:
      Successfully uninstalled pip-20.1
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\Isabella\\AppData\\Local\\Temp\\pip-uninstall-8mkzjz1n\\pip.exe'
Consider using the `--user` option or check the permissions.

C:\Users\Isabella>pip --version
pip 20.1.1 from c:\users\isabella\appdata\local\programs\python\python38\lib\site-packages\pip (python 3.8)
</code>```

EDIT: Tried doing it with --user and it said it was already up-to-date, so I guess there's nothing to worry about? Thanks for the replies.

答:
Welcome to Stack Overflow!
If you read the outputs closely, it says :

ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\Isabella\\AppData\\Local\\Temp\\pip-uninstall-8mkzjz1n\\pip.exe'
Consider using the "--user" option or check the permissions.

 Access is denied

and

 Consider using the "--user" option or check the permissions.

or you could try upgrading pip inside a virtualenv and let us know how it goes! :) goodluck!

Body:
Recently updated pip from 20.1 to 20.1.1. It all went well except for some reason I got an error message after it. I ran pip --version to see if it was changed to 20.1.1 and it did. Should I be concerned about the error message though? I'm on Windows 10 if that makes any difference.

C:\Users\Isabella>pip install --upgrade pip
Collecting pip
  Downloading pip-20.1.1-py2.py3-none-any.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 726 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1
    Uninstalling pip-20.1:
      Successfully uninstalled pip-20.1
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\Isabella\\AppData\\Local\\Temp\\pip-uninstall-8mkzjz1n\\pip.exe'
Consider using the `--user` option or check the permissions.

C:\Users\Isabella>pip --version
pip 20.1.1 from c:\users\isabella\appdata\local\programs\python\python38\lib\site-packages\pip (python 3.8)

EDIT: Tried doing it with --user and it said it was already up-to-date, so I guess there's nothing to worry about? Thanks for the replies.


问:
Django: Static files are not found
I'm trying to add some static files to my project. I have tried adding a static folder to my app.

I have two apps:

Authentication (authn),

Main (main).

I have a lot of CSS/js content and I don't really know which is the best method to save the files, maybe all static files should be in one directory 'staticfiles' or each app should have 'static' folder. I have tried adding static folder to one of my apps, at this time - authn. And by trying to load the static files I firstly did python manage.py collectstatic, that put my all files into one folder, but I got two different folders now - admin, main. After tried putting all my static files into a static folder in authn app, but the static files were not loading after that. Here are my project structure and some photos and logs of the console, pycharm.

答:
make static folder outside the app

inside static create two folder main and auth

inside main and auth create css js img and another catagories of folder

Put each app's static file into their folder.That is put main app's css into static/main/css/main.css like that

In settings.py make some changes-

```<code> BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
</code>```

STATICFILES_DIRS = [  os.path.join(BASE_DIR, "static"), ]

Title: Django: Static files are not found

Body:
make static folder outside the app

inside static create two folder main and auth

inside main and auth create css js img and another catagories of folder

Put each app's static file into their folder.That is put main app's css into static/main/css/main.css like that

In settings.py make some changes-

 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'

STATICFILES_DIRS = [  os.path.join(BASE_DIR, "static"), ]


问:
Changing AWS configuration directory
AWS stores the default configuration files in ~/.aws/.

I'm trying to have all hidden directories inside ~/.config/, and would like to change the default location to ~/.config/aws/

How would I do this from the AWS CLI?

答:
Custom locations for config and credentials files can be specified using two environment variables:

AWS_CONFIG_FILE: Specifies the location of the file that the AWS CLI uses to store configuration profiles. The default path is ~/.aws/config.

AWS_SHARED_CREDENTIALS_FILE: Specifies the location of the file that the AWS CLI uses to store access keys. The default path is ~/.aws/credentials.

Title: Changing AWS configuration directory


问:
split string into groups with given condition
Given a String only made of only 2 letters a,b. Now the task is to split this string into exactly 3 groups such that the number of a's in each group must be same. Then find how many such groups are possible.

Example:

```<code>Input:
ababab

Possiblities:
ab ab ab

Output:
1 as we can create only 1 such group, with single a in each group
</code>```

Example:

```<code>Input:
ababbabbaaba

Possiblities:

aba bbabba aba
abab babba aba
ababb abba aba

Output:3
as we can create 3 such possible groups with 2 a's in each group.
</code>```

Now I came across below code that is solving this task.

```<code>public static int findGroups(String input) {
    int numberOfAs = 0;
    for (int i = 0; i < input.length(); i++) {
        if (input.charAt(i) == 'a')
            numberOfAs++;
    }
    int n = input.length();
    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

    if (numberOfAs % 3 != 0)
        return 0;

    int numberOfAsInAGroup = numberOfAs / 3;

    int lastAIn1stGroup = 0; // last occurrence of A in 1st group
    int firstAIn2ndGroup = 0; // 1st occurrence of A in 2nd group
    int lastAIn2ndGroup = 0; // last occurrence of A in 2nd group
    int firstAIn3rdGroup = 0; // 1st occurrence of A in 3rd group
    int aCount = 0;
    for (int i = 0; i < n; i++) {
        if (input.charAt(i) == 'a') {
            aCount++;
            if (aCount == numberOfAsInAGroup) {
                lastAIn1stGroup = i;
            } else if (aCount == numberOfAsInAGroup + 1) {
                firstAIn2ndGroup = i;
            }
            if (aCount == 2 * numberOfAsInAGroup) {
                lastAIn2ndGroup = i;
            } else if (aCount == 2 * numberOfAsInAGroup + 1) {
                firstAIn3rdGroup = i;
                break;
            }
        }
    }

    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;
}
</code>```

This code is working perfectly finw without any errors. But I am trying to understand for past several days what formulas are being used in this code to solve this task.

Part - 1:

```<code>    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }
</code>```

After searching in google for several hrs I found the explanation here  - number-of-ways-of-distributing-n-identical-objects-among-r-groups:

Part - 2:

```<code>    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;
</code>```

I am not able to understand this part 2 formula, how this is solving the given problem, is there any explanation as mentioned for part 1.

Also just curious to know, is there any alternate version to solve this task without using formulas like this?

答:
It can be done in linear time.

```<code>public class Main {

    public static int Nth_A_After(String s, int n, int index){
        for(int i = index + 1; i < s.length(); i++) {
            if(s.charAt(i) == 'a'){
                n--;
                if(n == 0) return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        String s = "ababab";

        int count = 0;

        for(int i = 0; i < s.length(); i++) if(s.charAt(i) == 'a') count++;

        if(count % 3 != 0) {
            System.out.println("Impossible!");
            return;
        }

        int pos = count / 3;

        int firstEnd = Nth_A_After(s, pos, -1);
        int secondBegin = Nth_A_After(s, 1, firstEnd);
        int secondEnd = Nth_A_After(s, pos - 1, secondBegin);
        int thirdBegin = Nth_A_After(s, 1, secondEnd);

        int leftDif = secondBegin - firstEnd;
        int rightDif = thirdBegin - secondEnd;
        if(leftDif > 1) leftDif++;
        if(rightDif > 1) rightDif++;

        System.out.println(leftDif * rightDif);
    }
}
</code>```

I guess there is a problem in your example ababab, since there is more than just one possibility:

```<code>1. a ba bab
2. a bab ab
3. ab a bab
4. ab ab ab
</code>```

Body:
Given a String only made of only 2 letters a,b. Now the task is to split this string into exactly 3 groups such that the number of a's in each group must be same. Then find how many such groups are possible.

Example:

Input:
ababab

Possiblities:
ab ab ab

Output:
1 as we can create only 1 such group, with single a in each group

Example:

Input:
ababbabbaaba

Possiblities:

aba bbabba aba
abab babba aba
ababb abba aba

Output:3
as we can create 3 such possible groups with 2 a's in each group.

Now I came across below code that is solving this task.

public static int findGroups(String input) {
    int numberOfAs = 0;
    for (int i = 0; i < input.length(); i++) {
        if (input.charAt(i) == 'a')
            numberOfAs++;
    }
    int n = input.length();
    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

    if (numberOfAs % 3 != 0)
        return 0;

    int numberOfAsInAGroup = numberOfAs / 3;

    int lastAIn1stGroup = 0; // last occurrence of A in 1st group
    int firstAIn2ndGroup = 0; // 1st occurrence of A in 2nd group
    int lastAIn2ndGroup = 0; // last occurrence of A in 2nd group
    int firstAIn3rdGroup = 0; // 1st occurrence of A in 3rd group
    int aCount = 0;
    for (int i = 0; i < n; i++) {
        if (input.charAt(i) == 'a') {
            aCount++;
            if (aCount == numberOfAsInAGroup) {
                lastAIn1stGroup = i;
            } else if (aCount == numberOfAsInAGroup + 1) {
                firstAIn2ndGroup = i;
            }
            if (aCount == 2 * numberOfAsInAGroup) {
                lastAIn2ndGroup = i;
            } else if (aCount == 2 * numberOfAsInAGroup + 1) {
                firstAIn3rdGroup = i;
                break;
            }
        }
    }

    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;
}

This code is working perfectly finw without any errors. But I am trying to understand for past several days what formulas are being used in this code to solve this task.

Part - 1:

    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

After searching in google for several hrs I found the explanation here  - number-of-ways-of-distributing-n-identical-objects-among-r-groups:

Part - 2:

    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;

I am not able to understand this part 2 formula, how this is solving the given problem, is there any explanation as mentioned for part 1.

Also just curious to know, is there any alternate version to solve this task without using formulas like this?

Body:
It can be done in linear time.

public class Main {

    public static int Nth_A_After(String s, int n, int index){
        for(int i = index + 1; i < s.length(); i++) {
            if(s.charAt(i) == 'a'){
                n--;
                if(n == 0) return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        String s = "ababab";

        int count = 0;

        for(int i = 0; i < s.length(); i++) if(s.charAt(i) == 'a') count++;

        if(count % 3 != 0) {
            System.out.println("Impossible!");
            return;
        }

        int pos = count / 3;

        int firstEnd = Nth_A_After(s, pos, -1);
        int secondBegin = Nth_A_After(s, 1, firstEnd);
        int secondEnd = Nth_A_After(s, pos - 1, secondBegin);
        int thirdBegin = Nth_A_After(s, 1, secondEnd);

        int leftDif = secondBegin - firstEnd;
        int rightDif = thirdBegin - secondEnd;
        if(leftDif > 1) leftDif++;
        if(rightDif > 1) rightDif++;

        System.out.println(leftDif * rightDif);
    }
}

I guess there is a problem in your example ababab, since there is more than just one possibility:

1. a ba bab
2. a bab ab
3. ab a bab
4. ab ab ab


答:
As I understand from your doubt, you want to change the fields in state dynamically instead of writing the functions one by one....

```<code>setItemName = (changedValue, type) => {
  this.setState({
    Item: {
      ...this.state.Item,
      [type]: changedValue
    }
  });
};
</code>```

And your TextField going to be...

```<code><TextField
  className="my-24"
  label="Item Name"
  autoFocus
  id="itemName"
  name="itemName"
  width={1}
  value={this.state.Item.name}
  onChange={(changedValue) => this.setItemName(changedValue, 'name')}
  variant="outlined"
/>
</code>```

You just need to pass the state field name in the setItemName argument.
As for 'price' you need to write setItemName(changedValue, 'price')

Title: React State with object

Body:
As I understand from your doubt, you want to change the fields in state dynamically instead of writing the functions one by one....

setItemName = (changedValue, type) => {
  this.setState({
    Item: {
      ...this.state.Item,
      [type]: changedValue
    }
  });
};

And your TextField going to be...

<TextField
  className="my-24"
  label="Item Name"
  autoFocus
  id="itemName"
  name="itemName"
  width={1}
  value={this.state.Item.name}
  onChange={(changedValue) => this.setItemName(changedValue, 'name')}
  variant="outlined"
/>

You just need to pass the state field name in the setItemName argument.
As for 'price' you need to write setItemName(changedValue, 'price')