问:
Python 3 prettify result
How i can prettify scrapped result (from requests and BS4), remove slashes etc.

Now result looks like:

data-ft=\"{"top_level_post_id":"1396169803805852","tl_objid":"1396169803805852","throwback_story_fbid":"1396169803805852","page_id":"126721934083985"}\"
  id=\"u_0_1\" data-sigil=\"story-div story-popup-metadata
  story-popup-metadata feed-ufi-metadata\">\u003Cdiv
  data-sigil=\"m-feed-story-attachments-element\">\u003Cheader
  class=\"_4g33 _5qc1\">\u003Cdiv class=\"_5s61 _2pii _5i2i
  _52wc\">\u003Cdiv class=\"_5xu4\">\u003Ca class=\"_4prr\" href=\"/tjournal/?tn=\u00257E\"
  data-gt=\"{"tn":"~"}\">\u003Ci class=\"img profpic\"
  aria-label=\"TJournal\" role=\"img\" style=\"background:#d8dce6
  url("https://scontent.fhen1-1.fna.fbcdn.net/v/t1.0-1/cp0/e15/q65/p40x40/10419386_796086753814163_5610346145298574316_n.jpg?

My code:

```<code>r = requests.get('https://m.facebook.com/pages_reaction_units/more/?page_id=126721934083985&cursor={%22timeline_cursor%22:%22page_photos%22,%22timeline_section_cursor%22:null,%22has_next_page%22:true}&surface=mobile_page_home&unit_count=3', headers=headers)

res = r.content.decode()
soup = BeautifulSoup(res, 'lxml')
print(soup.prettify())
</code>```

答:
We can define custom formatter and pass it to BeautifulSoup.prettify method (in your case there's the problem with unicode escaping, got solution from here):

```<code>import requests

from bs4 import BeautifulSoup

r = requests.get('https://m.facebook.com/pages_reaction_units/more/?page_id=126721934083985&cursor={%22timeline_cursor%22:%22page_photos%22,%22timeline_section_cursor%22:null,%22has_next_page%22:true}&surface=mobile_page_home&unit_count=3')

def formatter(string):
    formatted = bytes(string, 'ascii').decode('unicode-escape')
    # for Python 2
    # formatted = string.decode('unicode-escape')
    return formatted

res = r.content.decode()
soup = BeautifulSoup(res, 'lxml')
print(soup.prettify(formatter=formatter))
</code>```

gives us

```<code><html>
 <body>
  <p>
   for (;;);{"actions":[{"cmd":"replace","target":"m_pages_reaction_see_more_unit","html":"<div class="_3-8x"><div class="_55wo _gui" id="unit_id_688092377989036"><div><div class="_3w7e"><div class="_55wo _56bf _5rgl" data-ft="{"top_level_post_id":"1396231463799686","tl_objid":"1396231463799686","page_id":"126721934083985"}" id="u_0_4"><div><h3 class="_52ja _52jh"><span><strong><a href="\/tjournal\/?__tn__=C">TJournal<\/a><\/strong><\/span><\/h3><div class="_5rgn" style=""><span><p>В московском метро оператор Wi-Fi объяснил наличие рекламы шутками про котят и гимнастику для глаз.<\/p><\/span><\/div><div class="_5rgo _27x0"><a class="_5tip _5tfq" href="https:\/\/lm.facebook.com\/l.php?u=https%3A%2F%2Fvc.ru%2Fp%2Fmosmetro-wifi&h=ATOEzvb7duNxYzFzO8Y_WNBP24h3OXswMOwrGBf1UOpOgSMNW0A8saNQTZxNVw2_hzp3bRyNC8rInRxtEbxx5ubADIB0GFnFadbwXzCKOCSq2k66bzaM2H-XTN8Y&enc=AZPdwIbpMFV3FWXB3fcldNTj5RGMsvmR3tL1UhSg7fx6yOErLQUUIu5_DtOs5sw7v7oUxaeuc7rfgXDJ66XN1n68KN53bmSqkpFfSTTOJK650QG9uJPCNnlHZJl0zgV5OIn1nwpLZfkxn2WHCFb9z5DpTz3k-hXMYvBg9Di00D1Wqg&s=1" id="u_0_5" target="_blank"><div class="_59e9 _55wr _5til"><table class="_4g33 _52wc"><tbody><tr><td class="_5s61 _3lsd"><img src="https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQCYmQ6aqZ7CRrUU&w=149&h=149&url=https%3A%2F%2Fvc.ru%2Fcover%2F24313%2Ffb%2Fcover.jpg&cfs=1&jq=75&ext=jpg&_nc_hash=AQCFGypsajWMdGm0" width="112" height="112" class="img" \/><\/td><td class="_4g34"><h1 class="_52jd _52jh _ing">«В мире успеет родиться 273 котёнка»: оператор Wi-Fi в московском метро решил объяснить наличие рекламы шуточными цитатами<\/h1><div class="_52jc _2b-u">vc.ru<div class="_52jc"><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/a><\/div><\/div><div class="_5sq4"><div class="mfss fcg"><abbr>27 мин<\/abbr><span> · <\/span><span class="_26zb"><span><span class="mfss">Доступно всем<\/span><\/span><\/span><\/div><div class="mfss fcg"><a href="\/story.php?story_fbid=1396231463799686&id=126721934083985#footer_action_list">Новость целиком<\/a><\/div><\/div><\/div><\/div><\/div><\/div><div class="_55wo _gui" id="unit_id_688092377989036"><div><div class="_3w7e"><div class="_55wo _56bf _5rgl" data-ft="{"top_level_post_id":"1396169803805852","tl_objid":"1396169803805852","page_id":"126721934083985"}" id="u_0_0"><div><h3 class="_52ja _52jh"><span><strong><a href="\/tjournal\/?__tn__=C">TJournal<\/a><\/strong><\/span><\/h3><div class="_5rgn" style=""><span><p>iOS 11, выходящая осенью, не поддерживает 32-битные приложения. Это значит, что пользователи потеряют доступ примерно к 200 тысячам программ. <\/p><p> Включая оригинальную Flappy Bird.<\/p><\/span><\/div><div class="_5rgo _27x0"><a class="_5tip _5tfq" href="https:\/\/lm.facebook.com\/l.php?u=https%3A%2F%2Fdtf.ru%2F7120-kak-uznat-kakie-prilozheniya-perestanut-rabotat-v-ios-11&h=ATPDoxCwMQLom_0MvLZd0sk90kReFLK9MtPs-flcXUdNA2IWlIuKBfnHqSQbNpveb8dW6gC32vxQCRtmUtBZQuy06LVxmW-gjvdi6C971XUvVhuyRCWlOdDWvgdj&enc=AZOcj4YClTNdw0ZHVMWhll-L-jVGpHnNtuLk9Su1t1GT4KnnMguG1EukLu57simsZJkFgnqQssiyu-wNtVVbXPYCIcVuYCfOcxWyWZs2j3gtpTJctaVpbpUlV4Na-zOn2PqlP8IqxHlC4uTH0jxH2qszc5trX-cCA-Mu5kuT2BDqeQ&s=1" id="u_0_1" target="_blank"><div class="_59e9 _55wr _5til"><table class="_4g33 _52wc"><tbody><tr><td class="_5s61 _3lsd"><img src="https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQAgAf90LRsVJMNs&w=149&h=149&url=https%3A%2F%2Fdtf.ru%2Fcover%2F7120%2Ffb%2Fcover.jpg&cfs=1&jq=75&ext=jpg&_nc_hash=AQAREWDHqfZjs47i" width="112" height="112" class="img" \/><\/td><td class="_4g34"><h1 class="_52jd _52jh _ing">Как узнать, какие приложения перестанут работать в iOS 11<\/h1><div class="_52jc _2b-u">dtf.ru<div class="_52jc"><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/a><\/div><\/div><div class="_5sq4"><div class="mfss fcg"><abbr>1 ч<\/abbr><span> · <\/span><span class="_26zb"><span><span class="mfss">Доступно всем<\/span><\/span><\/span><\/div><div class="mfss fcg"><a href="\/story.php?story_fbid=1396169803805852&id=126721934083985#footer_action_list">Новость целиком<\/a><\/div><\/div><\/div><\/div><\/div><\/div><div class="_55wo _gui" id="unit_id_688092377989036"><div><div class="_3w7e"><div class="_55wo _56bf _5rgl" data-ft="{"top_level_post_id":"1396120047144161","tl_objid":"1396120047144161","page_id":"126721934083985"}" id="u_0_2"><div><h3 class="_52ja _52jh"><span><strong><a href="\/tjournal\/?__tn__=C">TJournal<\/a><\/strong><\/span><\/h3><div class="_5rgn" style=""><span><p>«Когда я начал писать песни, я использовал единственный лексикон, которым владел, — народный говор».<\/p><p> Боб Дилан спустя полгода молчания всё же записал свою нобелевскую лекцию и прислал её по почте. В ней он рассказал о трёх книгах, изменивших его жизнь, и песнях, вдохновивших его на творчество.<\/p><\/span><\/div><div class="_5rgo _27x0"><a class="_5tip _5tfq" href="https:\/\/lm.facebook.com\/l.php?u=https%3A%2F%2Ftjournal.ru%2F45066-nashi-pesni-zhivi-na-zemle-zhivih&h=ATPEMvJ7GQTe04oluO0JF3NLS22d-lRvx6KKD66V_nqi9fsI1IXKolS42cYwhhi84uwDJNdjx2guKZGZLG1tDdU2Z8hdcEJCAPOhvNmzbYCQVFb1jYIQSDbGzDxe&enc=AZNVVbLvwHAh7vlAmvmJ1MPucduzaj6RF3CqoH-RDxZsiY929_44hm3bFI9T3qviVsZH4m2uipObgAZC7o8Mi2TuSW3sCSJLDDM87FFtr_ykoSiHSVoe6dJ6Ofp_Ccdp9ZC1awnV8G5hk2y7mslIMKmDu5V6HVbYuJil4PPv3nkqqw&s=1" id="u_0_3" target="_blank"><div class="_59e9 _55wr _5til"><table class="_4g33 _52wc"><tbody><tr><td class="_5s61 _3lsd"><img src="https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQAfW-DGqBho4DTZ&w=149&h=149&url=https%3A%2F%2Fgif.cmtt.space%2F3%2Fclub%2F04%2F44%2Fea%2F9a32486b17242f.jpg&cfs=1&jq=75&sx=186&sy=0&sw=847&sh=847&ext=jpg&_nc_hash=AQDaECn9dkAl-dAu" width="112" height="112" class="img" \/><\/td><td class="_4g34"><h1 class="_52jd _52jh _ing">«Наши песни живы на земле живых»<\/h1><div class="_52jc _2b-u">tjournal.ru<div class="_52jc"><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/a><\/div><\/div><div class="_5sq4"><div class="mfss fcg"><abbr>2 ч<\/abbr><span> · <\/span><span class="_26zb"><span><span class="mfss">Доступно всем<\/span><\/span><\/span><\/div><div class="mfss fcg"><a href="\/story.php?story_fbid=1396120047144161&id=126721934083985#footer_action_list">Новость целиком<\/a><\/div><\/div><\/div><\/div><\/div><\/div><div class="apm" id="m_pages_reaction_see_more_unit"><a href="\/pages_reaction_units\/more\/?page_id=126721934083985&cursor=%7B%22timeline_cursor%22%3A%22timeline_unit%3A1%3A00000000001496760847%3A04611686018427387904%3A09223372036854775805%3A04611686018427387904%22%2C%22timeline_section_cursor%22%3A%7B%7D%2C%22has_next_page%22%3Atrue%7D&surface=mobile_page_home&unit_count=3"><span>Еще<\/span><\/a><\/div><\/div>","replaceifexists":false,"allownull":false}],"css_hashes":["3HuCe","B4neB","UZuNp","9WMeb","xf2NL","9cXdw","JlaHi","QOT77","i6YK6","dkD1x","hInrP","PZ1UP","RnoEd","ol6iG","gfKii","1PJ9n","9U1Wz","IF96k"],"inline_css":"._4qba{font-style:normal}._4qbb,._4qbc,._4qbd{background:none;font-style:normal;padding:0;width:auto}._4qbd{border-bottom:1px solid #f99}._4qbb,._4qbc{border-bottom:1px solid #999}._4qbb:hover,._4qbc:hover,._4qbd:hover{background-color:#fcc;border-top:1px solid #ccc;cursor:help}
._3-8h{margin:4px}._3-8i{margin:8px}._3-8j{margin:12px}._3-8k{margin:16px}._3-8l{margin:20px}._3-8m{margin-bottom:4px;margin-top:4px}._3-8n{margin-bottom:8px;margin-top:8px}._3-8o{margin-bottom:12px;margin-top:12px}._3-8p{margin-bottom:16px;margin-top:16px}._3-8q{margin-bottom:20px;margin-top:20px}._3-8r{margin-left:4px;margin-right:4px}._3-8s{margin-left:8px;margin-right:8px}._3-8t{margin-left:12px;margin-right:12px}._3-8u{margin-left:16px;margin-right:16px}._3-8v{margin-left:20px;margin-right:20px}._3-8w{margin-top:4px}._3-8x{margin-top:8px}._3-8y{margin-top:12px}._3-8z{margin-top:16px}._3-8-{margin-top:20px}._3-8_{margin-right:4px}._3-90{margin-right:8px}._3-91{margin-right:12px}._3-92{margin-right:16px}._3-93{margin-right:20px}._3-94{margin-bottom:4px}._3-95{margin-bottom:8px}._3-96{margin-bottom:12px}._3-97{margin-bottom:16px}._3-98{margin-bottom:20px}._3-99{margin-left:4px}._3-9a{margin-left:8px}._3-9b{margin-left:12px}._3-9c{margin-left:16px}._3-9d{margin-left:20px}
._gui{border-bottom:1px solid #bec2c9;border-top:1px solid #ccc;display:block;margin:0 0 8px}._3g-o{display:block;margin:8px 0}html ._5tp0{display:block;margin:auto;max-height:32px;max-width:32px}.nontouch td._1r7u{padding-left:4px}._17lh{color:#4b4f56;display:block;font-size:12px;line-height:16px;max-height:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}._17li{display:inline-block;font-size:12px;line-height:16px;vertical-align:middle}._3w7e{position:relative}._3w7f{position:absolute;right:28px;top:0}._j5t{padding:6px 0}._j5t textarea{resize:none}._4bdb{width:320px}._4bdc{padding:4px 0}
._59e9{background:#f6f7f9}._55wm{background:#dddfe2}._5s6y{background:#000}._55wn{background:#4080ff}._55wo{background:#fff}._5oxw{background:#e9ebee}._50zt{background:#e9eaed}._25sz{background:#ff7f50}
._5rgl{margin:0 6px 6px;padding:6px}._gdx{margin:0 0 6px}.nontouch ._5rgl ._5rgl{border-color:#e9ebee;margin:6px 0 0}._5rgm{color:gray;margin-bottom:5px}._32a6{border-bottom:1px solid #e9ebee;padding-bottom:5px}._26zb{display:inline-block}._5sq4{margin-top:5px}._289a{display:block;margin:8px auto}._5rgn{margin:5px 0}._5rgl a,._5rgl a:visited{color:#2b55ad}._5rgl a:hover,._5rgl a:focus{background:#2b55ad;color:#fff}._4f23{border-bottom:1px solid #e9ebee;display:block;margin:0 -6px 5px -6px;padding:3px}._5nxi{font-size:small}._3ckq._2v9s{background-color:#e9ebee}._5d1 ._5rgl{font-size:small;padding:4px}._5d1 ._5rgm{margin-bottom:6px}._5d1 ._5sq4{margin-top:6px}._5d1 ._5rgn,._5d1 ._5rgo{margin:6px 0}
._56bf{border-color:#ccced3 #c4c6ca #b4b6ba;border-style:solid;border-width:1px}
._5rgr{margin:0 10px 15px;position:relative;user-select:none;word-wrap:break-word}._5gh8._5rgr{margin:0 0 8px}._3f50>._5rgr{margin:0}.embedded>._5rgr{margin:10px}.messageAttachments>._5rgr{margin:0}._5rgr ._5rgr{border-top:1px solid rgba(0, 0, 0, .07);margin:0}._5rgr ._5rgr._5ysf{border-top:0}._3f_b ._5rgu{position:relative;z-index:12}._5rgr ._4hkg{margin:0 10px 10px}._37w7 ._5rgr,._5rgr ._5s1m{margin:0}._37w7 ._5rgr::before{border-style:none}._5rgs._5rgs a{color:#1d2129}._5rgs._5jk3{color:#1d2129;font-weight:normal}._5rgs{border-bottom:1px solid rgba(0, 0, 0, .1);color:#999;font-size:13px;font-weight:bold;line-height:17px;padding:8px 10px}._5x45._5x45 a{color:#4b4f56;font-weight:normal}._5rgt,._5rgu{padding:0 10px}._5pes{margin-bottom:-10px}._u1r ._27x0{margin-bottom:-10px}._5rgt,._5t8z{margin:8px 0}._5rgt p,._5t8z p{margin-bottom:6px}._5rgt p:last-child,._5t8z p:last-child{margin-bottom:0}._5t8z{display:block}._5pes ._5t8z{margin-top:0}._5rgt a{color:#576b95;font-weight:normal}._37w7 ._5rgt{height:68px}._37w7 ._x0v ._5rgt{height:100%}._37w7 ._x0v ._5rgu{padding:0}._5rgt{position:relative}._4vbp{color:#7f7f7f;font-family:'HelveticaNeue-Medium', 'Helvetica Neue Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:14px;margin:15px 0 9px 0}._5msi a,._5msi button,._5msi div[data-sigil*="more"]{position:relative;z-index:1}._5msi a._5msj{bottom:0;left:0;position:absolute;right:0;top:0;z-index:0}._4hkg ._4hkg ._4hkg .widePic{margin-left:-35px;margin-right:-35px}._4hkg ._4hkg .widePic{margin-left:-25px;margin-right:-25px}._4hkg .widePic{margin-left:-15px;margin-right:-15px}._5rgr .centeredPic{text-align:center}._5rgr ._1p6-{background:#f6f7f9;border-top:1px #dadde1 solid;color:#5e5e5e;font-size:12px;font-weight:bold;line-height:36px;text-align:center}._5rgr ._1p6-::before{background-image:url(https:\/\/static.xx.fbcdn.net\/rsrc.php\/v3\/yM\/r\/ujDtH-5KmUB.png);background-repeat:no-repeat;background-size:32px 54px;background-position:0 -32px;content:'';display:inline-block;height:20px;margin:0 4px 4px 0;vertical-align:middle;width:20px}._4vbo{background-color:#000;border-bottom:1px solid rgba(255, 255, 255, .17);margin:0 0 26px 0}._4vbo._5cyz ._54m,._4vbo._5cyz ._22rc{opacity:.25}._1sme{margin-left:0;margin-right:0}._4vbo ._5rgs{color:#7f7f7f}._4vbo ._yff{opacity:.7}._21nd{padding:0 0 10px}._21nd ._5t8z{margin:8px 8px 0 8px}._kw0{margin-left:-10px;margin-right:-10px}._3zhw{background-color:#edf2fa;border-bottom:solid 1px #dddfe2;border-top:solid 1px #dddfe2;padding:8px 10px}._3zhx{color:#5e5e5e;font-size:12px;font-weight:bold}._3zhy{color:#5e5e5e;font-size:12px}._3zi1{margin-left:8px}._5rgr ._w54{border-top:1px solid #dddfe2;padding:10px 10px 2px 10px}._5rgr ._26ti{border:none;float:left;height:0;overflow:hidden;padding:0}._5rgr ._w55{color:#90949c;padding-right:10px}._5rgr._5-8v ._5rgt{font-size:16px;line-height:20px}._5rgr._5-8w ._5rgt{font-size:17px;line-height:21px}
._5til{border:1px solid #ccc;margin:5px 0;word-wrap:break-word}._1s56{margin-bottom:5px}._5tim ._5til,._5tim ._1s56{margin-bottom:10px}._5til._1s58,._5tim ._5til._1s58{margin-bottom:0}.nontouch ._5til ._3lsd{padding-right:4px}._5tip{display:block}.nontouch ._5tip,.nontouch ._5tip:visited{color:#3e4350}.nontouch ._5tip:focus,.nontouch ._5tip:hover,.nontouch ._5tip:focus ._5til,.nontouch ._5tip:hover ._5til{background:#3b5998;color:#fff}._1prt ._5tip{visibility:hidden}._5nxi ._ing{font-size:small}
.nontouch a,.nontouch a:visited{color:#3b5998;text-decoration:none}.nontouch .sub,.nontouch .sub:visited{color:gray}.nontouch .sec,.nontouch .sec:visited{color:#6d84b4}.nontouch .inv,.nontouch .inv:visited{color:#fff}
.nontouch a:focus,.nontouch a:hover,.nontouch .sub:focus,.nontouch .sub:hover,.nontouch .sec:focus,.nontouch .sec:hover{background-color:#3b5998;color:#fff}.nontouch .inv:focus,.nontouch .inv:hover,.nontouch .inv:hover .fcy,.nontouch .inv:focus .fcy{background-color:#fff;color:#3b5998}.operaMini.nontouch a:focus,.operaMini.nontouch .sub:focus,.operaMini.nontouch .sec:focus,.operaMini.nontouch .inv:focus{background-color:inherit}.operaMini.nontouch a:focus{color:#365899}.operaMini.nontouch .sub:focus{color:gray}.operaMini.nontouch .sec:focus{color:#4267b2}.operaMini.nontouch .inv:focus{color:#fff}
.nontouch ._55wp{padding:0}.nontouch ._55wq{padding:2px}.nontouch ._55wr{padding:4px}.nontouch ._55ws{padding:6px}.nontouch ._56hq{padding:8px}
.nontouch ._4g33{border:0;border-collapse:collapse;margin:0;padding:0;width:100%}.nontouch ._4g33._4zc6{width:auto}.nontouch ._4g33 tbody,.nontouch ._52wc>tr>td,.nontouch ._52wc>tbody>tr>td,.nontouch ._4g33 td._52wc,.nontouch ._52wf>tr>td,.nontouch ._52wf>tbody>tr>td,.nontouch ._4g33 td._52wf{vertical-align:top}.nontouch ._52wd>tr>td,.nontouch ._52wd>tbody>tr>td,.nontouch ._4g33 td._52wd{vertical-align:bottom}.nontouch ._52we>tr>td,.nontouch ._52we>tbody>tr>td,.nontouch ._4g33 td._52we{vertical-align:middle}.nontouch ._4g33 td{padding:0}.nontouch ._4g33 td._55wq{padding:2px}.nontouch ._4g33 td._55wr{padding:4px}.nontouch ._4g33 td._55ws{padding:6px}.nontouch ._4g33 td._56hq{padding:8px}.nontouch ._4g34{width:100%}
.img{border:0;display:inline-block;vertical-align:top}i.img u{position:absolute;width:0;height:0;overflow:hidden}
._52j9{color:#90949c}._52ja{color:#4b4f56}._52jb{color:#1d2129}.touched ._592p ._52j9,.touched ._592p._52j9,.touched._592p ._52j9,.touched._592p._52j9,.touched ._592p ._52ja,.touched ._592p._52ja,.touched._592p ._52ja,.touched._592p._52ja,.touched ._592p._52jb,.touched._592p ._52jb,.touched ._592p ._52jb,.touched._592p._52jb,.touched ._592p,.touched._592p{color:#fff}._56bq{font-size:11px;line-height:16px;text-transform:uppercase}._52jc{font-size:12px;line-height:16px}._52jd{font-size:14px;line-height:20px}._52je{font-size:16px;line-height:20px}._52jf{font-size:18px;line-height:24px}._52jg{font-weight:normal}._52jh{font-weight:bold}._52ji{text-align:left}._52jj{text-align:center}._52jk{text-align:right}
.fcb{color:#000}.fcg{color:gray}.fcw{color:#fff}.fcl{color:#3b5998}.fcs{color:#6d84b4}
.mfsxs{font-size:x-small}.mfss{font-size:small}body,tr,input,textarea,.mfsm{font-size:medium}.mfsl{font-size:large}
.acw{background-color:#fff}.acbk{background-color:#000}.acb{background-color:#3b5998}.aclb{background-color:#eceff5}.acdb{background-color:#31394a}.acg{background-color:#f2f2f2}.acy{background-color:#fffbe2;color:#7f7212}.acr{background-color:#ffebe8;color:#6d220d}
.aps{padding:2px 3px}.apm{padding:4px 3px}.apl{padding:6px 3px}"}
  </p>
 </body>
</html>
</code>```

Title: Python 3 prettify result

Body:
How i can prettify scrapped result (from requests and BS4), remove slashes etc.

Now result looks like:

data-ft=\"{"top_level_post_id":"1396169803805852","tl_objid":"1396169803805852","throwback_story_fbid":"1396169803805852","page_id":"126721934083985"}\"
  id=\"u_0_1\" data-sigil=\"story-div story-popup-metadata
  story-popup-metadata feed-ufi-metadata\">\u003Cdiv
  data-sigil=\"m-feed-story-attachments-element\">\u003Cheader
  class=\"_4g33 _5qc1\">\u003Cdiv class=\"_5s61 _2pii _5i2i
  _52wc\">\u003Cdiv class=\"_5xu4\">\u003Ca class=\"_4prr\" href=\"/tjournal/?tn=\u00257E\"
  data-gt=\"{"tn":"~"}\">\u003Ci class=\"img profpic\"
  aria-label=\"TJournal\" role=\"img\" style=\"background:#d8dce6
  url("https://scontent.fhen1-1.fna.fbcdn.net/v/t1.0-1/cp0/e15/q65/p40x40/10419386_796086753814163_5610346145298574316_n.jpg?

My code:

r = requests.get('https://m.facebook.com/pages_reaction_units/more/?page_id=126721934083985&cursor={%22timeline_cursor%22:%22page_photos%22,%22timeline_section_cursor%22:null,%22has_next_page%22:true}&surface=mobile_page_home&unit_count=3', headers=headers)

res = r.content.decode()
soup = BeautifulSoup(res, 'lxml')
print(soup.prettify())

Body:
We can define custom formatter and pass it to BeautifulSoup.prettify method (in your case there's the problem with unicode escaping, got solution from here):

import requests

from bs4 import BeautifulSoup

r = requests.get('https://m.facebook.com/pages_reaction_units/more/?page_id=126721934083985&cursor={%22timeline_cursor%22:%22page_photos%22,%22timeline_section_cursor%22:null,%22has_next_page%22:true}&surface=mobile_page_home&unit_count=3')

def formatter(string):
    formatted = bytes(string, 'ascii').decode('unicode-escape')
    # for Python 2
    # formatted = string.decode('unicode-escape')
    return formatted

res = r.content.decode()
soup = BeautifulSoup(res, 'lxml')
print(soup.prettify(formatter=formatter))

gives us

<html>
 <body>
  <p>
   for (;;);{"actions":[{"cmd":"replace","target":"m_pages_reaction_see_more_unit","html":"<div class="_3-8x"><div class="_55wo _gui" id="unit_id_688092377989036"><div><div class="_3w7e"><div class="_55wo _56bf _5rgl" data-ft="{"top_level_post_id":"1396231463799686","tl_objid":"1396231463799686","page_id":"126721934083985"}" id="u_0_4"><div><h3 class="_52ja _52jh"><span><strong><a href="\/tjournal\/?__tn__=C">TJournal<\/a><\/strong><\/span><\/h3><div class="_5rgn" style=""><span><p>В московском метро оператор Wi-Fi объяснил наличие рекламы шутками про котят и гимнастику для глаз.<\/p><\/span><\/div><div class="_5rgo _27x0"><a class="_5tip _5tfq" href="https:\/\/lm.facebook.com\/l.php?u=https%3A%2F%2Fvc.ru%2Fp%2Fmosmetro-wifi&h=ATOEzvb7duNxYzFzO8Y_WNBP24h3OXswMOwrGBf1UOpOgSMNW0A8saNQTZxNVw2_hzp3bRyNC8rInRxtEbxx5ubADIB0GFnFadbwXzCKOCSq2k66bzaM2H-XTN8Y&enc=AZPdwIbpMFV3FWXB3fcldNTj5RGMsvmR3tL1UhSg7fx6yOErLQUUIu5_DtOs5sw7v7oUxaeuc7rfgXDJ66XN1n68KN53bmSqkpFfSTTOJK650QG9uJPCNnlHZJl0zgV5OIn1nwpLZfkxn2WHCFb9z5DpTz3k-hXMYvBg9Di00D1Wqg&s=1" id="u_0_5" target="_blank"><div class="_59e9 _55wr _5til"><table class="_4g33 _52wc"><tbody><tr><td class="_5s61 _3lsd"><img src="https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQCYmQ6aqZ7CRrUU&w=149&h=149&url=https%3A%2F%2Fvc.ru%2Fcover%2F24313%2Ffb%2Fcover.jpg&cfs=1&jq=75&ext=jpg&_nc_hash=AQCFGypsajWMdGm0" width="112" height="112" class="img" \/><\/td><td class="_4g34"><h1 class="_52jd _52jh _ing">«В мире успеет родиться 273 котёнка»: оператор Wi-Fi в московском метро решил объяснить наличие рекламы шуточными цитатами<\/h1><div class="_52jc _2b-u">vc.ru<div class="_52jc"><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/a><\/div><\/div><div class="_5sq4"><div class="mfss fcg"><abbr>27 мин<\/abbr><span> · <\/span><span class="_26zb"><span><span class="mfss">Доступно всем<\/span><\/span><\/span><\/div><div class="mfss fcg"><a href="\/story.php?story_fbid=1396231463799686&id=126721934083985#footer_action_list">Новость целиком<\/a><\/div><\/div><\/div><\/div><\/div><\/div><div class="_55wo _gui" id="unit_id_688092377989036"><div><div class="_3w7e"><div class="_55wo _56bf _5rgl" data-ft="{"top_level_post_id":"1396169803805852","tl_objid":"1396169803805852","page_id":"126721934083985"}" id="u_0_0"><div><h3 class="_52ja _52jh"><span><strong><a href="\/tjournal\/?__tn__=C">TJournal<\/a><\/strong><\/span><\/h3><div class="_5rgn" style=""><span><p>iOS 11, выходящая осенью, не поддерживает 32-битные приложения. Это значит, что пользователи потеряют доступ примерно к 200 тысячам программ. <\/p><p> Включая оригинальную Flappy Bird.<\/p><\/span><\/div><div class="_5rgo _27x0"><a class="_5tip _5tfq" href="https:\/\/lm.facebook.com\/l.php?u=https%3A%2F%2Fdtf.ru%2F7120-kak-uznat-kakie-prilozheniya-perestanut-rabotat-v-ios-11&h=ATPDoxCwMQLom_0MvLZd0sk90kReFLK9MtPs-flcXUdNA2IWlIuKBfnHqSQbNpveb8dW6gC32vxQCRtmUtBZQuy06LVxmW-gjvdi6C971XUvVhuyRCWlOdDWvgdj&enc=AZOcj4YClTNdw0ZHVMWhll-L-jVGpHnNtuLk9Su1t1GT4KnnMguG1EukLu57simsZJkFgnqQssiyu-wNtVVbXPYCIcVuYCfOcxWyWZs2j3gtpTJctaVpbpUlV4Na-zOn2PqlP8IqxHlC4uTH0jxH2qszc5trX-cCA-Mu5kuT2BDqeQ&s=1" id="u_0_1" target="_blank"><div class="_59e9 _55wr _5til"><table class="_4g33 _52wc"><tbody><tr><td class="_5s61 _3lsd"><img src="https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQAgAf90LRsVJMNs&w=149&h=149&url=https%3A%2F%2Fdtf.ru%2Fcover%2F7120%2Ffb%2Fcover.jpg&cfs=1&jq=75&ext=jpg&_nc_hash=AQAREWDHqfZjs47i" width="112" height="112" class="img" \/><\/td><td class="_4g34"><h1 class="_52jd _52jh _ing">Как узнать, какие приложения перестанут работать в iOS 11<\/h1><div class="_52jc _2b-u">dtf.ru<div class="_52jc"><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/a><\/div><\/div><div class="_5sq4"><div class="mfss fcg"><abbr>1 ч<\/abbr><span> · <\/span><span class="_26zb"><span><span class="mfss">Доступно всем<\/span><\/span><\/span><\/div><div class="mfss fcg"><a href="\/story.php?story_fbid=1396169803805852&id=126721934083985#footer_action_list">Новость целиком<\/a><\/div><\/div><\/div><\/div><\/div><\/div><div class="_55wo _gui" id="unit_id_688092377989036"><div><div class="_3w7e"><div class="_55wo _56bf _5rgl" data-ft="{"top_level_post_id":"1396120047144161","tl_objid":"1396120047144161","page_id":"126721934083985"}" id="u_0_2"><div><h3 class="_52ja _52jh"><span><strong><a href="\/tjournal\/?__tn__=C">TJournal<\/a><\/strong><\/span><\/h3><div class="_5rgn" style=""><span><p>«Когда я начал писать песни, я использовал единственный лексикон, которым владел, — народный говор».<\/p><p> Боб Дилан спустя полгода молчания всё же записал свою нобелевскую лекцию и прислал её по почте. В ней он рассказал о трёх книгах, изменивших его жизнь, и песнях, вдохновивших его на творчество.<\/p><\/span><\/div><div class="_5rgo _27x0"><a class="_5tip _5tfq" href="https:\/\/lm.facebook.com\/l.php?u=https%3A%2F%2Ftjournal.ru%2F45066-nashi-pesni-zhivi-na-zemle-zhivih&h=ATPEMvJ7GQTe04oluO0JF3NLS22d-lRvx6KKD66V_nqi9fsI1IXKolS42cYwhhi84uwDJNdjx2guKZGZLG1tDdU2Z8hdcEJCAPOhvNmzbYCQVFb1jYIQSDbGzDxe&enc=AZNVVbLvwHAh7vlAmvmJ1MPucduzaj6RF3CqoH-RDxZsiY929_44hm3bFI9T3qviVsZH4m2uipObgAZC7o8Mi2TuSW3sCSJLDDM87FFtr_ykoSiHSVoe6dJ6Ofp_Ccdp9ZC1awnV8G5hk2y7mslIMKmDu5V6HVbYuJil4PPv3nkqqw&s=1" id="u_0_3" target="_blank"><div class="_59e9 _55wr _5til"><table class="_4g33 _52wc"><tbody><tr><td class="_5s61 _3lsd"><img src="https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQAfW-DGqBho4DTZ&w=149&h=149&url=https%3A%2F%2Fgif.cmtt.space%2F3%2Fclub%2F04%2F44%2Fea%2F9a32486b17242f.jpg&cfs=1&jq=75&sx=186&sy=0&sw=847&sh=847&ext=jpg&_nc_hash=AQDaECn9dkAl-dAu" width="112" height="112" class="img" \/><\/td><td class="_4g34"><h1 class="_52jd _52jh _ing">«Наши песни живы на земле живых»<\/h1><div class="_52jc _2b-u">tjournal.ru<div class="_52jc"><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/a><\/div><\/div><div class="_5sq4"><div class="mfss fcg"><abbr>2 ч<\/abbr><span> · <\/span><span class="_26zb"><span><span class="mfss">Доступно всем<\/span><\/span><\/span><\/div><div class="mfss fcg"><a href="\/story.php?story_fbid=1396120047144161&id=126721934083985#footer_action_list">Новость целиком<\/a><\/div><\/div><\/div><\/div><\/div><\/div><div class="apm" id="m_pages_reaction_see_more_unit"><a href="\/pages_reaction_units\/more\/?page_id=126721934083985&cursor=%7B%22timeline_cursor%22%3A%22timeline_unit%3A1%3A00000000001496760847%3A04611686018427387904%3A09223372036854775805%3A04611686018427387904%22%2C%22timeline_section_cursor%22%3A%7B%7D%2C%22has_next_page%22%3Atrue%7D&surface=mobile_page_home&unit_count=3"><span>Еще<\/span><\/a><\/div><\/div>","replaceifexists":false,"allownull":false}],"css_hashes":["3HuCe","B4neB","UZuNp","9WMeb","xf2NL","9cXdw","JlaHi","QOT77","i6YK6","dkD1x","hInrP","PZ1UP","RnoEd","ol6iG","gfKii","1PJ9n","9U1Wz","IF96k"],"inline_css":"._4qba{font-style:normal}._4qbb,._4qbc,._4qbd{background:none;font-style:normal;padding:0;width:auto}._4qbd{border-bottom:1px solid #f99}._4qbb,._4qbc{border-bottom:1px solid #999}._4qbb:hover,._4qbc:hover,._4qbd:hover{background-color:#fcc;border-top:1px solid #ccc;cursor:help}
._3-8h{margin:4px}._3-8i{margin:8px}._3-8j{margin:12px}._3-8k{margin:16px}._3-8l{margin:20px}._3-8m{margin-bottom:4px;margin-top:4px}._3-8n{margin-bottom:8px;margin-top:8px}._3-8o{margin-bottom:12px;margin-top:12px}._3-8p{margin-bottom:16px;margin-top:16px}._3-8q{margin-bottom:20px;margin-top:20px}._3-8r{margin-left:4px;margin-right:4px}._3-8s{margin-left:8px;margin-right:8px}._3-8t{margin-left:12px;margin-right:12px}._3-8u{margin-left:16px;margin-right:16px}._3-8v{margin-left:20px;margin-right:20px}._3-8w{margin-top:4px}._3-8x{margin-top:8px}._3-8y{margin-top:12px}._3-8z{margin-top:16px}._3-8-{margin-top:20px}._3-8_{margin-right:4px}._3-90{margin-right:8px}._3-91{margin-right:12px}._3-92{margin-right:16px}._3-93{margin-right:20px}._3-94{margin-bottom:4px}._3-95{margin-bottom:8px}._3-96{margin-bottom:12px}._3-97{margin-bottom:16px}._3-98{margin-bottom:20px}._3-99{margin-left:4px}._3-9a{margin-left:8px}._3-9b{margin-left:12px}._3-9c{margin-left:16px}._3-9d{margin-left:20px}
._gui{border-bottom:1px solid #bec2c9;border-top:1px solid #ccc;display:block;margin:0 0 8px}._3g-o{display:block;margin:8px 0}html ._5tp0{display:block;margin:auto;max-height:32px;max-width:32px}.nontouch td._1r7u{padding-left:4px}._17lh{color:#4b4f56;display:block;font-size:12px;line-height:16px;max-height:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}._17li{display:inline-block;font-size:12px;line-height:16px;vertical-align:middle}._3w7e{position:relative}._3w7f{position:absolute;right:28px;top:0}._j5t{padding:6px 0}._j5t textarea{resize:none}._4bdb{width:320px}._4bdc{padding:4px 0}
._59e9{background:#f6f7f9}._55wm{background:#dddfe2}._5s6y{background:#000}._55wn{background:#4080ff}._55wo{background:#fff}._5oxw{background:#e9ebee}._50zt{background:#e9eaed}._25sz{background:#ff7f50}
._5rgl{margin:0 6px 6px;padding:6px}._gdx{margin:0 0 6px}.nontouch ._5rgl ._5rgl{border-color:#e9ebee;margin:6px 0 0}._5rgm{color:gray;margin-bottom:5px}._32a6{border-bottom:1px solid #e9ebee;padding-bottom:5px}._26zb{display:inline-block}._5sq4{margin-top:5px}._289a{display:block;margin:8px auto}._5rgn{margin:5px 0}._5rgl a,._5rgl a:visited{color:#2b55ad}._5rgl a:hover,._5rgl a:focus{background:#2b55ad;color:#fff}._4f23{border-bottom:1px solid #e9ebee;display:block;margin:0 -6px 5px -6px;padding:3px}._5nxi{font-size:small}._3ckq._2v9s{background-color:#e9ebee}._5d1 ._5rgl{font-size:small;padding:4px}._5d1 ._5rgm{margin-bottom:6px}._5d1 ._5sq4{margin-top:6px}._5d1 ._5rgn,._5d1 ._5rgo{margin:6px 0}
._56bf{border-color:#ccced3 #c4c6ca #b4b6ba;border-style:solid;border-width:1px}
._5rgr{margin:0 10px 15px;position:relative;user-select:none;word-wrap:break-word}._5gh8._5rgr{margin:0 0 8px}._3f50>._5rgr{margin:0}.embedded>._5rgr{margin:10px}.messageAttachments>._5rgr{margin:0}._5rgr ._5rgr{border-top:1px solid rgba(0, 0, 0, .07);margin:0}._5rgr ._5rgr._5ysf{border-top:0}._3f_b ._5rgu{position:relative;z-index:12}._5rgr ._4hkg{margin:0 10px 10px}._37w7 ._5rgr,._5rgr ._5s1m{margin:0}._37w7 ._5rgr::before{border-style:none}._5rgs._5rgs a{color:#1d2129}._5rgs._5jk3{color:#1d2129;font-weight:normal}._5rgs{border-bottom:1px solid rgba(0, 0, 0, .1);color:#999;font-size:13px;font-weight:bold;line-height:17px;padding:8px 10px}._5x45._5x45 a{color:#4b4f56;font-weight:normal}._5rgt,._5rgu{padding:0 10px}._5pes{margin-bottom:-10px}._u1r ._27x0{margin-bottom:-10px}._5rgt,._5t8z{margin:8px 0}._5rgt p,._5t8z p{margin-bottom:6px}._5rgt p:last-child,._5t8z p:last-child{margin-bottom:0}._5t8z{display:block}._5pes ._5t8z{margin-top:0}._5rgt a{color:#576b95;font-weight:normal}._37w7 ._5rgt{height:68px}._37w7 ._x0v ._5rgt{height:100%}._37w7 ._x0v ._5rgu{padding:0}._5rgt{position:relative}._4vbp{color:#7f7f7f;font-family:'HelveticaNeue-Medium', 'Helvetica Neue Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:14px;margin:15px 0 9px 0}._5msi a,._5msi button,._5msi div[data-sigil*="more"]{position:relative;z-index:1}._5msi a._5msj{bottom:0;left:0;position:absolute;right:0;top:0;z-index:0}._4hkg ._4hkg ._4hkg .widePic{margin-left:-35px;margin-right:-35px}._4hkg ._4hkg .widePic{margin-left:-25px;margin-right:-25px}._4hkg .widePic{margin-left:-15px;margin-right:-15px}._5rgr .centeredPic{text-align:center}._5rgr ._1p6-{background:#f6f7f9;border-top:1px #dadde1 solid;color:#5e5e5e;font-size:12px;font-weight:bold;line-height:36px;text-align:center}._5rgr ._1p6-::before{background-image:url(https:\/\/static.xx.fbcdn.net\/rsrc.php\/v3\/yM\/r\/ujDtH-5KmUB.png);background-repeat:no-repeat;background-size:32px 54px;background-position:0 -32px;content:'';display:inline-block;height:20px;margin:0 4px 4px 0;vertical-align:middle;width:20px}._4vbo{background-color:#000;border-bottom:1px solid rgba(255, 255, 255, .17);margin:0 0 26px 0}._4vbo._5cyz ._54m,._4vbo._5cyz ._22rc{opacity:.25}._1sme{margin-left:0;margin-right:0}._4vbo ._5rgs{color:#7f7f7f}._4vbo ._yff{opacity:.7}._21nd{padding:0 0 10px}._21nd ._5t8z{margin:8px 8px 0 8px}._kw0{margin-left:-10px;margin-right:-10px}._3zhw{background-color:#edf2fa;border-bottom:solid 1px #dddfe2;border-top:solid 1px #dddfe2;padding:8px 10px}._3zhx{color:#5e5e5e;font-size:12px;font-weight:bold}._3zhy{color:#5e5e5e;font-size:12px}._3zi1{margin-left:8px}._5rgr ._w54{border-top:1px solid #dddfe2;padding:10px 10px 2px 10px}._5rgr ._26ti{border:none;float:left;height:0;overflow:hidden;padding:0}._5rgr ._w55{color:#90949c;padding-right:10px}._5rgr._5-8v ._5rgt{font-size:16px;line-height:20px}._5rgr._5-8w ._5rgt{font-size:17px;line-height:21px}
._5til{border:1px solid #ccc;margin:5px 0;word-wrap:break-word}._1s56{margin-bottom:5px}._5tim ._5til,._5tim ._1s56{margin-bottom:10px}._5til._1s58,._5tim ._5til._1s58{margin-bottom:0}.nontouch ._5til ._3lsd{padding-right:4px}._5tip{display:block}.nontouch ._5tip,.nontouch ._5tip:visited{color:#3e4350}.nontouch ._5tip:focus,.nontouch ._5tip:hover,.nontouch ._5tip:focus ._5til,.nontouch ._5tip:hover ._5til{background:#3b5998;color:#fff}._1prt ._5tip{visibility:hidden}._5nxi ._ing{font-size:small}
.nontouch a,.nontouch a:visited{color:#3b5998;text-decoration:none}.nontouch .sub,.nontouch .sub:visited{color:gray}.nontouch .sec,.nontouch .sec:visited{color:#6d84b4}.nontouch .inv,.nontouch .inv:visited{color:#fff}
.nontouch a:focus,.nontouch a:hover,.nontouch .sub:focus,.nontouch .sub:hover,.nontouch .sec:focus,.nontouch .sec:hover{background-color:#3b5998;color:#fff}.nontouch .inv:focus,.nontouch .inv:hover,.nontouch .inv:hover .fcy,.nontouch .inv:focus .fcy{background-color:#fff;color:#3b5998}.operaMini.nontouch a:focus,.operaMini.nontouch .sub:focus,.operaMini.nontouch .sec:focus,.operaMini.nontouch .inv:focus{background-color:inherit}.operaMini.nontouch a:focus{color:#365899}.operaMini.nontouch .sub:focus{color:gray}.operaMini.nontouch .sec:focus{color:#4267b2}.operaMini.nontouch .inv:focus{color:#fff}
.nontouch ._55wp{padding:0}.nontouch ._55wq{padding:2px}.nontouch ._55wr{padding:4px}.nontouch ._55ws{padding:6px}.nontouch ._56hq{padding:8px}
.nontouch ._4g33{border:0;border-collapse:collapse;margin:0;padding:0;width:100%}.nontouch ._4g33._4zc6{width:auto}.nontouch ._4g33 tbody,.nontouch ._52wc>tr>td,.nontouch ._52wc>tbody>tr>td,.nontouch ._4g33 td._52wc,.nontouch ._52wf>tr>td,.nontouch ._52wf>tbody>tr>td,.nontouch ._4g33 td._52wf{vertical-align:top}.nontouch ._52wd>tr>td,.nontouch ._52wd>tbody>tr>td,.nontouch ._4g33 td._52wd{vertical-align:bottom}.nontouch ._52we>tr>td,.nontouch ._52we>tbody>tr>td,.nontouch ._4g33 td._52we{vertical-align:middle}.nontouch ._4g33 td{padding:0}.nontouch ._4g33 td._55wq{padding:2px}.nontouch ._4g33 td._55wr{padding:4px}.nontouch ._4g33 td._55ws{padding:6px}.nontouch ._4g33 td._56hq{padding:8px}.nontouch ._4g34{width:100%}
.img{border:0;display:inline-block;vertical-align:top}i.img u{position:absolute;width:0;height:0;overflow:hidden}
._52j9{color:#90949c}._52ja{color:#4b4f56}._52jb{color:#1d2129}.touched ._592p ._52j9,.touched ._592p._52j9,.touched._592p ._52j9,.touched._592p._52j9,.touched ._592p ._52ja,.touched ._592p._52ja,.touched._592p ._52ja,.touched._592p._52ja,.touched ._592p._52jb,.touched._592p ._52jb,.touched ._592p ._52jb,.touched._592p._52jb,.touched ._592p,.touched._592p{color:#fff}._56bq{font-size:11px;line-height:16px;text-transform:uppercase}._52jc{font-size:12px;line-height:16px}._52jd{font-size:14px;line-height:20px}._52je{font-size:16px;line-height:20px}._52jf{font-size:18px;line-height:24px}._52jg{font-weight:normal}._52jh{font-weight:bold}._52ji{text-align:left}._52jj{text-align:center}._52jk{text-align:right}
.fcb{color:#000}.fcg{color:gray}.fcw{color:#fff}.fcl{color:#3b5998}.fcs{color:#6d84b4}
.mfsxs{font-size:x-small}.mfss{font-size:small}body,tr,input,textarea,.mfsm{font-size:medium}.mfsl{font-size:large}
.acw{background-color:#fff}.acbk{background-color:#000}.acb{background-color:#3b5998}.aclb{background-color:#eceff5}.acdb{background-color:#31394a}.acg{background-color:#f2f2f2}.acy{background-color:#fffbe2;color:#7f7212}.acr{background-color:#ffebe8;color:#6d220d}
.aps{padding:2px 3px}.apm{padding:4px 3px}.apl{padding:6px 3px}"}
  </p>
 </body>
</html>


来源: stackexchange

问:
Most efficient way to insert associative array with matching array to table keys
Given the following array;

```<code>[0] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
),
[2] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
),
[3] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
)
</code>```

And a database table with the same column names col1, col2 and col3

What's the most efficient way to insert this into a database?

I currently have something like this;

```<code>$i = 0;
$db_columns = '';

$column_values = array();

foreach ($rows as $k => $row)
{
    $columns = array();
    $fields = array();

    foreach ($row as $a => $b)
    {
        $column_values[$a.$i] = $b;
        $columns[] = ':'.$a.$i;
        $fields[] = $a;
    }

    // build up sql values
    $db_columns .= ($db_columns ? ', ' : '').'('.implode(', ', $columns).')';

    $i++;
}

// perform insert
$sql = "INSERT INTO table (".implode(', ', $fields).")
    VALUES $db_columns";

$query = $db->prepare($sql);
$status = $query->execute($column_values);
</code>```

Which will build the query string like so;

```<code>INSERT INTO table (col1, col2, col3)
VALUES (:col10, :col20, :col30), (:col11, :col21, :col31), (:col12, :col22, :col32)
</code>```

With an array to match the bound variables :col10, :col20, :col30, :col11 etc...

So all well and good. It does what I want and works, but the code to me seems overly complicated considering the input array keys match the table. There must be a cleaner way to do this.

答:
You can simplify a little the code by using question mark parameters. For example, in the way:

```<code>$db_columns = '(' .  implode('),(', array_fill(0, count($rows), implode(',', array_fill(0, count($rows[0]), '?')))) . ')';

$sql = "INSERT INTO table (".implode(', ', array_keys($rows[0])).")
    VALUES $db_columns";

$query = $db->prepare($sql);
$status = $query->execute($column_values);
$query->execute(array_merge(...array_map('array_values', $rows)));
</code>```

demo on eval.in

ContentLicense: CC BY-SA 3.0

Body:
Given the following array;

[0] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
),
[2] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
),
[3] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
)

And a database table with the same column names col1, col2 and col3

What's the most efficient way to insert this into a database?

I currently have something like this;

$i = 0;
$db_columns = '';

$column_values = array();

foreach ($rows as $k => $row)
{
    $columns = array();
    $fields = array();

    foreach ($row as $a => $b)
    {
        $column_values[$a.$i] = $b;
        $columns[] = ':'.$a.$i;
        $fields[] = $a;
    }

    // build up sql values
    $db_columns .= ($db_columns ? ', ' : '').'('.implode(', ', $columns).')';

    $i++;
}

// perform insert
$sql = "INSERT INTO table (".implode(', ', $fields).")
    VALUES $db_columns";

$query = $db->prepare($sql);
$status = $query->execute($column_values);

Which will build the query string like so;

INSERT INTO table (col1, col2, col3)
VALUES (:col10, :col20, :col30), (:col11, :col21, :col31), (:col12, :col22, :col32)

With an array to match the bound variables :col10, :col20, :col30, :col11 etc...

So all well and good. It does what I want and works, but the code to me seems overly complicated considering the input array keys match the table. There must be a cleaner way to do this.

Body:
You can simplify a little the code by using question mark parameters. For example, in the way:

$db_columns = '(' .  implode('),(', array_fill(0, count($rows), implode(',', array_fill(0, count($rows[0]), '?')))) . ')';

$sql = "INSERT INTO table (".implode(', ', array_keys($rows[0])).")
    VALUES $db_columns";

$query = $db->prepare($sql);
$status = $query->execute($column_values);
$query->execute(array_merge(...array_map('array_values', $rows)));

demo on eval.in


问:
C Source Code in Latex document
Can anyone recommend me a good template to include C source code with line numbering
in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:

```<code>(1)   /* Hello World program */
(2)
(3)   #include<stdio.h>
(4)
(5)   main()
(6)   {
(7)    printf("Hello World");
(8)   }
</code>```

Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.

Thanks so much
Richard

答:
Take a look at Code listings in LaTeX. You'll find a couple of alternatives there. Some options are:

listings

minted

lgrind

ContentLicense: CC BY-SA 2.5

Title: C Source Code in Latex document

Body:
Can anyone recommend me a good template to include C source code with line numbering
in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:

(1)   /* Hello World program */
(2)
(3)   #include<stdio.h>
(4)
(5)   main()
(6)   {
(7)    printf("Hello World");
(8)   }

Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.

Thanks so much
Richard

ContentLicense: CC BY-SA 4.0


问:
Print application version for each report using JasperReports
We are using JasperReports 6.0.0 and have about 30 templates for different reports that have almost nothing in common. Today we have got a requirement to print application version at the bottom of each page for every report.

I could not find any good solution to do it without modifying every template file. Does JasperReport allows to specify general layout for all templates? Is there any solution to add label to each page without modifying existent templates?

答:
Some approaches:

Modify all .jrxml files and add a footer to each one, manually.

Use XSLT to modify all the .jrxml templates and add a footer.

Use iText to modify the report output after generating the report PDF.

Use the JasperReports API to programmatically inject a footer band into the in-memory template prior to compilation and execution.

Use the JasperReports API to programmatically inject a footer band into each .jrxml file and save the file back to disk.

Create a master template and include a parameterized subreport.

The last approach would have a master template as follows:

```<code> -----------
|  Title    |
 -----------
| Subreport |
 -----------
|  Footer   |
 -----------
</code>```

Then, when running the report, pass in a parameter that indicates what subreport to include (i.e., one of thirty). In this fashion, the Title Band and Footer Band are shared by all thirty reports. It's more work, but ultimately the most flexible solution.

If the Title Band differs completely across all reports, parameterize it to use a subreport.

Here's a screenshot of a master report that includes a subreport, which is given as a parameter. In the screenshot, the Title Band doesn't include a subreport because each of the several reports looks identical (the human-readable report title is also a parameter). It should be easy to see that if the Title Band had to change its layout for each report, then using a subreport instead would facilitate such a solution:

The footer, though, as shown in the screenshot, is one possible answer to your question.

You may need to define a variable that allows for calculating the page numbers:

```<code><variable name="V_CURRENT_PAGE_NUMBER" class="java.lang.Integer" resetType="Page">
    <variableExpression><![CDATA[1]]></variableExpression>
    <initialValueExpression><![CDATA[$V{PAGE_NUMBER}+1]]></initialValueExpression>
</variable>
</code>```

And a corresponding text field that references the page number:

```<code>msg("Page {0} of {1}", $V{V_CURRENT_PAGE_NUMBER}, $V{PAGE_NUMBER})
</code>```

Keeping in mind that JasperReports uses absolute paths, define a few parameters to avoid hard-coding the location of the subreports. For example:

```<code>$P{P_REPORT_SUBREPORTS_PATH} + $P{P_SUBREPORT_NAME} + ".jasper"
</code>```

Here, P_REPORT_SUBREPORTS_PATH is defined in terms of a P_REPORT_BASE variable:

```<code>$P{P_REPORT_BASE} + "subreports/"
</code>```

This allows the report IDE to use a different directory than that of the web server by providing a different value for P_REPORT_BASE, depending on context.

Finally, keep in mind that what might be seemingly different reports could be a parameterized report. JasperReports allows for custom styles, which makes possible to dynamically change the report appearance (e.g., text justification, fonts, emphasis, borders, and so forth). In the screenshot, the report title, for example, is changed with each of the several reports--but they all share the same Title Band because the report title is passed in as a String parameter.

Body:
Some approaches:

Modify all .jrxml files and add a footer to each one, manually.

Use XSLT to modify all the .jrxml templates and add a footer.

Use iText to modify the report output after generating the report PDF.

Use the JasperReports API to programmatically inject a footer band into the in-memory template prior to compilation and execution.

Use the JasperReports API to programmatically inject a footer band into each .jrxml file and save the file back to disk.

Create a master template and include a parameterized subreport.

The last approach would have a master template as follows:

 -----------
|  Title    |
 -----------
| Subreport |
 -----------
|  Footer   |
 -----------

Then, when running the report, pass in a parameter that indicates what subreport to include (i.e., one of thirty). In this fashion, the Title Band and Footer Band are shared by all thirty reports. It's more work, but ultimately the most flexible solution.

If the Title Band differs completely across all reports, parameterize it to use a subreport.

Here's a screenshot of a master report that includes a subreport, which is given as a parameter. In the screenshot, the Title Band doesn't include a subreport because each of the several reports looks identical (the human-readable report title is also a parameter). It should be easy to see that if the Title Band had to change its layout for each report, then using a subreport instead would facilitate such a solution:

The footer, though, as shown in the screenshot, is one possible answer to your question.

You may need to define a variable that allows for calculating the page numbers:

<variable name="V_CURRENT_PAGE_NUMBER" class="java.lang.Integer" resetType="Page">
    <variableExpression><![CDATA[1]]></variableExpression>
    <initialValueExpression><![CDATA[$V{PAGE_NUMBER}+1]]></initialValueExpression>
</variable>

And a corresponding text field that references the page number:

msg("Page {0} of {1}", $V{V_CURRENT_PAGE_NUMBER}, $V{PAGE_NUMBER})

Keeping in mind that JasperReports uses absolute paths, define a few parameters to avoid hard-coding the location of the subreports. For example:

$P{P_REPORT_SUBREPORTS_PATH} + $P{P_SUBREPORT_NAME} + ".jasper"

Here, P_REPORT_SUBREPORTS_PATH is defined in terms of a P_REPORT_BASE variable:

$P{P_REPORT_BASE} + "subreports/"

This allows the report IDE to use a different directory than that of the web server by providing a different value for P_REPORT_BASE, depending on context.

Finally, keep in mind that what might be seemingly different reports could be a parameterized report. JasperReports allows for custom styles, which makes possible to dynamically change the report appearance (e.g., text justification, fonts, emphasis, borders, and so forth). In the screenshot, the report title, for example, is changed with each of the several reports--but they all share the same Title Band because the report title is passed in as a String parameter.


问:
Is adding async to a method signature a breaking change?
In addressing a question about how much to use async/await, i.e. "should all methods return Task?", the author of this answer, Matías Fidemraizer, claims that, even if your method currently only does synchronous stuff, it should still return a task so if you make it do async stuff later, "you can turn it into actual async operations without affecting the entire code base".  That makes sense, but if I'm actually awaiting something, I have to add async to the method signature.  So we're talking about going from:

```<code>public Task WhateverAsync()
{
    return Task.FromResult(true);
}
</code>```

to

```<code>public async Task WhateverAsync()
{
    return await AwaitableSomething();
}
</code>```

Is adding async to a method signature a breaking change?

答:
No, this is not (really) a breaking change. Adding an async keyword to a method is only a hint to the compiler that it should turn it into an asychronous state machine.

I'm using the following code to check the public signature of a method in LINQPad.

```<code>var method = typeof(ContainingClass).GetMethod("WhateverAsync");
method.ReturnType.Dump();
method.GetParameters().Length.Dump();
method.GetCustomAttributes().Dump();
</code>```

The first two dumps return the following for both of your methods.

```<code>System.Threading.Tasks.Task
0
</code>```

Meaning they return the same type of value and take the same amount of parameters. They do have different attributes though, which is technically a breaking change (but if code does depend on it, it's garbage code).

The first method has no custom attributes, while the 2nd method has the following 2 attributes: AsyncStateMachineAttribute and DebuggerStepThroughAttribute.

Something else you want to be aware of when working with reflection is that adding the async keyword to a method, adds a nested private (generated) class to its containing type usually named something along the lines of <WhateverAsync>d__0.

Body:
In addressing a question about how much to use async/await, i.e. "should all methods return Task?", the author of this answer, Matías Fidemraizer, claims that, even if your method currently only does synchronous stuff, it should still return a task so if you make it do async stuff later, "you can turn it into actual async operations without affecting the entire code base".  That makes sense, but if I'm actually awaiting something, I have to add async to the method signature.  So we're talking about going from:

public Task WhateverAsync()
{
    return Task.FromResult(true);
}

to

public async Task WhateverAsync()
{
    return await AwaitableSomething();
}

Is adding async to a method signature a breaking change?

Body:
No, this is not (really) a breaking change. Adding an async keyword to a method is only a hint to the compiler that it should turn it into an asychronous state machine.

I'm using the following code to check the public signature of a method in LINQPad.

var method = typeof(ContainingClass).GetMethod("WhateverAsync");
method.ReturnType.Dump();
method.GetParameters().Length.Dump();
method.GetCustomAttributes().Dump();

The first two dumps return the following for both of your methods.

System.Threading.Tasks.Task
0

Meaning they return the same type of value and take the same amount of parameters. They do have different attributes though, which is technically a breaking change (but if code does depend on it, it's garbage code).

The first method has no custom attributes, while the 2nd method has the following 2 attributes: AsyncStateMachineAttribute and DebuggerStepThroughAttribute.

Something else you want to be aware of when working with reflection is that adding the async keyword to a method, adds a nested private (generated) class to its containing type usually named something along the lines of <WhateverAsync>d__0.


问:
Docker build "no such file or directory" but work with docker-compose
I try to register with gitlab a image:

```<code>docker build -t registry.gitlab.com/xxx/xxx compose/base
</code>```

But I get:

Step 4/7 : COPY ./requirements /requirements lstat requirements: no
  such file or directory

However build with compose work:

```<code>docker-compose -f dev.yml build python

services:
  python:
    build:
      context: .
      dockerfile: ./compose/base/Dockerfile
</code>```

The file structure:

-Project/requirements
-Project/compose/base

How I replicate what compose do?

答:
Your problem is in docker build context, i suggest you try this:</p>

```<code>docker build -t registry.gitlab.com/xxx/xxx -f compose/base/Dockerfile .
</code>```

Body:
I try to register with gitlab a image:

docker build -t registry.gitlab.com/xxx/xxx compose/base

But I get:

Step 4/7 : COPY ./requirements /requirements lstat requirements: no
  such file or directory

However build with compose work:

docker-compose -f dev.yml build python

services:
  python:
    build:
      context: .
      dockerfile: ./compose/base/Dockerfile

The file structure:

-Project/requirements
-Project/compose/base

How I replicate what compose do?

Body:
Your problem is in docker build context, i suggest you try this:

docker build -t registry.gitlab.com/xxx/xxx -f compose/base/Dockerfile .


问:
How to get intersection of the arrays in a nested array
I have an array like the following which is computed from another function I don't want to modify.

```<code>var d = [[1, 2, 3], [2, 3], [1, 3]];
</code>```

I want to use _.intersection with all the arrays within the above array like this:

```<code>var c = _.intersection(d);
// should return [3]
</code>```

but _.intersection takes multiple array parameters as input, not an array of arrays.

I have tried to flatten an array using something similar to Merge/flatten an array of arrays in JavaScript? but it convert the whole array into a single array.

```<code>var merged = [].concat.apply([], d);
[1, 2, 3, 2, 3, 1, 3]; // I don't want this
</code>```

Let me explain this in detail. I have a nested array d (which contains arrays and length is dynamic). Now I want to find the intersection of all arrays that are within array d.

How can I call _.intersection([1, 2, 3], [2, 3], [1, 3], ...) but dynamically with d?

答:
In ES5 you can use Function#apply to spread the array into parameters:

var d = [[1, 2, 3], [2, 3], [1, 3]];

var result = _.intersection.apply(_, d);

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script></code>```

You can use lodash's _.spread that will convert a function to consume an array of parameters:

var d = [[1, 2, 3], [2, 3], [1, 3]];

var result = _.spread(_.intersection)(d);

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

In ES6 you can use the spread syntax to do the same thing:

const d = [[1, 2, 3], [2, 3], [1, 3]];

const result = _.intersection(...d);

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script></code>```

Body:
I have an array like the following which is computed from another function I don't want to modify.

var d = [[1, 2, 3], [2, 3], [1, 3]];

I want to use _.intersection with all the arrays within the above array like this:

var c = _.intersection(d);
// should return [3]

but _.intersection takes multiple array parameters as input, not an array of arrays.

I have tried to flatten an array using something similar to Merge/flatten an array of arrays in JavaScript? but it convert the whole array into a single array.

var merged = [].concat.apply([], d);
[1, 2, 3, 2, 3, 1, 3]; // I don't want this

Let me explain this in detail. I have a nested array d (which contains arrays and length is dynamic). Now I want to find the intersection of all arrays that are within array d.

How can I call _.intersection([1, 2, 3], [2, 3], [1, 3], ...) but dynamically with d?

Body:
In ES5 you can use Function#apply to spread the array into parameters:

var d = [[1, 2, 3], [2, 3], [1, 3]];

var result = _.intersection.apply(_, d);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

You can use lodash's _.spread that will convert a function to consume an array of parameters:

var d = [[1, 2, 3], [2, 3], [1, 3]];

var result = _.spread(_.intersection)(d);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

In ES6 you can use the spread syntax to do the same thing:

const d = [[1, 2, 3], [2, 3], [1, 3]];

const result = _.intersection(...d);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


问:
Possibility to send reports to one launch in ReportPortal for .net (Specflow)
I have the need to send reports from different OS and test runs to the same launch in the report portal.
How this can be done?</p>

答:
Here is how it's accomplished on my project:

CI server creates an RP launch and saves the launch id to app.config of the test binaries.

The test binaries are copied to VMs and run there.

When the tests start, they see that there is launch id in app.config and don't create a new launch - they re-use the existing one. Also they don't close the launch once they are done.

```<code>[BeforeTestRun(Order = -30000)]
public static void BeforeTestRunPart()
{
    ReportPortalAddin.BeforeRunStarted += ReportPortalAddin_BeforeRunStarted;
    ReportPortalAddin.BeforeRunFinished += ReportPortalAddin_BeforeRunFinished;
}

public static void ReportPortalAddin_BeforeRunStarted(object sender, RunStartedEventArgs e)
{
    var launchId = SettingsManager.CommonSettings.ReportPortalLaunchId;
    if (launchId.IsNullOrEmpty() == false)
    {
        e.Canceled = true;
        Bridge.Context.LaunchId = launchId;
    }
}

public static void ReportPortalAddin_BeforeRunFinished(object sender, RunFinishedEventArgs e)
{
    var launchId = SettingsManager.CommonSettings.ReportPortalLaunchId;
    if (launchId.IsNullOrEmpty() == false)
    {
        e.Canceled = true;
    }
}
</code>```

When all tests are run, CI server closes the RP launch.

Body:
Here is how it's accomplished on my project:

CI server creates an RP launch and saves the launch id to app.config of the test binaries.

The test binaries are copied to VMs and run there.

When the tests start, they see that there is launch id in app.config and don't create a new launch - they re-use the existing one. Also they don't close the launch once they are done.

[BeforeTestRun(Order = -30000)]
public static void BeforeTestRunPart()
{
    ReportPortalAddin.BeforeRunStarted += ReportPortalAddin_BeforeRunStarted;
    ReportPortalAddin.BeforeRunFinished += ReportPortalAddin_BeforeRunFinished;
}

public static void ReportPortalAddin_BeforeRunStarted(object sender, RunStartedEventArgs e)
{
    var launchId = SettingsManager.CommonSettings.ReportPortalLaunchId;
    if (launchId.IsNullOrEmpty() == false)
    {
        e.Canceled = true;
        Bridge.Context.LaunchId = launchId;
    }
}

public static void ReportPortalAddin_BeforeRunFinished(object sender, RunFinishedEventArgs e)
{
    var launchId = SettingsManager.CommonSettings.ReportPortalLaunchId;
    if (launchId.IsNullOrEmpty() == false)
    {
        e.Canceled = true;
    }
}

When all tests are run, CI server closes the RP launch.


问:
reading Jframe attribute and writing its value to an xml file
I writing a java program that will read the content of JFrame and based on the value of that an xml file will be created which will contain the attributes and its corresponding value.
I have two classes one having java swing and another creating an xml file.
On my frame i have few check boxes and few combo boxes and I want to create the xml containing attribute and value of these.
I am not able to set the value of these attributes at all in my CreateXML.java file.
If anybody has some solution please help me out.

Regards,
SHK

答:
JFrame is an indirect subclass of Container that implements method public Component[] getComponents(). Once you have reference to you JFrame you can iterate over its components and create XML if you need. Pay attention that if one of the components is instance of Container you should go inside recursively.

I believe that this is what you should implement into your CreateXML class.


问:
React router dom routes are loaded onto React Developer tools but the routes are not working in the browser
I am new to React and currently working on a navigation bar. I have index.js which is my startup file

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import history from 'history';
import Routes from './routes/index';
import Template from './containers/Template';

ReactDOM.render(
  (
    <BrowserRouter
        history={history}
        routes={Routes}
    >
        <Template />
    </BrowserRouter>
  ),document.getElementById('root')
);
</code>```

the routes are imported from the routes/index.js file which comes like this

```<code>import React from 'react';
import {Route, BrowserRouter, Switch} from 'react-router-dom';
import Template from '../containers/Template';
import Home from '../containers/Home';
import Profile from '../containers/Profile';

const createRoutes = () => {
  return (
      <BrowserRouter>
      <Switch>
        <Route path= '/' component= {Template}/>
        <Route path= '/' component={Home}/>
        <Route path= {'/profile'} component={Profile}/>
      </Switch>
      </BrowserRouter>
  )
}

const Routes = createRoutes();

export default Routes;
</code>```

My main problem is that when I am using chrome and React Developer tools I can see the routes related to the BrowserRouter object as follows
Routes in the Browser element inspection

But I cannot open any of the specified routes always getting "Cannot get /profile", note I am using webpack as a web development bundle.

答:
What is happening here is your webpack-dev-server is trying to serve you an html page called /profile which does not exist as you are using a single page app.

Take a look at this link but it comes down to the fact that this is expected behaviour from the webpack-dev-server as the /profile html page does not exist.

In order to get this kind of behaviour to work you need to implement server-side rendering or you could use React-Router's hash location

Body:
I am new to React and currently working on a navigation bar. I have index.js which is my startup file

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import history from 'history';
import Routes from './routes/index';
import Template from './containers/Template';

ReactDOM.render(
  (
    <BrowserRouter
        history={history}
        routes={Routes}
    >
        <Template />
    </BrowserRouter>
  ),document.getElementById('root')
);

the routes are imported from the routes/index.js file which comes like this

import React from 'react';
import {Route, BrowserRouter, Switch} from 'react-router-dom';
import Template from '../containers/Template';
import Home from '../containers/Home';
import Profile from '../containers/Profile';

const createRoutes = () => {
  return (
      <BrowserRouter>
      <Switch>
        <Route path= '/' component= {Template}/>
        <Route path= '/' component={Home}/>
        <Route path= {'/profile'} component={Profile}/>
      </Switch>
      </BrowserRouter>
  )
}

const Routes = createRoutes();

export default Routes;

My main problem is that when I am using chrome and React Developer tools I can see the routes related to the BrowserRouter object as follows
Routes in the Browser element inspection

But I cannot open any of the specified routes always getting "Cannot get /profile", note I am using webpack as a web development bundle.


问:
Button seems to be covered by video
I am trying to write a program that captures photos with webcam. I want to add a JButton to the JFrame of a live video. Yet, the button doesnt show up. My belief is that it is covered by the video. I attached my code below.

```<code>import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyFrame extends JFrame {
private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    MyFrame frame = new MyFrame();
    frame.contentPane.add(new JButton("Camera"));
    frame.setVisible(true);
}
 // Create the frame.
public MyFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 650, 490);
    contentPane = new JPanel();
    setContentPane(contentPane);
    contentPane.setLayout(null);
    new MyThread().start();
}
VideoCap videoCap = new VideoCap();
public void paintComponent(Graphics g){
    g = contentPane.getGraphics();
    g.drawImage(videoCap.getOneFrame(), 0, 0, this);
}
class MyThread extends Thread{
    @Override
    public void run() {
        for (;;){
            repaint();
            try { Thread.sleep(30);
            } catch (InterruptedException e) {    }
        }
    }
}
}
</code>```

Any suggestions would be awesome.

I looked through many questions regarding Jbuttons not showing up, but I am not sure which one is similar to mine. Please point me in the right direction if there is.

Thank you in advance.

答:
I am unsure, as to which library you are using in order to create the said video. Though in this example, I used the opencv library to create an image from webcam. You have to modify it, in order to make it work for your usecase.

```<code>import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.opencv.core.*;
import org.opencv.videoio.VideoCapture;

public class ApplicationBase {

    private BufferedImage m_Captured_BufferedImage;

    static {
        System.out.println(System.getProperty("java.library.path"));
        System.loadLibrary ( Core.NATIVE_LIBRARY_NAME );
    }

    private void displayGUI ( BufferedImage image, String title, int x, int y ) {
        JFrame frame = new JFrame ( title );
        frame.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );

        JPanel contentPane = new JPanel ( new BorderLayout ( 5, 5 ) );

        PictureDrawer pictureDrawer = new PictureDrawer ( image );
        contentPane.add ( pictureDrawer, BorderLayout.CENTER );

        JButton button = new JButton ( "Click Me not!" );
        contentPane.add ( button, BorderLayout.PAGE_END );

        frame.setContentPane ( contentPane );
        frame.pack ();
        frame.setLocationByPlatform ( true );
        frame.setVisible ( true );
    }

    private void startApp () {
        VideoCapture camera = new VideoCapture ( 0 );

        Mat videoFrame = new Mat ();
        camera.read ( videoFrame );

        if ( camera.read ( videoFrame ) ) {
            m_Captured_BufferedImage = matToBufferedImage ( videoFrame );
            Runnable runnable = new Runnable () {
                @Override
                public void run () {
                    displayGUI ( m_Captured_BufferedImage, "Image", 0, 0 );
                }
            };
            EventQueue.invokeLater ( runnable );
        }
        camera.release ();
    }

    public BufferedImage matToBufferedImage ( Mat videoFrame ) {
        //Mat() to BufferedImage
        int type = 0;
        if ( videoFrame.channels () == 1 ) {
            type = BufferedImage.TYPE_BYTE_GRAY;
        } else if ( videoFrame.channels () == 3 ) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        BufferedImage image = new BufferedImage ( videoFrame.width (), videoFrame.height (), type );
        WritableRaster raster = image.getRaster ();
        DataBufferByte dataBuffer = ( DataBufferByte ) raster.getDataBuffer ();
        byte [] data = dataBuffer.getData ();
        videoFrame.get ( 0, 0, data );

        return image;
    }

    public static void main ( String [] args ) {
        new ApplicationBase ().startApp ();
    }
}

class PictureDrawer extends JComponent {

    private BufferedImage m_BufferedImage;

    public PictureDrawer ( BufferedImage bufferedImage ) {
        this.m_BufferedImage = bufferedImage;
    }

    @Override
    protected void paintComponent ( Graphics g ) {
        super.paintComponent ( g );
        g.drawImage ( m_BufferedImage, 0, 0, this );
    }

    @Override
    public Dimension getPreferredSize () {
        return new Dimension ( m_BufferedImage.getWidth (), m_BufferedImage.getHeight () );
    }
}
</code>```

I downloaded the OpenCV library from this

Compiled the project with this command:

```<code>javac -classpath .;C:\install\opencv\opencv\build\java\opencv-320.jar; -d bin source\*.java
</code>```

Command to run project:

```<code>>java -classpath .;C:\install\opencv\opencv\build\java\opencv-320.jar; -Djava.library.path=C:\install\opencv\opencv\build\java\x64 ApplicationBase
</code>```

Title: Button seems to be covered by video

Body:
I am trying to write a program that captures photos with webcam. I want to add a JButton to the JFrame of a live video. Yet, the button doesnt show up. My belief is that it is covered by the video. I attached my code below.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyFrame extends JFrame {
private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    MyFrame frame = new MyFrame();
    frame.contentPane.add(new JButton("Camera"));
    frame.setVisible(true);
}
 // Create the frame.
public MyFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 650, 490);
    contentPane = new JPanel();
    setContentPane(contentPane);
    contentPane.setLayout(null);
    new MyThread().start();
}
VideoCap videoCap = new VideoCap();
public void paintComponent(Graphics g){
    g = contentPane.getGraphics();
    g.drawImage(videoCap.getOneFrame(), 0, 0, this);
}
class MyThread extends Thread{
    @Override
    public void run() {
        for (;;){
            repaint();
            try { Thread.sleep(30);
            } catch (InterruptedException e) {    }
        }
    }
}
}

Any suggestions would be awesome.

I looked through many questions regarding Jbuttons not showing up, but I am not sure which one is similar to mine. Please point me in the right direction if there is.

Thank you in advance.

Body:
I am unsure, as to which library you are using in order to create the said video. Though in this example, I used the opencv library to create an image from webcam. You have to modify it, in order to make it work for your usecase.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.opencv.core.*;
import org.opencv.videoio.VideoCapture;

public class ApplicationBase {

    private BufferedImage m_Captured_BufferedImage;

    static {
        System.out.println(System.getProperty("java.library.path"));
        System.loadLibrary ( Core.NATIVE_LIBRARY_NAME );
    }

    private void displayGUI ( BufferedImage image, String title, int x, int y ) {
        JFrame frame = new JFrame ( title );
        frame.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );

        JPanel contentPane = new JPanel ( new BorderLayout ( 5, 5 ) );

        PictureDrawer pictureDrawer = new PictureDrawer ( image );
        contentPane.add ( pictureDrawer, BorderLayout.CENTER );

        JButton button = new JButton ( "Click Me not!" );
        contentPane.add ( button, BorderLayout.PAGE_END );

        frame.setContentPane ( contentPane );
        frame.pack ();
        frame.setLocationByPlatform ( true );
        frame.setVisible ( true );
    }

    private void startApp () {
        VideoCapture camera = new VideoCapture ( 0 );

        Mat videoFrame = new Mat ();
        camera.read ( videoFrame );

        if ( camera.read ( videoFrame ) ) {
            m_Captured_BufferedImage = matToBufferedImage ( videoFrame );
            Runnable runnable = new Runnable () {
                @Override
                public void run () {
                    displayGUI ( m_Captured_BufferedImage, "Image", 0, 0 );
                }
            };
            EventQueue.invokeLater ( runnable );
        }
        camera.release ();
    }

    public BufferedImage matToBufferedImage ( Mat videoFrame ) {
        //Mat() to BufferedImage
        int type = 0;
        if ( videoFrame.channels () == 1 ) {
            type = BufferedImage.TYPE_BYTE_GRAY;
        } else if ( videoFrame.channels () == 3 ) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        BufferedImage image = new BufferedImage ( videoFrame.width (), videoFrame.height (), type );
        WritableRaster raster = image.getRaster ();
        DataBufferByte dataBuffer = ( DataBufferByte ) raster.getDataBuffer ();
        byte [] data = dataBuffer.getData ();
        videoFrame.get ( 0, 0, data );

        return image;
    }

    public static void main ( String [] args ) {
        new ApplicationBase ().startApp ();
    }
}

class PictureDrawer extends JComponent {

    private BufferedImage m_BufferedImage;

    public PictureDrawer ( BufferedImage bufferedImage ) {
        this.m_BufferedImage = bufferedImage;
    }

    @Override
    protected void paintComponent ( Graphics g ) {
        super.paintComponent ( g );
        g.drawImage ( m_BufferedImage, 0, 0, this );
    }

    @Override
    public Dimension getPreferredSize () {
        return new Dimension ( m_BufferedImage.getWidth (), m_BufferedImage.getHeight () );
    }
}

I downloaded the OpenCV library from this

Compiled the project with this command:

javac -classpath .;C:\install\opencv\opencv\build\java\opencv-320.jar; -d bin source\*.java

Command to run project:

>java -classpath .;C:\install\opencv\opencv\build\java\opencv-320.jar; -Djava.library.path=C:\install\opencv\opencv\build\java\x64 ApplicationBase


问:
JavaScript test failing - checking for similar items, true if one item or less needs to be switched
Working on this code for a test, passing some but failing others.

Problem:

Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.

Given two arrays a and b, check whether they are similar.

Example:

For a = [1, 2, 3] and b = [1, 2, 3], the output should be
  areSimilar(a, b) = true.

The arrays are equal, no need to swap any elements.

For a = [1, 2, 3] and b = [2, 1, 3], the output should be
  areSimilar(a, b) = true.

My Solution:

function areSimilar(a, b) {
    var error = 0;
    for(var i = 0; i  1){
            return false;
        } else{
            return true;
        }
}```

Example of Test Passed:

Input:

a: [1, 2, 2]
  b: [2, 1, 1]

Output:

false

Expected Output:

false

Example of Test Failed:

Input:

a: [2, 3, 9]
  b: [10, 3, 2]

Output:

true

Expected Output:

false

答:
Here is my solution.

function swapPair(a, i, j) {
 var temp;
 temp = a[i];
 a[i] = a[j];
 a[j] = temp;
 return a;
}

function areSame(a, b) {
 var i;
 for (i = 0; i < a.length; i += 1) {
  if (a[i] !== b[i]) {
   return false;
  }
 }
 return true;
}

function areSimilar(a, b) {
 var i, temp;
 for (i = 0; i < a.length; i += 1) {
  // do we need to try a swap?
  if (a[i] !== b[i]) {
   for (j = i + 1; j < a.length; j += 1) {
    a = swapPair(a, i, j);
    if (areSame(a, b) === true) { // do we have a match now?
     return true;
    } else {
     a = swapPair(a, i, j); // swap back so we can try another pair
    }
   }
   // we could not find a swap that satisfies areSame(a, b)
   return false;
  }
 }
 // no swap was required
 return true;
}

console.log(areSimilar([1, 2, 3], [1, 2, 3]) === true);
console.log(areSimilar([1, 2, 3], [2, 1, 3]) === true);
console.log(areSimilar([1, 2, 2], [2, 1, 1]) === false);
console.log(areSimilar([2, 3, 9], [10, 3, 2]) === false);
console.log(areSimilar([2, 3, 1], [1, 3, 2]) === true);
console.log(areSimilar([832, 998, 148, 570, 533, 561, 894, 147, 455, 279], [832, 998, 148, 570, 533, 561, 455, 147, 894, 279]) === true);
console.log(areSimilar([2, 1, 1], [1, 1, 2]) === true);```

Body:
Working on this code for a test, passing some but failing others.

Problem:

Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.

Given two arrays a and b, check whether they are similar.

Example:

For a = [1, 2, 3] and b = [1, 2, 3], the output should be
  areSimilar(a, b) = true.

The arrays are equal, no need to swap any elements.

For a = [1, 2, 3] and b = [2, 1, 3], the output should be
  areSimilar(a, b) = true.

My Solution:

function areSimilar(a, b) {
    var error = 0;
    for(var i = 0; i  1){
            return false;
        } else{
            return true;
        }
}

Example of Test Passed:

Input:

a: [1, 2, 2]
  b: [2, 1, 1]

Output:

false

Expected Output:

false

Example of Test Failed:

Input:

a: [2, 3, 9]
  b: [10, 3, 2]

Output:

true

Expected Output:

false


问:
Error: Could not find or load main class org.test.spark.streamExample
I was trying to execute sample basic sparkstreaming example in Scala IDE, but I am getting below error:

```<code>Error: Could not find or load main class org.test.spark.streamExample.
</code>```

Could anyone help me to sort out this please.

答:
The main reason for such error is that some compilation errors may exists, it could be some any build path related issue or some code issue.
Check the issue in problem tab .

Other than this , check Scala Library version in your POM and Scala Installation version in Scala compiler

Body:
I was trying to execute sample basic sparkstreaming example in Scala IDE, but I am getting below error:

Error: Could not find or load main class org.test.spark.streamExample.

Could anyone help me to sort out this please.


问:
data attribute not updated before page refresh with jQuery
In my project I have a table, each of its rows holding id and title as data attributes

```<code><tr data-id="1" data-title="title"><td id="td_title">some text</td></tr>
</code>```

I use jQuery to update the data-tile attribute

```<code>$newTitle = 'newTitle';
$row_to_update = $("tr").find("[data-id='1']");
$row_to_update.attr('data-title', newTitle );
</code>```

So after that, in  the html I can see the updated values, but if I try this:

```<code>$var = $row_to_update.data('title');
alert($var);
</code>```

It returns the old title, unless I load the page again.
I suppose I have to clear the cache, but I only found $.domCache, which is not applicable to jQuery and also saw and tried

```<code>function clearjQueryCache(){
    for (var x in jQuery.cache){
        delete jQuery.cache[x];
    }
}
</code>```

but obviously not correct, as everything stopped working

答:
.find() method allows us to search through the descendants of these
  elements in the DOM tree and construct a new jQuery object from the
  matching elements. The .find() and .children() methods are similar,
  except that the latter only travels a single level down the DOM tree.

ًWith $("tr").find("[data-id='1']"); tr doesn't have  element with [data-id='1'] to find it .. So no need to use .find()

```<code>$newTitle = 'newTitle';
$row_to_update = $("tr[data-id='1']");
$row_to_update.data('title', $newTitle );
//then
$var = $row_to_update.data('title');
alert($var);  // the output should be newTitle
</code>```

Working demo

$(document).ready(function(){
  $newTitle = 'newTitle';
  $row_to_update = $("tr[data-id='1']");
  $row_to_update.data('title', $newTitle );
  //then
  $var = $row_to_update.data('title');
  alert($var);  // the output should be newTitle
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1" data-title="title"><td id="td_title">some text</td></tr>
<tr data-id="2" data-title="title"><td id="td_title">some text</td></tr>
</table></code>```

Body:
In my project I have a table, each of its rows holding id and title as data attributes

some text

I use jQuery to update the data-tile attribute

$newTitle = 'newTitle';
$row_to_update = $("tr").find("[data-id='1']");
$row_to_update.attr('data-title', newTitle );

So after that, in  the html I can see the updated values, but if I try this:

$var = $row_to_update.data('title');
alert($var);

It returns the old title, unless I load the page again.
I suppose I have to clear the cache, but I only found $.domCache, which is not applicable to jQuery and also saw and tried

function clearjQueryCache(){
    for (var x in jQuery.cache){
        delete jQuery.cache[x];
    }
}

but obviously not correct, as everything stopped working

Body:
.find() method allows us to search through the descendants of these
  elements in the DOM tree and construct a new jQuery object from the
  matching elements. The .find() and .children() methods are similar,
  except that the latter only travels a single level down the DOM tree.

ًWith $("tr").find("[data-id='1']"); tr doesn't have  element with [data-id='1'] to find it .. So no need to use .find()

$newTitle = 'newTitle';
$row_to_update = $("tr[data-id='1']");
$row_to_update.data('title', $newTitle );
//then
$var = $row_to_update.data('title');
alert($var);  // the output should be newTitle

Working demo

$(document).ready(function(){
  $newTitle = 'newTitle';
  $row_to_update = $("tr[data-id='1']");
  $row_to_update.data('title', $newTitle );
  //then
  $var = $row_to_update.data('title');
  alert($var);  // the output should be newTitle
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1" data-title="title"><td id="td_title">some text</td></tr>
<tr data-id="2" data-title="title"><td id="td_title">some text</td></tr>
</table>


问:
Powershell convert string to array
How do I change:

```<code>$Text = "Apple Pear Peach Banana"
</code>```

to

```<code>$Text = @("Apple", "Pear", "Peach", "Banana")
</code>```

I am planning to feed the array to a foreach loop. The input the user is prompted to enter fruit with a space between (I will use Read-Host for that). So then I need to convert a space-separated string to an array for the foreach loop.

Thank you...

答:
$Text.Split(' ')

need more characters for answer.

Title: Powershell convert string to array

Body:
How do I change:

$Text = "Apple Pear Peach Banana"

to

$Text = @("Apple", "Pear", "Peach", "Banana")

I am planning to feed the array to a foreach loop. The input the user is prompted to enter fruit with a space between (I will use Read-Host for that). So then I need to convert a space-separated string to an array for the foreach loop.

Thank you...


问:
JMeter Regular Expression Not Handling String with Variable and '$'
Version: 3.0

I want to use a variable to parse a response that includes a '$'

```<code>${__V(${Variable})}\)</a></span><!-- R_PAGE_POSITION\$(..?)
</code>```

This is not bringing back a match, but does if I either replace the variable with a value e.g.

```<code>12345\)</a></span><!-- R_CLASS_NAME\$(..?)
</code>```

Or omit from the dollar sign onwards:

```<code>${__V(${Variable})}\)</a></span><!-- R_PAGE_POSITION
</code>```

This suggests that there is some issue between the Variable syntax and the dollar sign that means they cannot co-exist.

Anyone experience a similar issue?

答:
You need to use double backslash here:

```<code>${__V(${Variable})}\)</a></span><!-- R_PAGE_POSITION\\$(..?)
                                                    ^^
</code>```

That way, you let JMeter know that it is not a variable marker inside a JMeter expression (the first backslash), and that it is not the end-of-string anchor (the second backslash).

Body:
Version: 3.0

I want to use a variable to parse a response that includes a '$'

${__V(${Variable})}\)

Body:
You need to use double backslash here:

${__V(${Variable})}\)</a></span><!-- R_PAGE_POSITION\\$(..?)
                                                    ^^

That way, you let JMeter know that it is not a variable marker inside a JMeter expression (the first backslash), and that it is not the end-of-string anchor (the second backslash).


问:
Running XQuery on the command line
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

```<code>Error: Could not find or load main class net.sf.saxon.Query
</code>```

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".

答:
My Xidel is a command-line XQuery 3.0 tool.

```<code> xidel your-file.xml --xquery 'your-xquery'
</code>```

But "select where" is not XQuery. XQuery looks like for ... in .. where .. return or //*[..where..], e.g.

```<code>xidel your-file.xml -e "//*[@type = 'something']"
</code>```

With Xidel -e is short for --xpath or --xquery depending on the following argument (XPath is pretty much the same as XQuery if you are not trying to create a new XML document), and if you need " or ' depends if you call it from the bash or cmd console

Title: Running XQuery on the command line

Body:
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

Error: Could not find or load main class net.sf.saxon.Query

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".

Body:
My Xidel is a command-line XQuery 3.0 tool.

 xidel your-file.xml --xquery 'your-xquery'

But "select where" is not XQuery. XQuery looks like for ... in .. where .. return or //*[..where..], e.g.

xidel your-file.xml -e "//*[@type = 'something']"

With Xidel -e is short for --xpath or --xquery depending on the following argument (XPath is pretty much the same as XQuery if you are not trying to create a new XML document), and if you need " or ' depends if you call it from the bash or cmd console


答:
Use Split()</p>

```<code>$text = $text.Split(" ")
</code>```

Title: Powershell convert string to array

Body:
Use Split()

$text = $text.Split(" ")


问:
Quick and dirty solution for communication between processes in different machines
I have two processes written in java in two machines within my network that should pass simple chunks of data to each other.

I'm looking for a quick and dirty way (without resorting to writing files and polling for changes on network share files)

答:
I find RMI to be somewhat annoying.  You have to define 3 files for a single remote object and you have to learn stuff that's outside the normal development process if you don't already know how to use it (I believe there is a separate compiler step involved).

There may be tools to make it work, but might I suggest just opening a simple socket?  They are pretty close to trivial to use.

The only caveat is that you should be careful about defining what flows between the computers.

OwnerDisplayName: Dani

OwnerDisplayName: Bill K


问:
Linq GroupBy and multiple columns
```<code>class ExpenseClaim
{
    int EmployeeId;
    int Team;
    double Cost;
}

List<EmployeeExpense> GetEmployeeExpenses()
{
    return _expenseClaims // `_expenseClaims` is `List<ExpenseClaim>`
             .GroupBy(e => e.EmployeeId)
             .Select(x =>
                new EmployeeExpense(
                        x.Key,
                        // TODO: employee team?
                        x.Sum(e => e.Cost)
                );
}
</code>```

Excuse the rather contrived example.

How do I get the employee team in GetEmployeeExpenses? I'm assuming I need a second group by but I can't work out the syntax.

Note that for a given employee, their Team will always be the same anyway, so I'd be happy to take the Team of for example the first grouped by record.

so...

```<code>ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }

=>

EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }
</code>```

答:
Query expression version of it (might be easier to read, depending on situation and amount of grouping):

```<code>IEnumerable<EmployeeExpense> GetEmployeeExpenses(List<ExpenseClaim> claims)
{
    return
        from c in claims
        group c by c.EmployeeId into groupedById
        from g in groupedById
        group g by g.Team into groupedByTeam
        let firstElement = groupedByTeam.First()
        select new EmployeeExpense {
            EmployeeId = firstElement.EmployeeId,
            Team = firstElement.Team,
            Cost = groupedByTeam.Sum(e => e.Cost)
        };
}
</code>```

Title: Linq GroupBy and multiple columns

Body:
class ExpenseClaim
{
    int EmployeeId;
    int Team;
    double Cost;
}

List<EmployeeExpense> GetEmployeeExpenses()
{
    return _expenseClaims // `_expenseClaims` is `List<ExpenseClaim>`
             .GroupBy(e => e.EmployeeId)
             .Select(x =>
                new EmployeeExpense(
                        x.Key,
                        // TODO: employee team?
                        x.Sum(e => e.Cost)
                );
}

Excuse the rather contrived example.

How do I get the employee team in GetEmployeeExpenses? I'm assuming I need a second group by but I can't work out the syntax.

Note that for a given employee, their Team will always be the same anyway, so I'd be happy to take the Team of for example the first grouped by record.

so...

ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }

=>

EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }

Body:
Query expression version of it (might be easier to read, depending on situation and amount of grouping):

IEnumerable<EmployeeExpense> GetEmployeeExpenses(List<ExpenseClaim> claims)
{
    return
        from c in claims
        group c by c.EmployeeId into groupedById
        from g in groupedById
        group g by g.Team into groupedByTeam
        let firstElement = groupedByTeam.First()
        select new EmployeeExpense {
            EmployeeId = firstElement.EmployeeId,
            Team = firstElement.Team,
            Cost = groupedByTeam.Sum(e => e.Cost)
        };
}


问:
Using Visual Studio 2015 with a newer UE
I have a windows 8 which means I am unable to install virtual studio 2017, I cannot upgrade to 8.1 because I have already tried and it crashed my entire computer and forced me to factory reset, and I'm not taking the same chance again. Is there any way I can use virtual studio 2015 with unreal engine 4.16? If not, what other IDE's can I use and how would I use them with unreal engine. Thank you for any responses. </p>

答:
You can use Visual Studio 2015 without any problems, altough Visual Studio 2017  is recommended.

I think EPIC officially only supports Visual Studio as IDE, but you can use many alternatives, for example CLion or KDE. Just search around in the Wiki or Answerhub and you will find the necessary steps to set everything up.


问:
Does struct assignment guarantee padding to also be equal
Say I have a struct with 2 fields and the implementation of C that I have also has some padding between these fields.

If I create two variables of the struct and assign one to another, will the padding be guaranteed to be equal?

I know that for most compilers it would be so (because they just call memcpy), but I want to know what is specified about the padding in the standard?

Intention for this question is, can I use memcmp to check equality of structs.

Say I have a compiler which emits code that just assigns all the members of the struct instead of doing memcpy, will it be a valid implementation of the assignment of struct operation?

答:
The standard says in a note 51 of 6.2.6.1 General:

Thus, for example, structure assignment need not copy any padding bits.


问:
PHP : Gmail authentication in my application - will oAuth do this better?
In my project all the Gmail users can access my application. So I referred Google API, The suggest me to use OpenID / OAuth.

Could you say which one is better.

I referred many no. of tutorials regarding oAuth, but none of them satisfied me.

So Please advice, the simple method to achieve this.

答:
I would recommend the OpenID+OAuth Hybrid protocol as it lets you combine an OpenID request with an OAuth authentication request. This extension is useful you if require the use both OpenID and OAuth, particularly in that it simplifies the process for users by requesting their approval once instead of twice.

It means you can use google APIs aswell as pull back the user's information. This is a very interesting article on the differences and similarities of oAuth + openID.

However, if you don't need to use any of the google API's and just need to pull back user info have a look at LightOpenID - it is really easy to use. and has an out-the-box example with Google OpenID


问:
Removing a trailing slash using htaccess for specefic route
I'm adding a trailing slash at the end of the URL using .htaccess.
Is there a way to exclude a specific route from adding that trailing slash

What is what happens now:

```<code>example.com/sitemap/
</code>```

What I want:

```<code>example.com/sitemap
</code>```

This is my .htaccess file:

```<code></IfModule>

        RewriteEngine on
        RewriteCond %{HTTPS} !on
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

        RewriteCond %{HTTP_HOST} !^$
        RewriteCond %{HTTP_HOST} !^www\. [NC]
        RewriteCond %{HTTPS}s ^on(s)|
        RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]
</code>```

答:
```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]
</code>```

This would seem to be the code that is appending a trailing slash. So, you can include an additional condition to exclude the mentioned URL. For example:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/sitemap$
RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]
</code>```

The ! prefix on the CondPattern negates the regex. So, a pattern like !^/sitemap$ will match any URL that is not /sitemap.

You will need to clear your browser cache before testing.

Body:
I'm adding a trailing slash at the end of the URL using .htaccess.
Is there a way to exclude a specific route from adding that trailing slash

What is what happens now:

example.com/sitemap/

What I want:

example.com/sitemap

This is my .htaccess file:

</IfModule>

        RewriteEngine on
        RewriteCond %{HTTPS} !on
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

        RewriteCond %{HTTP_HOST} !^$
        RewriteCond %{HTTP_HOST} !^www\. [NC]
        RewriteCond %{HTTPS}s ^on(s)|
        RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]

Body:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]

This would seem to be the code that is appending a trailing slash. So, you can include an additional condition to exclude the mentioned URL. For example:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/sitemap$
RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]

The ! prefix on the CondPattern negates the regex. So, a pattern like !^/sitemap$ will match any URL that is not /sitemap.

You will need to clear your browser cache before testing.