问:
Reactjs SPA - Pressing IOS Safari back button updates the url but not the component view
We have a reactjs SPA application where we want to navigate back and forth using browser back button/swipe the screen, if on Mac.

when a user clicks on a link from home page, they will be navigated to a detail page and the url looks like https://example.com/pdetail?prdt=Computer

On detail page, User has an ability to search, and when the user searches(Say Stationery), we update the url and push the url to history and the the detail page component is updated with the searched data.Like

https://example.com/pdetail?prdt=Stationery

```<code> filterSearch(searchval) {
  //search related code to set variables
  let newUrl = setParams(searchval, 'prdt')
  this.props.history.push(`?${newUrl}`);
// dispatch an api call to get data
}

 export function setParams(query = "", param) {
  const searchParams = new URLSearchParams(window.location.search);
  searchParams.set(param, query.trim());
  return searchParams.toString();
}
</code>```

Now when the user browse back using the browser back button, we expect it to go the previous data(https://example.com/pdetail?prdt=Computer) from (https://example.com/pdetail?prdt=Stationery) and Vice Versa as we move back and forth. It is working fine in chrome and IE.

But in Safari, as the user presses back button, url is changing in the browser but the component view is not.

as we navigate back, I noticed that it did not go to ComponentDidMount as we go to the same page. But it goes ComponentDidUpdate so I added my code in there.

```<code>componentDidUpdate() {
    window.onpopstate  = (e) => {

        if(this.props.history.action == 'POP')
        {
            e.preventDefault();

            const search = window.location.search;

            const params = new URLSearchParams(search);

            if(params.has('prdt') === true)
            {
                 const selectedprdt = params.get('prdt');

                 this.props.fetchDetails('FETCH_PRDT_DETAILS' , selectedprdt);
            }

        }
    }
}
</code>```

Let me know how can get this back forth page navigation with consistent url and data in Safari.
It is working fine in IE and chrome.

EDIT:

I have edited my code to add an eventListener in componentDidMount and UI is working in Safari. But when I see in the logs, I noticed the event runs multiple times not just once, which is very inefficient as we are making server calls.

```<code>componentDidMount()
{

    const selectedprdt = getParams(window.location, 'prdt');
    if(selectedprdt !== '')
    {
        this.props.fetchDetails('FETCH_PRDT_DETAILS' , selectedprdt);
    }

   window.addEventListener('popstate', this.handleBackButton)
}

handleBackButton = (e) =>
{

    if(this.props.history.action == 'POP')
    {

        const search = window.location.search;

        const params = new URLSearchParams(search);

        if(params.has('prdt') === true)
        {
             const selectedMarket = params.get('prdt');

             this.props.fetchDetails('FETCH_PRDT_DETAILS' , selectedprdt);
        }

        e.preventDefault();

    }

}

</code>```

Please let me know how to stop eventListener to executing the calls multiple times.

Thanks,

答:
I had to remove the same listener on component Unmount.</p>

```<code>componentWillUnMount()
{
  window.removeEventListener('popstate', this.handleBackButton)
}

</code>```

Body:
We have a reactjs SPA application where we want to navigate back and forth using browser back button/swipe the screen, if on Mac.

when a user clicks on a link from home page, they will be navigated to a detail page and the url looks like https://example.com/pdetail?prdt=Computer

On detail page, User has an ability to search, and when the user searches(Say Stationery), we update the url and push the url to history and the the detail page component is updated with the searched data.Like

https://example.com/pdetail?prdt=Stationery

 filterSearch(searchval) {
  //search related code to set variables
  let newUrl = setParams(searchval, 'prdt')
  this.props.history.push(`?${newUrl}`);
// dispatch an api call to get data
}

 export function setParams(query = "", param) {
  const searchParams = new URLSearchParams(window.location.search);
  searchParams.set(param, query.trim());
  return searchParams.toString();
}

Now when the user browse back using the browser back button, we expect it to go the previous data(https://example.com/pdetail?prdt=Computer) from (https://example.com/pdetail?prdt=Stationery) and Vice Versa as we move back and forth. It is working fine in chrome and IE.

But in Safari, as the user presses back button, url is changing in the browser but the component view is not.

as we navigate back, I noticed that it did not go to ComponentDidMount as we go to the same page. But it goes ComponentDidUpdate so I added my code in there.

componentDidUpdate() {
    window.onpopstate  = (e) => {

        if(this.props.history.action == 'POP')
        {
            e.preventDefault();

            const search = window.location.search;

            const params = new URLSearchParams(search);

            if(params.has('prdt') === true)
            {
                 const selectedprdt = params.get('prdt');

                 this.props.fetchDetails('FETCH_PRDT_DETAILS' , selectedprdt);
            }

        }
    }
}

Let me know how can get this back forth page navigation with consistent url and data in Safari.
It is working fine in IE and chrome.

EDIT:

I have edited my code to add an eventListener in componentDidMount and UI is working in Safari. But when I see in the logs, I noticed the event runs multiple times not just once, which is very inefficient as we are making server calls.

componentDidMount()
{

    const selectedprdt = getParams(window.location, 'prdt');
    if(selectedprdt !== '')
    {
        this.props.fetchDetails('FETCH_PRDT_DETAILS' , selectedprdt);
    }

   window.addEventListener('popstate', this.handleBackButton)
}

handleBackButton = (e) =>
{

    if(this.props.history.action == 'POP')
    {

        const search = window.location.search;

        const params = new URLSearchParams(search);

        if(params.has('prdt') === true)
        {
             const selectedMarket = params.get('prdt');

             this.props.fetchDetails('FETCH_PRDT_DETAILS' , selectedprdt);
        }

        e.preventDefault();

    }

}

Please let me know how to stop eventListener to executing the calls multiple times.

Thanks,

Body:
I had to remove the same listener on component Unmount.

componentWillUnMount()
{
  window.removeEventListener('popstate', this.handleBackButton)
}


来源: stackexchange

问:
How to use GitHub Actions with multiple repositories and deploy to GitHub Pages?
Is there a way to setup Github Actions to run multiple npm run builds? I wanted to use multiple repos and set them as different webpages on the main site.

Imagine I had 3 repos: Main, Angular App, and React App.

The Main repo would have my landing site. Angular App and React App would be two different sites.

From foobar.github.io (main repo), I would go to foobar.github.io/angular to navigate to my Angular App. foobar.github.io/react would be a react app.

Each application would be in 3 different repositories. Is there a way for me to push to my Angular App and GitHub Actions would automatically do an ng build --prod --base-href='angular', and update that page or even run a build for all repositories and deploy it?

To do this locally, I would have to do a build command on each repository, and then drag each prod folder into my repo, then push it up, which, in my opinion, can get very inefficient.

答:
The easiest way to do this would be to add a workflow to each repository that updates the corresponding area in Pages. I.e. in the "Main" repo, it would look something like:

```<code>on: push

jobs:
  main:
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Build
        run: TODO

      - name: Publish
        run: TODO
</code>```

And in the other repositories, you'd have something similar.  For example in the Angular repository:

```<code>on: push

jobs:
  angular:
    steps:
      - name: Checkout App
        uses: actions/checkout@v2

      - name: Build Angular
        run: |
          npm ci
          npm run build
          ng build --prod --base-href='angular'

      - name: Publish
        run: TODO
</code>```

If you wanted to only publish when you update Main, you could have a workflow in your Main repository that builds and publishes all three, e.g.:

```<code>on: push

jobs:
  main:
    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
        with:
          repository: my-org/main
          path: main

      - name: Build
        run: TODO
        working-directory: ./main

      - name: Publish
        run: TODO
        working-directory: ./main

  react:
    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
        with:
          repository: my-org/react
          path: react

      - name: Build React
        run: TODO
        working-directory: ./react

      - name: Publish
        run: TODO
        working-directory: ./react

  angular:
    steps:
      - name: Checkout App
        uses: actions/checkout@v2
        with:
          repository: my-org/angular
          path: angular

      - name: Build Angular
        run: |
          npm ci
          npm run build
          ng build --prod --base-href='angular',
        working-directory: ./angular

      - name: Publish
        run: TODO
        working-directory: ./angular
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The easiest way to do this would be to add a workflow to each repository that updates the corresponding area in Pages. I.e. in the "Main" repo, it would look something like:

on: push

jobs:
  main:
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Build
        run: TODO

      - name: Publish
        run: TODO

And in the other repositories, you'd have something similar.  For example in the Angular repository:

on: push

jobs:
  angular:
    steps:
      - name: Checkout App
        uses: actions/checkout@v2

      - name: Build Angular
        run: |
          npm ci
          npm run build
          ng build --prod --base-href='angular'

      - name: Publish
        run: TODO

If you wanted to only publish when you update Main, you could have a workflow in your Main repository that builds and publishes all three, e.g.:

on: push

jobs:
  main:
    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
        with:
          repository: my-org/main
          path: main

      - name: Build
        run: TODO
        working-directory: ./main

      - name: Publish
        run: TODO
        working-directory: ./main

  react:
    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
        with:
          repository: my-org/react
          path: react

      - name: Build React
        run: TODO
        working-directory: ./react

      - name: Publish
        run: TODO
        working-directory: ./react

  angular:
    steps:
      - name: Checkout App
        uses: actions/checkout@v2
        with:
          repository: my-org/angular
          path: angular

      - name: Build Angular
        run: |
          npm ci
          npm run build
          ng build --prod --base-href='angular',
        working-directory: ./angular

      - name: Publish
        run: TODO
        working-directory: ./angular


问:
How to find all combinations possible from alphabet and numbers
So basically i want it to start with for example aaaa then go to aaab and once it has done all combinations possible with 4 digits i want it to start doing 5 digits, i want this to put in a variable so it puts in aaaa when aaaa is checked it switches to aaab and so on.</p>

答:
You can co-opt itertools.product for this:

```<code>def my_generator(initial_length):
    while True:
        # get all permutations of length 4, in order
        for p in itertools.product('abcdefghijklmnopqrstuvwxyz', repeat=initial_length):
            yield ''.join(p)
        # when we run out, increase the length and start again
        initial_length += 1
</code>```

Usage:

```<code>>>> x = my_generator(4)
>>> next(x)
'aaaa'
>>> next(x)
'aaab'
>>> next(x)
'aaac'
>>> [next(x) for _ in range(26**4 - 4)][-1]
'zzzy'
>>> next(x)
'zzzz'
>>> next(x)
'aaaaa'
>>> next(x)
'aaaab'
</code>```

Body:
You can co-opt itertools.product for this:

def my_generator(initial_length):
    while True:
        # get all permutations of length 4, in order
        for p in itertools.product('abcdefghijklmnopqrstuvwxyz', repeat=initial_length):
            yield ''.join(p)
        # when we run out, increase the length and start again
        initial_length += 1

Usage:

>>> x = my_generator(4)
>>> next(x)
'aaaa'
>>> next(x)
'aaab'
>>> next(x)
'aaac'
>>> [next(x) for _ in range(26**4 - 4)][-1]
'zzzy'
>>> next(x)
'zzzz'
>>> next(x)
'aaaaa'
>>> next(x)
'aaaab'


问:
Vertical centering working in almost every browser, but not in IE7
It's actually two part question regarding my simple page (that will be replaced some day with real content), HTML+CSS boilerplate used there for vertical centering and IE7.

http://engitize.net/

Can anyone provide detailed explanation why the page is displayed correctly in non-IE browsers (Chrome, Fx, Opera), almost all semi-recent to recent IEs (IE5.5, IE6, IE8, IE9), but not in IE7?

I am especially interested in: it works in IE6, yet it doesn't work in IE7, because... kind of explanation.

What should be changed to make div#c properly centered vertically in IE7?

I am using specific height for div#c, but used boilerplate is height-agnostic and fix should preserve this feature.

Spoiling other browsers is not an option, unless it's IE5.5 (ok, IE6 too, but only if it is really unavoidable).

Changing <!DOCTYPE html> and turning IEs into quirks mode is also not accepted (and it's a pretty bad practice for newly developed pages).

If you don't have IE7 (just as I), you can visit http://ipinfo.info/netrenderer/ or http://browserling.com/, paste URL there and choose IE7 to see the problem yourself.

Because the page will change after accepting some answer, I'm providing snapshot of relevant HTML and CSS parts from it (with logo URL changed to be absolute).

```<code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
html, body { height: 100%; }
body { background-color: #fff; color: #000; margin: 0px; padding: 0px; }
div { margin: 0px; padding: 0px; }
#outer { position: relative; width: 100%; height: 100%; overflow: visible; }
#outer[id] { display: table; position: static; }
#middle { position: absolute; top: 50%; width: 100%; text-align: center; } /* for explorer only*/
#middle[id] { display: table-cell; vertical-align: middle; position: static; }
#c { position: relative; top: -50%; } /* for explorer only */
#c { width: 385px; height: 120px; margin-left: auto; margin-right: auto; }
#c { background-image: url(http://engitize.net/engitize.png); background-repeat: no-repeat; background-position: center top; }
#c div { position: relative; top: 100px; width: 100%; color: #666; font-weight: bold; font-family: serif; font-size: 12px; text-align: right; }
#footer { width: 100%; text-align: center; height: 15px; padding: 5px 0 0 0; margin: -20px auto 0 auto; border: 0; background-color: #def; }
#footer div { padding: 0px 5px 0px 5px; text-align: right; font-size: 10px; font-family: sans-serif; }
a { text-decoration: none; color: #006; }
a:hover { color: #00c; }
p { margin: 0px; padding: 0px; }
</style>
</head>
<body>
<div id="outer"><div id="middle"><div id="c"><div>
because history is important!
</div></div></div></div>
<div id="footer"><div>
<p style="float:left;"><strong>Przemysław Pawełczyk</strong>'s imprint | Coming in 2012!</p>
<p style="float:right;"><a href="http://przemoc.net/">Przemoc's network</a></p>
</div></div>
</body>
</html>
</code>```

答:
your Q#1 has been answered by @thirtydot,  IE7 and below does not support the CSS table properties so another way has to be found for them. and his absolute positioning technique is usually the preferred way to do this as most times in a scenario like this (splash page?)  the width and height of the centred content would be known.

addendum to above per comments:
In answer to why it was working in IE6 and not IE7 even though IE6 doesn't support the table properties either, IE7 was actually picking up the position: static rule from the #middle[id] {} rule - IE7 does understand this type of selector so this means the later absolute/relative positioning was not working the same as it was in IE6

Taking the above into account redoing the CSS to make sure IE7 and 6 got the same CSS and that it was placed later in cascade to override the "good" CSS it turns out the the positioning method is height agnostic too, in the comments there are various links to to test this, but here is the final working version:

Hybrid table cell/positioning method : here

That fiddle does include the image width and heights, but if you remove them and the positioning for the "sub text" it does (or should) show that whatever is in the middle does stay centered

HTML used is the same as the bottom of this answer.. minus the extra  element

CSS:

```<code>html, body { height: 100%; margin: 0; padding: 0;}
body { background-color: #fff; color: #000;  }

#outer {
    position: relative;
    width: 100%;
    height: 100%;
    display: table;
}

#middle {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

#c {
    width: 385px;
    height: 120px;
    margin: 0 auto;
    background: url(http://engitize.net/engitize.png) no-repeat 50% 50%;
}

/**** for IE7 and below ****/
/* hacks but there is another method below */
#middle {
  *position: absolute;
  *top: 50%;
  *width: 100%;
  *text-align: center;
  }

#c {
  *position: relative;
  *top: -50%;
}

/**** end IE7 and below rules ****/

#c div {
    position: relative;
    top: 100px;
    width: 100%;
    color: #666;
    font-weight: bold;
    font-family: serif;
    font-size: 12px;
    text-align: right;
}

#footer {
    width: 100%;
    text-align: center;
    height: 15px;
    padding: 5px 0 0 0;
    margin: -20px auto 0 auto;
    border: 0;
    background-color: #def;
}
#footer div {
    padding: 0px 5px 0px 5px;
    text-align: right; font-size: 10px;
    font-family: sans-serif;
}
#footer p {margin: 0;}
</code>```

As pointed out in comments using the technique that the HTML5 boilerplate uses to class the HTML element conditionally see:

Conditional stylesheets vs CSS hacks?
  Answer: Neither!

means you could replace the IE7 hacks with:

```<code>.ie6 #middle, .ie7 #middle {
  position: absolute;
  top: 50%;
  width: 100%;
  text-align: center;
}

.ie6 #c, .ie7 #c {
  position: relative;
  top: -50%;
}
</code>```

Original alternative - "Matchstick Technique"

You could likely mix the following technique with the "table-cell" technique via conditional comments or hacks, but this (hacky!) technique works across browser as far as my tests have seen

As you've asked for a height agnostic version.. you might or might not like the "matchstick"  technique, this involves using inline blocks and lining them up.. the "matchstick" is a 100% high empty, off page, inline-block element with its vertical-alignment set to "middle" once it's in place the next inline-block (your actual content div) sits beside it and aligns to the middle or it, then using text-align: center; on it you have the horizontal centering too

here's a link to a working example fiddle

Note: I've left your widths intact, but you can test without widths/heights by removing the height & width off #c and also remove the CSS for the #c div text div - in a plain text scenario entering text into either of these divs should 'auto' centre.

and especially note the insertion of the extra  HTML just inside the outer div (that's likely why this is not a preferred method!), this is the "matchstick" that props the whole page open.

Code used in fiddle:

```<code>html, body { height: 100%; margin: 0; padding: 0; }
body { background-color: #fff; color: #000; }

#outer { position: relative; width: 100%; height: 100%;}

/* a matchstick spacer */
#outer i {
 display: inline-block;
 height: 100%;
 width: 1px;
 margin-left: -1px; /* to hide off page */
 margin-right: -4px; /* to remove spacing between this and #middle block */
 vertical-align: middle; /* will make inline block next to it center vertically */
 background: #f00; /* red, not required just to see or not see it */
 }

#middle {
  display: inline-block;
  width: 100%;
  text-align: center;
  vertical-align: middle;
}

/* image 385 * 120 */
#c {
  display: inline-block;
  /* presuming image heights, but it wouldn't matter if there was width/height here or not */
  width: 385px;
  height: 120px;
  background: url(http://engitize.net/engitize.png) no-repeat 50% 50%;
}

#middle, #c { /* IE hack for inline block on block level elements */
 *display: inline;
}

#c div { position: relative; top: 100px; width: 100%; color: #666; font-weight: bold; font-family: serif; font-size: 12px; text-align: right; }

#footer { width: 100%; text-align: center; height: 15px; padding: 5px 0 0 0; margin: -20px auto 0 auto; border: 0; background-color: #def; }
#footer div { padding: 0px 5px 0px 5px; text-align: right; font-size: 10px; font-family: sans-serif; }

a { text-decoration: none; color: #006; }
a:hover { color: #00c; }
p { margin: 0px; padding: 0px; }
</code>```

HTML:

```<code><div id="outer">
  <i></i>
  <div id="middle">
      <div id="c"><div>
        because history is important!
      </div></div>
  </div>
</div>

<div id="footer">
  <div>
   <p style="float:left;"><strong>Przemys?aw Pawe?czyk</strong>'s imprint | Coming in 2012!</p>
   <p style="float:right;"><a href="http://przemoc.net/">Przemoc's network</a></p>
  </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's actually two part question regarding my simple page (that will be replaced some day with real content), HTML+CSS boilerplate used there for vertical centering and IE7.

http://engitize.net/

Can anyone provide detailed explanation why the page is displayed correctly in non-IE browsers (Chrome, Fx, Opera), almost all semi-recent to recent IEs (IE5.5, IE6, IE8, IE9), but not in IE7?

I am especially interested in: it works in IE6, yet it doesn't work in IE7, because... kind of explanation.

What should be changed to make div#c properly centered vertically in IE7?

I am using specific height for div#c, but used boilerplate is height-agnostic and fix should preserve this feature.

Spoiling other browsers is not an option, unless it's IE5.5 (ok, IE6 too, but only if it is really unavoidable).

Changing <!DOCTYPE html> and turning IEs into quirks mode is also not accepted (and it's a pretty bad practice for newly developed pages).

If you don't have IE7 (just as I), you can visit http://ipinfo.info/netrenderer/ or http://browserling.com/, paste URL there and choose IE7 to see the problem yourself.

Because the page will change after accepting some answer, I'm providing snapshot of relevant HTML and CSS parts from it (with logo URL changed to be absolute).

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

because history is important!

Przemysław Pawełczyk's imprint | Coming in 2012!

Przemoc's network

Body:
your Q#1 has been answered by @thirtydot,  IE7 and below does not support the CSS table properties so another way has to be found for them. and his absolute positioning technique is usually the preferred way to do this as most times in a scenario like this (splash page?)  the width and height of the centred content would be known.

addendum to above per comments:
In answer to why it was working in IE6 and not IE7 even though IE6 doesn't support the table properties either, IE7 was actually picking up the position: static rule from the #middle[id] {} rule - IE7 does understand this type of selector so this means the later absolute/relative positioning was not working the same as it was in IE6

Taking the above into account redoing the CSS to make sure IE7 and 6 got the same CSS and that it was placed later in cascade to override the "good" CSS it turns out the the positioning method is height agnostic too, in the comments there are various links to to test this, but here is the final working version:

Hybrid table cell/positioning method : here

That fiddle does include the image width and heights, but if you remove them and the positioning for the "sub text" it does (or should) show that whatever is in the middle does stay centered

HTML used is the same as the bottom of this answer.. minus the extra <i></i> element

CSS:

html, body { height: 100%; margin: 0; padding: 0;}
body { background-color: #fff; color: #000;  }

#outer {
    position: relative;
    width: 100%;
    height: 100%;
    display: table;
}

#middle {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

#c {
    width: 385px;
    height: 120px;
    margin: 0 auto;
    background: url(http://engitize.net/engitize.png) no-repeat 50% 50%;
}

/**** for IE7 and below ****/
/* hacks but there is another method below */
#middle {
  *position: absolute;
  *top: 50%;
  *width: 100%;
  *text-align: center;
  }

#c {
  *position: relative;
  *top: -50%;
}

/**** end IE7 and below rules ****/

#c div {
    position: relative;
    top: 100px;
    width: 100%;
    color: #666;
    font-weight: bold;
    font-family: serif;
    font-size: 12px;
    text-align: right;
}

#footer {
    width: 100%;
    text-align: center;
    height: 15px;
    padding: 5px 0 0 0;
    margin: -20px auto 0 auto;
    border: 0;
    background-color: #def;
}
#footer div {
    padding: 0px 5px 0px 5px;
    text-align: right; font-size: 10px;
    font-family: sans-serif;
}
#footer p {margin: 0;}

As pointed out in comments using the technique that the HTML5 boilerplate uses to class the HTML element conditionally see:

Conditional stylesheets vs CSS hacks?
  Answer: Neither!

means you could replace the IE7 hacks with:

.ie6 #middle, .ie7 #middle {
  position: absolute;
  top: 50%;
  width: 100%;
  text-align: center;
}

.ie6 #c, .ie7 #c {
  position: relative;
  top: -50%;
}

Original alternative - "Matchstick Technique"

You could likely mix the following technique with the "table-cell" technique via conditional comments or hacks, but this (hacky!) technique works across browser as far as my tests have seen

As you've asked for a height agnostic version.. you might or might not like the "matchstick"  technique, this involves using inline blocks and lining them up.. the "matchstick" is a 100% high empty, off page, inline-block element with its vertical-alignment set to "middle" once it's in place the next inline-block (your actual content div) sits beside it and aligns to the middle or it, then using text-align: center; on it you have the horizontal centering too

here's a link to a working example fiddle

Note: I've left your widths intact, but you can test without widths/heights by removing the height & width off #c and also remove the CSS for the #c div text div - in a plain text scenario entering text into either of these divs should 'auto' centre.

and especially note the insertion of the extra <i></i> HTML just inside the outer div (that's likely why this is not a preferred method!), this is the "matchstick" that props the whole page open.

Code used in fiddle:

html, body { height: 100%; margin: 0; padding: 0; }
body { background-color: #fff; color: #000; }

#outer { position: relative; width: 100%; height: 100%;}

/* a matchstick spacer */
#outer i {
 display: inline-block;
 height: 100%;
 width: 1px;
 margin-left: -1px; /* to hide off page */
 margin-right: -4px; /* to remove spacing between this and #middle block */
 vertical-align: middle; /* will make inline block next to it center vertically */
 background: #f00; /* red, not required just to see or not see it */
 }

#middle {
  display: inline-block;
  width: 100%;
  text-align: center;
  vertical-align: middle;
}

/* image 385 * 120 */
#c {
  display: inline-block;
  /* presuming image heights, but it wouldn't matter if there was width/height here or not */
  width: 385px;
  height: 120px;
  background: url(http://engitize.net/engitize.png) no-repeat 50% 50%;
}

#middle, #c { /* IE hack for inline block on block level elements */
 *display: inline;
}

#c div { position: relative; top: 100px; width: 100%; color: #666; font-weight: bold; font-family: serif; font-size: 12px; text-align: right; }

#footer { width: 100%; text-align: center; height: 15px; padding: 5px 0 0 0; margin: -20px auto 0 auto; border: 0; background-color: #def; }
#footer div { padding: 0px 5px 0px 5px; text-align: right; font-size: 10px; font-family: sans-serif; }

a { text-decoration: none; color: #006; }
a:hover { color: #00c; }
p { margin: 0px; padding: 0px; }

HTML:

<div id="outer">
  <i></i>
  <div id="middle">
      <div id="c"><div>
        because history is important!
      </div></div>
  </div>
</div>

<div id="footer">
  <div>
   <p style="float:left;"><strong>Przemys?aw Pawe?czyk</strong>'s imprint | Coming in 2012!</p>
   <p style="float:right;"><a href="http://przemoc.net/">Przemoc's network</a></p>
  </div>
</div>


问:
Why does this fail using HashMap In Java?
```<code>import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        //Use inputs from https://pastebin.com/DMQ6xqKe and assign to s * t, as stackoverflow limited character use
        String s = "";
        String t = "";

        System.out.println(isAnagram(s, t));
    }

    public static boolean isAnagram(String s, String t) {
        HashMap<Character, Integer> sMap = new HashMap<>();
        HashMap<Character, Integer> tMap = new HashMap<>();

        if(s.length() != t.length())
        {
            return false;
        }

        for(int i = 0; i < s.length(); i++)
        {
            if(sMap.containsKey(s.charAt(i)))
            {
                sMap.replace(s.charAt(i), sMap.get(s.charAt(i)) + 1);
            }
            else
            {
                sMap.put(s.charAt(i), 1);
            }
        }

        for(int i = 0; i < t.length(); i++)
        {
            if(tMap.containsKey(t.charAt(i)))
            {
                tMap.replace(t.charAt(i), tMap.get(t.charAt(i)) + 1);
            }
            else
            {
                tMap.put(t.charAt(i), 1);
            }
        }

        //FAILS BUT WHY!?!??!?
        for(int i = 0; i < s.length(); i++)
        {
            System.out.println("outside " + sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
            if(sMap.get(s.charAt(i)) != tMap.get(s.charAt(i)))
            {
                System.out.println(sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
                return false;
            }
        }

        //PASSES BUT PREVIOUS FAILS?!!?!??!
        // if(!sMap.equals(tMap))
        // {
        //     return false;
        // }

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

This code fails but the commented code using .equals works. I don't really understand. Logged the values, they matched but the check fails saying different values.

答:
It is because of the implementation of equals method in HashMap. in this implementation
tow maps are equal if each (key, value) pair in the first map equals to (key, value) pair in the second map. and in this implementation two key, value pair are equal if both key reference the same object and both value reference the same object. here because your map may contain same key, value but in different object they are not equal.</p>

Body:
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        //Use inputs from https://pastebin.com/DMQ6xqKe and assign to s * t, as stackoverflow limited character use
        String s = "";
        String t = "";

        System.out.println(isAnagram(s, t));
    }

    public static boolean isAnagram(String s, String t) {
        HashMap<Character, Integer> sMap = new HashMap<>();
        HashMap<Character, Integer> tMap = new HashMap<>();

        if(s.length() != t.length())
        {
            return false;
        }

        for(int i = 0; i < s.length(); i++)
        {
            if(sMap.containsKey(s.charAt(i)))
            {
                sMap.replace(s.charAt(i), sMap.get(s.charAt(i)) + 1);
            }
            else
            {
                sMap.put(s.charAt(i), 1);
            }
        }

        for(int i = 0; i < t.length(); i++)
        {
            if(tMap.containsKey(t.charAt(i)))
            {
                tMap.replace(t.charAt(i), tMap.get(t.charAt(i)) + 1);
            }
            else
            {
                tMap.put(t.charAt(i), 1);
            }
        }

        //FAILS BUT WHY!?!??!?
        for(int i = 0; i < s.length(); i++)
        {
            System.out.println("outside " + sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
            if(sMap.get(s.charAt(i)) != tMap.get(s.charAt(i)))
            {
                System.out.println(sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
                return false;
            }
        }

        //PASSES BUT PREVIOUS FAILS?!!?!??!
        // if(!sMap.equals(tMap))
        // {
        //     return false;
        // }

        return true;
    }
}

This code fails but the commented code using .equals works. I don't really understand. Logged the values, they matched but the check fails saying different values.


问:
Reason for Overflow (G++ vs Clang++)
When I'm compiling the following piece of C++ code using Clang++ and G++

```<code>void ScaleFactor(float32_t scale, int32_t &factor) {
    factor = floor(log2(abs(scale))+1)
    cout << factor << endl;
}
</code>```

where the value of scale equals 0.234375 and factor is passed by reference to an integer variable in another function, I'm getting the following different outputs for factor while debugging using GDB

```<code>(int32_t &) @0x7fffffffdaa0: -2147483648 (Clang++)
(int32_t &) @0x7fffffffda9c: -2 (G++)
</code>```

But, on replacing abs() with fabs() each output matches with the desired output

```<code>(int32_t &) @0x7fffffffdb90: -2 (Clang++)
(int32_t &) @0x7fffffffdddc: -2 (G++)
</code>```

What might be the reason for this discrepancy?

答: See the answer to this post.  abs is generally for integers and fabs is for floating point types.  However, it looks like G++ implementation of abs will handle floats, too.

Title: Reason for Overflow (G++ vs Clang++)

Body:
When I'm compiling the following piece of C++ code using Clang++ and G++

void ScaleFactor(float32_t scale, int32_t &factor) {
    factor = floor(log2(abs(scale))+1)
    cout << factor << endl;
}

where the value of scale equals 0.234375 and factor is passed by reference to an integer variable in another function, I'm getting the following different outputs for factor while debugging using GDB

(int32_t &) @0x7fffffffdaa0: -2147483648 (Clang++)
(int32_t &) @0x7fffffffda9c: -2 (G++)

But, on replacing abs() with fabs() each output matches with the desired output

(int32_t &) @0x7fffffffdb90: -2 (Clang++)
(int32_t &) @0x7fffffffdddc: -2 (G++)

What might be the reason for this discrepancy?


问:
NumPy - Selecting a submatrix from another 2d array
This is my original 2d array A

```<code>[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 0, 0, 8, 8, 8, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
</code>```

Let's say I want to return a 3x3 submatrix of 8's at the middle. I made a boolean mask with this expression A == 8 and it looks like this.

```<code>array([[False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False]])
</code>```

This is the point where I'm stuck. How can I return the submatrix with that boolean mask? If I do A[A == 8], it returns a flat array of 8s like this

```<code>array([8, 8, 8, 8, 8, 8, 8, 8, 8])
</code>```

Another way is getting the row and column numbers with np.where(A == 8) which returns (array([5, 5, 5, 6, 6, 6, 7, 7, 7]), array([3, 4, 5, 3, 4, 5, 3, 4, 5])). How can I return the matrix using them?

Is there any better approach for this problem?

答:
You can try the following </p>

```<code> data = A[np.any(A==8,axis=1)]
 data.T[np.all(data==8,axis=0)]
</code>```

<p>This should give, </p>

```<code> array([[8, 8, 8],
        [8, 8, 8],
        [8, 8, 8]])
</code>```

Body:
This is my original 2d array A

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 0, 0, 8, 8, 8, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Let's say I want to return a 3x3 submatrix of 8's at the middle. I made a boolean mask with this expression A == 8 and it looks like this.

array([[False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False]])

This is the point where I'm stuck. How can I return the submatrix with that boolean mask? If I do A[A == 8], it returns a flat array of 8s like this

array([8, 8, 8, 8, 8, 8, 8, 8, 8])

Another way is getting the row and column numbers with np.where(A == 8) which returns (array([5, 5, 5, 6, 6, 6, 7, 7, 7]), array([3, 4, 5, 3, 4, 5, 3, 4, 5])). How can I return the matrix using them?

Is there any better approach for this problem?

Body:
You can try the following

 data = A[np.any(A==8,axis=1)]
 data.T[np.all(data==8,axis=0)]

This should give,

 array([[8, 8, 8],
        [8, 8, 8],
        [8, 8, 8]])


问:
Writing interrupt handler in x86 real mode assembly
I am learning interrupt handling in x86 real mode using assembly. I am following the below example taken from here :

```<code>.include "common.h"
BEGIN
    CLEAR
    /* Set address of the handler for interrupt 0. */
    movw $handler, 0x00
    /* Set code segment of the handler for interrupt 0. */
    mov %cs, 0x02
    int $0
    PUTC $'b
    hlt
handler:
    PUTC $'a
    iret
</code>```

But when I compile and run the above code,

```<code>$ as --32 -o main.o main.S -g
$ ld -T linker.ld -o main.img --oformat binary -m elf_i386 -nostdlib main.o
$ qemu-system-i386 -hda main.img
</code>```

I get the following error :

```<code>qemu-system-i386: Trying to execute code outside RAM or ROM at 0xf00fff53
This usually means one of the following happened:

(1) You told QEMU to execute a kernel for the wrong machine type, and it crashed on startup (eg trying to run a raspberry pi kernel on a versatilepb QEMU machine)
(2) You didn't give QEMU a kernel or BIOS filename at all, and QEMU executed a ROM full of no-op instructions until it fell off the end
(3) Your guest kernel has a bug and crashed by jumping off into nowhere

This is almost always one of the first two, so check your command line and that you are using the right type of kernel for this machine.
If you think option (3) is likely then you can try debugging your guest with the -d debug options; in particular -d guest_errors will cause the log to include a dump of the guest register state at this point.

Execution cannot continue; stopping here.
</code>```

What am I missing here? Why mov %cs, 0x02 is needed or what its really doing?

I tried debugging this under gdb, when I did step execution line by line, i did not face this error under gdb, which was wierd and am still checking.

EDIT

This is how BEGIN is defined :

```<code>.macro BEGIN
    .local after_locals
    .code16
    cli
    /* Set %cs to 0. */
    ljmp $0, $1f
    1:
    xor %ax, %ax
    /* We must zero %ds for any data access. */
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %fs
    mov %ax, %gs
    mov %ax, %bp
    /* Automatically disables interrupts until the end of the next instruction. */
    mov %ax, %ss
    /* We should set SP because BIOS calls may depend on that. TODO confirm. */
    mov %bp, %sp
    /* Store the initial dl to load stage 2 later on. */
    mov %dl, initial_dl
    jmp after_locals
    initial_dl: .byte 0
after_locals:
.endm
</code>```

答:
I can only assume that you have introduced bugs into the code originally presented in the tutorial. For instance you say you assemble with:

```<code>as --32 -o main.o main.S -g
</code>```

If you include common.h as it appears in the tutorial this command should fail with something like:

```<code>common.h: Assembler messages:
common.h:399: Warning: stray `\'
common.h:400: Warning: stray `\'
common.h:401: Warning: stray `\'
common.h:421: Warning: stray `\'
common.h:422: Warning: stray `\'
common.h:423: Warning: stray `\'
common.h:424: Warning: stray `\'
common.h:425: Warning: stray `\'
</code>```

These errors occur because the way the tutorial code was written it requires the C preprocessor to be run on the assembly code. The easiest way is to use GCC to assemble the code by passing it to the backend AS assembler:

```<code>gcc -c -g -m32 -o main.o main.S
</code>```

GCC will take any file extension with a .S extension and run the C preprocessor on the .Sbefore passing it through the AS assembler. As an alternative you can run the C preprocessor directly with cpp and then run as separately.

To build main.img with GCC you'd use commands like these:

```<code>gcc -c -g -m32 -o main.o main.S
ld -T linker.ld -o main.img --oformat binary -m elf_i386 -nostdlib main.o
</code>```

To build it with the C preprocessor you could do:

```<code>cpp main.S > main.s
as -g --32 -o main.o main.s
ld -T linker.ld -o main.img --oformat binary -m elf_i386 -nostdlib main.o
</code>```

The code worked as expected when run with QEMU using:

```<code>qemu-system-i386 -hda main.img
</code>```

The output should appear similar to:

Question regarding CS and the Real Mode IVT

You inquired about this code:

```<code>/* Set address of the handler for interrupt 0. */
movw $handler, 0x00
/* Set code segment of the handler for interrupt 0. */
mov %cs, 0x02
int $0
</code>```

In real mode the default IBM-PC Interrupt Vector Table (IVT) is the first 1024 bytes of memory starting at physical address 0x00000 (0x0000:0x0000) up to 0x00400 (0x0000:0x0400). Each entry in the IVT is 4 bytes (4 bytes per entry*256 interrupts=1024 bytes). A word (2 bytes) for the Instruction Pointer (IP) (also referred to as the offset) where the interrupt vector is located followed by a word (2 bytes) that contains the segment.

Interrupt 0 starts at the very bottom of the IVT at memory 0x000000 (0x0000:0x0000). Interrupt 1 starts at 0x00004 (0x0000:0x0004)... Interrupt 255 starts at 0x003FC (0x0000:0x03FC).

The instruction:

```<code>/* Set address of the handler for interrupt 0. */
movw $handler, 0x00
</code>```

Moves the 16-bit offset of handler to memory address DS:0x0000 . With 16-bit addressing DS is always an implied segment unless register BP appears in a memory reference (ie. (%bp)) then the segment is assumed to be SS.

DS is set to 0x0000 in the BEGIN macro so DS:0x00 is 0x0000:0x0000 which is the IP (offset) portion of Interrupt 0's segment:offset address. The instruction:

```<code>/* Set code segment of the handler for interrupt 0. */
mov %cs, 0x02
</code>```

CS is set to 0x0000 in the BEGIN macro. This instruction moves 0x0000 to memory address DS:0x02 (0x0000:0x0002). 0x0000:0x0002 is the segment portion of Interrupt 0's address. After this instruction the IVT entry for Interrupt 0 now points at the handler code in our boot sector. The instruction:

```<code>int $0
</code>```

Invokes interrupt 0 which is now pointing at handler. It should display a to the screen and then continue with the code after int $0 which prints b and then halts.

Code for Minimal Complete Verifiable Example

Your question lacks a minimal complete verifiable example. I modified common.h to only include the macros needed by the code you wrote and kept everything else the same:

linker.ld:

```<code>common.h: Assembler messages:
common.h:399: Warning: stray `\'
common.h:400: Warning: stray `\'
common.h:401: Warning: stray `\'
common.h:421: Warning: stray `\'
common.h:422: Warning: stray `\'
common.h:423: Warning: stray `\'
common.h:424: Warning: stray `\'
common.h:425: Warning: stray `\'
</code>```0

common.h:

```<code>common.h: Assembler messages:
common.h:399: Warning: stray `\'
common.h:400: Warning: stray `\'
common.h:401: Warning: stray `\'
common.h:421: Warning: stray `\'
common.h:422: Warning: stray `\'
common.h:423: Warning: stray `\'
common.h:424: Warning: stray `\'
common.h:425: Warning: stray `\'
</code>```1

main.S:

```<code>common.h: Assembler messages:
common.h:399: Warning: stray `\'
common.h:400: Warning: stray `\'
common.h:401: Warning: stray `\'
common.h:421: Warning: stray `\'
common.h:422: Warning: stray `\'
common.h:423: Warning: stray `\'
common.h:424: Warning: stray `\'
common.h:425: Warning: stray `\'
</code>```2

Recommendations

GDB (The GNU Debugger) doesn't understand real mode segment:offset addressing. Debugging real mode code with GDB is very problematic and not something I recommend. You should consider using BOCHS to debug real mode code as it understands real mode, segment:offset addressing, and is better suited for debugging bootloaders or any code that is run before entering 32-bit protected mode or long mode.

Body:
I am learning interrupt handling in x86 real mode using assembly. I am following the below example taken from here :

.include "common.h"
BEGIN
    CLEAR
    /* Set address of the handler for interrupt 0. */
    movw $handler, 0x00
    /* Set code segment of the handler for interrupt 0. */
    mov %cs, 0x02
    int $0
    PUTC $'b
    hlt
handler:
    PUTC $'a
    iret

But when I compile and run the above code,

$ as --32 -o main.o main.S -g
$ ld -T linker.ld -o main.img --oformat binary -m elf_i386 -nostdlib main.o
$ qemu-system-i386 -hda main.img

I get the following error :

qemu-system-i386: Trying to execute code outside RAM or ROM at 0xf00fff53
This usually means one of the following happened:

(1) You told QEMU to execute a kernel for the wrong machine type, and it crashed on startup (eg trying to run a raspberry pi kernel on a versatilepb QEMU machine)
(2) You didn't give QEMU a kernel or BIOS filename at all, and QEMU executed a ROM full of no-op instructions until it fell off the end
(3) Your guest kernel has a bug and crashed by jumping off into nowhere

This is almost always one of the first two, so check your command line and that you are using the right type of kernel for this machine.
If you think option (3) is likely then you can try debugging your guest with the -d debug options; in particular -d guest_errors will cause the log to include a dump of the guest register state at this point.

Execution cannot continue; stopping here.

What am I missing here? Why mov %cs, 0x02 is needed or what its really doing?

I tried debugging this under gdb, when I did step execution line by line, i did not face this error under gdb, which was wierd and am still checking.

EDIT

This is how BEGIN is defined :

.macro BEGIN
    .local after_locals
    .code16
    cli
    /* Set %cs to 0. */
    ljmp $0, $1f
    1:
    xor %ax, %ax
    /* We must zero %ds for any data access. */
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %fs
    mov %ax, %gs
    mov %ax, %bp
    /* Automatically disables interrupts until the end of the next instruction. */
    mov %ax, %ss
    /* We should set SP because BIOS calls may depend on that. TODO confirm. */
    mov %bp, %sp
    /* Store the initial dl to load stage 2 later on. */
    mov %dl, initial_dl
    jmp after_locals
    initial_dl: .byte 0
after_locals:
.endm

Body:
I can only assume that you have introduced bugs into the code originally presented in the tutorial. For instance you say you assemble with:

as --32 -o main.o main.S -g

If you include common.h as it appears in the tutorial this command should fail with something like:

common.h: Assembler messages:
common.h:399: Warning: stray `\'
common.h:400: Warning: stray `\'
common.h:401: Warning: stray `\'
common.h:421: Warning: stray `\'
common.h:422: Warning: stray `\'
common.h:423: Warning: stray `\'
common.h:424: Warning: stray `\'
common.h:425: Warning: stray `\'

These errors occur because the way the tutorial code was written it requires the C preprocessor to be run on the assembly code. The easiest way is to use GCC to assemble the code by passing it to the backend AS assembler:

gcc -c -g -m32 -o main.o main.S

GCC will take any file extension with a .S extension and run the C preprocessor on the .Sbefore passing it through the AS assembler. As an alternative you can run the C preprocessor directly with cpp and then run as separately.

To build main.img with GCC you'd use commands like these:

gcc -c -g -m32 -o main.o main.S
ld -T linker.ld -o main.img --oformat binary -m elf_i386 -nostdlib main.o

To build it with the C preprocessor you could do:

cpp main.S > main.s
as -g --32 -o main.o main.s
ld -T linker.ld -o main.img --oformat binary -m elf_i386 -nostdlib main.o

The code worked as expected when run with QEMU using:

qemu-system-i386 -hda main.img

The output should appear similar to:

Question regarding CS and the Real Mode IVT

You inquired about this code:

/* Set address of the handler for interrupt 0. */
movw $handler, 0x00
/* Set code segment of the handler for interrupt 0. */
mov %cs, 0x02
int $0

In real mode the default IBM-PC Interrupt Vector Table (IVT) is the first 1024 bytes of memory starting at physical address 0x00000 (0x0000:0x0000) up to 0x00400 (0x0000:0x0400). Each entry in the IVT is 4 bytes (4 bytes per entry*256 interrupts=1024 bytes). A word (2 bytes) for the Instruction Pointer (IP) (also referred to as the offset) where the interrupt vector is located followed by a word (2 bytes) that contains the segment.

Interrupt 0 starts at the very bottom of the IVT at memory 0x000000 (0x0000:0x0000). Interrupt 1 starts at 0x00004 (0x0000:0x0004)... Interrupt 255 starts at 0x003FC (0x0000:0x03FC).

The instruction:

/* Set address of the handler for interrupt 0. */
movw $handler, 0x00

Moves the 16-bit offset of handler to memory address DS:0x0000 . With 16-bit addressing DS is always an implied segment unless register BP appears in a memory reference (ie. (%bp)) then the segment is assumed to be SS.

DS is set to 0x0000 in the BEGIN macro so DS:0x00 is 0x0000:0x0000 which is the IP (offset) portion of Interrupt 0's segment:offset address. The instruction:

/* Set code segment of the handler for interrupt 0. */
mov %cs, 0x02

CS is set to 0x0000 in the BEGIN macro. This instruction moves 0x0000 to memory address DS:0x02 (0x0000:0x0002). 0x0000:0x0002 is the segment portion of Interrupt 0's address. After this instruction the IVT entry for Interrupt 0 now points at the handler code in our boot sector. The instruction:

int $0

Invokes interrupt 0 which is now pointing at handler. It should display a to the screen and then continue with the code after int $0 which prints b and then halts.

Code for Minimal Complete Verifiable Example

Your question lacks a minimal complete verifiable example. I modified common.h to only include the macros needed by the code you wrote and kept everything else the same:

linker.ld:

SECTIONS
{
    /* We could also pass the -Ttext 0x7C00 to as instead of doing this.
     * If your program does not have any memory accesses, you can omit this.
     */
    . = 0x7c00;
    .text :
    {
        __start = .;

        /* We are going to stuff everything
         * into a text segment for now, including data.
         * Who cares? Other segments only exist to appease C compilers.
         */
        *(.text)

        /* Magic bytes. 0x1FE == 510.
         *
         * We could add this on each Gas file separately with `.word`,
         * but this is the perfect place to DRY that out.
         */
        . = 0x1FE;
        SHORT(0xAA55)

        /* This is only needed if we are going to use a 2 stage boot process,
         * e.g. by reading more disk than the default 512 bytes with BIOS `int 0x13`.
         */
        *(.stage2)

        /* Number of sectors in stage 2. Used by the `int 13` to load it from disk.
         *
         * The value gets put into memory as the very last thing
         * in the `.stage` section if it exists.
         *
         * We must put it *before* the final `. = ALIGN(512)`,
         * or else it would fall out of the loaded memory.
         *
         * This must be absolute, or else it would get converted
         * to the actual address relative to this section (7c00 + ...)
         * and linking would fail with "Relocation truncated to fit"
         * because we are trying to put that into al for the int 13.
         */
        __stage2_nsectors = ABSOLUTE((. - __start) / 512);

        /* Ensure that the generated image is a multiple of 512 bytes long. */
        . = ALIGN(512);
        __end = .;
        __end_align_4k = ALIGN(4k);
    }
}

common.h:

/* I really want this for the local labels.
 *
 * The major downside is that every register passed as argument requires `<>`:
 * http://stackoverflow.com/questions/19776992/gas-altmacro-macro-with-a-percent-sign-in-a-default-parameter-fails-with-oper/
 */
.altmacro

/* Helpers */

/* Push registers ax, bx, cx and dx. Lightweight `pusha`. */
.macro PUSH_ADX
    push %ax
    push %bx
    push %cx
    push %dx
.endm

/* Pop registers dx, cx, bx, ax. Inverse order from PUSH_ADX,
 * so this cancels that one.
 */
.macro POP_DAX
    pop %dx
    pop %cx
    pop %bx
    pop %ax
.endm

/* Structural. */

/* Setup a sane initial state.
 *
 * Should be the first thing in every file.
 *
 * Discussion of what is needed exactly: http://stackoverflow.com/a/32509555/895245
 */
.macro BEGIN
    LOCAL after_locals
    .code16
    cli
    /* Set %cs to 0. TODO Is that really needed? */
    ljmp $0, $1f
    1:
    xor %ax, %ax
    /* We must zero %ds for any data access. */
    mov %ax, %ds
    /* TODO is it really need to clear all those segment registers, e.g. for BIOS calls? */
    mov %ax, %es
    mov %ax, %fs
    mov %ax, %gs
    /* TODO What to move into BP and SP?
     * http://stackoverflow.com/questions/10598802/which-value-should-be-used-for-sp-for-booting-process
     */
    mov %ax, %bp
    /* Automatically disables interrupts until the end of the next instruction. */
    mov %ax, %ss
    /* We should set SP because BIOS calls may depend on that. TODO confirm. */
    mov %bp, %sp
    /* Store the initial dl to load stage 2 later on. */
    mov %dl, initial_dl
    jmp after_locals
    initial_dl: .byte 0
after_locals:
.endm

/* BIOS */

.macro CURSOR_POSITION x=$0, y=$0
    PUSH_ADX
    mov $0x02, %ah
    mov $0x00, %bh
    mov \x, %dh
    mov \y, %dl
    int $0x10
    POP_DAX
.endm

/* Clear the screen, move to position 0, 0. */
.macro CLEAR
    PUSH_ADX
    mov $0x0600, %ax
    mov $0x7, %bh
    mov $0x0, %cx
    mov $0x184f, %dx
    int $0x10
    CURSOR_POSITION
    POP_DAX
.endm

/* Print a 8 bit ASCII value at current cursor position.
 *
 * * `c`: r/m/imm8 ASCII value to be printed.
 *
 * Usage:
 *
 * ....
 * PUTC $'a
 * ....
 *
 * prints `a` to the screen.
 */
.macro PUTC c=$0x20
    push %ax
    mov \c, %al
    mov $0x0E, %ah
    int $0x10
    pop %ax
.endm

main.S:

.include "common.h"
BEGIN
    CLEAR
    /* Set address of the handler for interrupt 0. */
    movw $handler, 0x00
    /* Set code segment of the handler for interrupt 0. */
    mov %cs, 0x02
    int $0
    PUTC $'b
    hlt
handler:
    PUTC $'a
    iret

Recommendations

GDB (The GNU Debugger) doesn't understand real mode segment:offset addressing. Debugging real mode code with GDB is very problematic and not something I recommend. You should consider using BOCHS to debug real mode code as it understands real mode, segment:offset addressing, and is better suited for debugging bootloaders or any code that is run before entering 32-bit protected mode or long mode.


问:
Split Dataframe with some conditions
Goal:

I would like to split my dataframe into 3 multiple dataframes.
My problem is, I don't know how I can get the dataframes with the more similar sum of "value" column for each one

Here is my current Code:

```<code>import pandas as pd
import math

splitter = 3

df = pd.read_csv('account.csv')
q_rows = df.shape[0]                                # Number of rows
q_rows_x_dataframe = math.ceil(q_rows / splitter)   # Quantity of rows for splitter

for index, row in df.iterrows():
    row.shift(q_rows_x_dataframe + 1)

>>> df
   network  value
0        A   1400
1        B   1300
2        C   1200
3        D   1100
4        E   1000
5        F    900
6        G    800
7        H    700
8        I    600
9        J    500
10       K    400
11       L    300
12       M    200
13       N    100
</code>```

This is my desired output:

```<code>A   1400
D   1100
G   800
J   500
M   200

B   1300
E   1000
H   700
K   400
N   100

C   1200
F   900
I   600
L   300
</code>```

答:
Group with a modulus on the index should work:</p>

```<code>splitter = 3
[g for _, g in df.groupby(df.index % splitter)]

[   network  value
 0        A   1400
 3        D   1100
 6        G    800
 9        J    500
 12       M    200,    network  value
 1        B   1300
 4        E   1000
 7        H    700
 10       K    400
 13       N    100,    network  value
 2        C   1200
 5        F    900
 8        I    600
 11       L    300]
</code>```

Title: Split Dataframe with some conditions

Body:
Goal:

I would like to split my dataframe into 3 multiple dataframes.
My problem is, I don't know how I can get the dataframes with the more similar sum of "value" column for each one

Here is my current Code:

import pandas as pd
import math

splitter = 3

df = pd.read_csv('account.csv')
q_rows = df.shape[0]                                # Number of rows
q_rows_x_dataframe = math.ceil(q_rows / splitter)   # Quantity of rows for splitter

for index, row in df.iterrows():
    row.shift(q_rows_x_dataframe + 1)

>>> df
   network  value
0        A   1400
1        B   1300
2        C   1200
3        D   1100
4        E   1000
5        F    900
6        G    800
7        H    700
8        I    600
9        J    500
10       K    400
11       L    300
12       M    200
13       N    100

This is my desired output:

A   1400
D   1100
G   800
J   500
M   200

B   1300
E   1000
H   700
K   400
N   100

C   1200
F   900
I   600
L   300

Body:
Group with a modulus on the index should work:

splitter = 3
[g for _, g in df.groupby(df.index % splitter)]

[   network  value
 0        A   1400
 3        D   1100
 6        G    800
 9        J    500
 12       M    200,    network  value
 1        B   1300
 4        E   1000
 7        H    700
 10       K    400
 13       N    100,    network  value
 2        C   1200
 5        F    900
 8        I    600
 11       L    300]


问:
Adding a video to the animating frame
We can add an image to the frame by Adding the image as the background of the content but I can't find a solution to add a video using the same approach without a hand. (I just want a frame for my video.)

I want to add an id to the added video too.

Here is the CodePen.

And here is exact same code:

setTimeout(function(){
MovieClip();

}, 2000)

function MovieClip() {
  let video = document.createElement('video');
  video.setAttribute("id", "clip"); // Note: add id to video so that we can interact with it later
  document.getElementsByClassName('content')[0].appendChild(video);

  let clip = document.getElementById("clip");

  let source = document.createElement('source');
  source.src = `http://clips.vorwaerts-gmbh.de/VfE_html5.mp4`;

  /* Adding video as the background of the content not working
  let node = document.getElementsByClassName('content')[0];
  node.style.background = `url(http://clips.vorwaerts-gmbh.de/VfE_html5.mp4) center/cover`; */

  source.type = 'video/mp4';
  video.appendChild(source);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* html {
 overflow: hidden;
 background-color: #121518;
}

video {
 position: absolute;
 overflow: hidden;
 left: 0vw;
 top: 0vh;
 width: 90%;
 height: auto;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 margin-left: auto;
 margin-right: auto;
 margin-top: auto;
 margin-bottom: auto;
  border: 0.1vw dashed #eb4034;

} */

body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #11151a;
}

.box {
 border-radius: 1.31vh;
 position: relative;
 overflow: hidden;
}

.box::after {
    content: '';
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:
    repeating-linear-gradient(-45deg, white 0  0.48828125vw, hotpink 0 0.9765625vw) 0 0/1.380859375vw 1.380859375vw;
    width: calc(100% + 1.380859375vw);
    height: calc(100% + 1.380859375vw);
    transform: translate(-1.380859375vw, -1.380859375vw);
    will-change: transform;
    animation: animate 4s linear infinite;
  }

.box .content {
  width: calc(90vw -  1.953125vw);
  height: calc(85vh - 3.9318479685452163vh);
  /*border-radius: 1.31vh;*/
  box-shadow: 0 0 0.262vh deeppink, 0 0 0.6553vh rgba(0, 0, 0, 1), inset 0 0 0.6553vh rgba(0, 0, 0, 1);
  margin:1vh;
}

@keyframes animate {
  to {
    transform: translate(0, 0);
    will-change: transform;
  }
}

.stopAnimation:after {
  -webkit-transform: none !important;
  transform: none !important;
}</code>```

<!DOCTYPE html>

```

Please run the CodePen, I think there is two main issues with my code:

First: the video doesn't fill the frame

Second: Compare the top corner with the bottom, as you see the lower corner is covered unexpectedly with the video.

答:
I'm not sure if this is what you want, but if you want to have a video on top of this box element, you can add position: absolute to the video element.

Add this
  video.style.position = 'absolute'; after video.appendChild(source);

Title: Adding a video to the animating frame

Body:
We can add an image to the frame by Adding the image as the background of the content but I can't find a solution to add a video using the same approach without a hand. (I just want a frame for my video.)

I want to add an id to the added video too.

Here is the CodePen.

And here is exact same code:

setTimeout(function(){
MovieClip();

}, 2000)

function MovieClip() {
  let video = document.createElement('video');
  video.setAttribute("id", "clip"); // Note: add id to video so that we can interact with it later
  document.getElementsByClassName('content')[0].appendChild(video);

  let clip = document.getElementById("clip");

  let source = document.createElement('source');
  source.src = `http://clips.vorwaerts-gmbh.de/VfE_html5.mp4`;

  /* Adding video as the background of the content not working
  let node = document.getElementsByClassName('content')[0];
  node.style.background = `url(http://clips.vorwaerts-gmbh.de/VfE_html5.mp4) center/cover`; */

  source.type = 'video/mp4';
  video.appendChild(source);

}

/* html {
 overflow: hidden;
 background-color: #121518;
}

video {
 position: absolute;
 overflow: hidden;
 left: 0vw;
 top: 0vh;
 width: 90%;
 height: auto;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 margin-left: auto;
 margin-right: auto;
 margin-top: auto;
 margin-bottom: auto;
  border: 0.1vw dashed #eb4034;

} */

body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #11151a;
}

.box {
 border-radius: 1.31vh;
 position: relative;
 overflow: hidden;
}

.box::after {
    content: '';
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:
    repeating-linear-gradient(-45deg, white 0  0.48828125vw, hotpink 0 0.9765625vw) 0 0/1.380859375vw 1.380859375vw;
    width: calc(100% + 1.380859375vw);
    height: calc(100% + 1.380859375vw);
    transform: translate(-1.380859375vw, -1.380859375vw);
    will-change: transform;
    animation: animate 4s linear infinite;
  }

.box .content {
  width: calc(90vw -  1.953125vw);
  height: calc(85vh - 3.9318479685452163vh);
  /*border-radius: 1.31vh;*/
  box-shadow: 0 0 0.262vh deeppink, 0 0 0.6553vh rgba(0, 0, 0, 1), inset 0 0 0.6553vh rgba(0, 0, 0, 1);
  margin:1vh;
}

@keyframes animate {
  to {
    transform: translate(0, 0);
    will-change: transform;
  }
}

.stopAnimation:after {
  -webkit-transform: none !important;
  transform: none !important;
}

<!DOCTYPE html>

Please run the CodePen, I think there is two main issues with my code:

First: the video doesn't fill the frame

Second: Compare the top corner with the bottom, as you see the lower corner is covered unexpectedly with the video.


问:
Insert extra columns with NULL values from one table to another table HIVE
Table1 have columns col1 , col2 ,col3 , col4 , col5

Table2 have columns col1 , col3 , col5

I want to insert rows from Table2 to Table1

But col2 , col4 should be NULL datatype after inserting into Table2

How can I do it in HIVE , Currently I am using Hortonworks 3.1 version

答:
You just use insert . . . select:

```<code>insert into table1 (col1, col2, col3, col4, col5)
    select col1, null, col3, null, col5
    from table2;
</code>```

Body:
You just use insert . . . select:

insert into table1 (col1, col2, col3, col4, col5)
    select col1, null, col3, null, col5
    from table2;


问:
Getting a PgConnection from a Pool with Vert.x vertx-pg-client
I want to perform an expensive query on postgresql (runtime about 7-60 seconds), occasionally the results aren't needed after the query starts and so I'd like to cancel it. I want to use vert.x libraries to do this. I've looked at using io.vertx.reactivex.pgclient.PgConnection as it supports cancelling a query. However there doesn't appear to be a way to get a PgConnection from a pooled source. The other option is to use io.vertx.reactivex.sqlclient.SqlConnection returned from a PgPool but this doesn't support cancelling a query. Thus my question is how can I cancel a query on a pooled connection?

答:
```<code>pgPool.rxGetConnection().flatMap(
    conn -> {
      PgConnection pgconn = new PgConnection((io.vertx.pgclient.PgConnection)conn.getDelegate());
      ...
      return Single.just(conn);
    }
).subscribe(conn -> conn.close());
</code>```

Doing something like the above will give you a io.vertx.reactivex.pgclient.PgConnection from the io.vertx.reactivex.sqlclient.SqlConnection obtained from a rxGetConnection

Body:
pgPool.rxGetConnection().flatMap(
    conn -> {
      PgConnection pgconn = new PgConnection((io.vertx.pgclient.PgConnection)conn.getDelegate());
      ...
      return Single.just(conn);
    }
).subscribe(conn -> conn.close());

Doing something like the above will give you a io.vertx.reactivex.pgclient.PgConnection from the io.vertx.reactivex.sqlclient.SqlConnection obtained from a rxGetConnection


问:
Convolve a 3D array with three kernels (x, y, z) in python
I have a 3D image and three kernels k1, k2, k3 in the x, y and z direction.

```<code>img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension
</code>```

I can use numpy.convolve iteratively to calculate the convolution like this:

```<code>for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[1])
      oneline=img[i,j,:]
      img[i,j,:]=np.convolve(oneline, k1, mode='same')

for i in np.arange(img.shape[1])
   for j in np.arange(img.shape[2])
      oneline=img[:,i,j]
      img[:,i,j]=np.convolve(oneline, k2, mode='same')

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[2])
      oneline=img[i,:,j]
      img[i,:,j]=np.convolve(oneline, k3, mode='same')
</code>```

Is there an easier way to do it? Thanks.

答:
You can use Scipy's convolve. However, the kernel is typically the same number of dimensions as the input. Rather than a vector for each dimension. Not sure how exactly that will play out with what you are trying to do, but I just provided a sample kernel for show:

```<code># Sample kernel
n = 4
kern = np.ones((n+1, n+1, n+1))
vals = np.arange(n+1)
for i in vals:
    for j in vals:
        for k in vals:
            kern[i , j, k] = n/2 - np.sqrt((i-n/2)**2 + (j-n/2)**2 + (k-n/2)**2)

# 3d convolve
scipy.signal.convolve(img, kern, mode='same')
</code>```

Body:
I have a 3D image and three kernels k1, k2, k3 in the x, y and z direction.

img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension

I can use numpy.convolve iteratively to calculate the convolution like this:

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[1])
      oneline=img[i,j,:]
      img[i,j,:]=np.convolve(oneline, k1, mode='same')

for i in np.arange(img.shape[1])
   for j in np.arange(img.shape[2])
      oneline=img[:,i,j]
      img[:,i,j]=np.convolve(oneline, k2, mode='same')

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[2])
      oneline=img[i,:,j]
      img[i,:,j]=np.convolve(oneline, k3, mode='same')

Is there an easier way to do it? Thanks.

Body:
You can use Scipy's convolve. However, the kernel is typically the same number of dimensions as the input. Rather than a vector for each dimension. Not sure how exactly that will play out with what you are trying to do, but I just provided a sample kernel for show:

# Sample kernel
n = 4
kern = np.ones((n+1, n+1, n+1))
vals = np.arange(n+1)
for i in vals:
    for j in vals:
        for k in vals:
            kern[i , j, k] = n/2 - np.sqrt((i-n/2)**2 + (j-n/2)**2 + (k-n/2)**2)

# 3d convolve
scipy.signal.convolve(img, kern, mode='same')


问:
Django REST framework - Serializer relations User.username
Im working on a django project, and I have a model that looks like this:

```<code>class Comment(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE)
    slug            = models.SlugField(unique=True,null=True, blank=True)
    content_type    = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       = models.PositiveIntegerField()
    content_object  = GenericForeignKey('content_type', 'object_id')
    parent          = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE)
    content         = models.TextField()
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = CommentManager()

    def __str__(self):
        return str(self.user.username)
</code>```

I use this serializer:

```<code>class CommentDetailSerializer(ModelSerializer):
    user = SerializerMethodField()
    replies = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_replies(self,obj):
        if obj.is_parent:
            return CommentChildSerializer(obj.children(),many=True).data
</code>```

for this view:

```<code>class CommentDetailApiView(RetrieveAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentDetailSerializer
    lookup_field = 'slug'
</code>```

here is the PostSerializer I use,

```<code>class PostSerializer(ModelSerializer):
    user = SerializerMethodField()
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            'user',
            'title',
            'content',
            'comments'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_comments(self,obj):
        comments_qs = Comment.objects.filter_by_instance(obj)
        comments = CommentSerializer(comments_qs, many=True).data
        return comments
</code>```

this is what I get in the PostDetailAPIView:

```<code>{
    "user": "abc",
    "title": "blabla",
    "content": "bla",
    "comments": [
        {
            "user": 1,
            "content": "hey",
            "timestamp": "2020-02-18T00:07:29.932850Z"
        }
    ]
}
</code>```

How do I get the comment user username instead of its id?

I get the username of the comment user only in the CommentDetailApiView.

Thank you

答:
You can add an UserSerializer to indicate what you want to show of the user:

```<code>from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username',)

class CommentDetailSerializer(ModelSerializer):
    user = UserSerializer()
    ..... # the rest of your code
</code>```

Body:
Im working on a django project, and I have a model that looks like this:

class Comment(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE)
    slug            = models.SlugField(unique=True,null=True, blank=True)
    content_type    = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       = models.PositiveIntegerField()
    content_object  = GenericForeignKey('content_type', 'object_id')
    parent          = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE)
    content         = models.TextField()
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = CommentManager()

    def __str__(self):
        return str(self.user.username)

I use this serializer:

class CommentDetailSerializer(ModelSerializer):
    user = SerializerMethodField()
    replies = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_replies(self,obj):
        if obj.is_parent:
            return CommentChildSerializer(obj.children(),many=True).data

for this view:

class CommentDetailApiView(RetrieveAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentDetailSerializer
    lookup_field = 'slug'

here is the PostSerializer I use,

class PostSerializer(ModelSerializer):
    user = SerializerMethodField()
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            'user',
            'title',
            'content',
            'comments'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_comments(self,obj):
        comments_qs = Comment.objects.filter_by_instance(obj)
        comments = CommentSerializer(comments_qs, many=True).data
        return comments

this is what I get in the PostDetailAPIView:

{
    "user": "abc",
    "title": "blabla",
    "content": "bla",
    "comments": [
        {
            "user": 1,
            "content": "hey",
            "timestamp": "2020-02-18T00:07:29.932850Z"
        }
    ]
}

How do I get the comment user username instead of its id?

I get the username of the comment user only in the CommentDetailApiView.

Thank you

Body:
You can add an UserSerializer to indicate what you want to show of the user:

from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username',)

class CommentDetailSerializer(ModelSerializer):
    user = UserSerializer()
    ..... # the rest of your code


问:
SSRS - extract data from column containing JSON
I have a dataset with a column containing arrays of JSON data that looks like:

[{"name":"aaa","type":"yyy"},{"name":"bbb","type":"ccc"}]

or more specifically:

dataset with JSON array column

Is there any straight forward method of extracting the JSON data from the column using something like JSON_QUERY, so that I can use it in a report

答:
As far as I can tell, the existing JSON array format is not usable with any of the T-SQL JSON functions.

The array in the column "jsonCol" needs to be in the form of:

{ "tag": [{"name":"aaa","type":"yyy"},{"name":"bbb","type":"ccc"}]}

and then I can extract each array element individually with:

SELECT JSON_QUERY(jsonCol, '$.tag[0]') as tag
FROM

So I could add a prefix and suffix string to the select statement to fix this as long as no one else will see it.


问:
CardView Corner Radius
Is there a way to make CardView only have corner radius at the top?</p>

```<code><android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="10dp"
    >
</code>```

答:
You can put your ImageView inside a CardView, and add those properties to the ImageView:

```<code>android:cropToPadding="true"
android:paddingBottom="15dp"
</code>```

That way you will get rid of the rounded bottom corner, but keep in mind that this comes in the price of having a small portion of your image cut off.

Title: CardView Corner Radius

Body:
Is there a way to make CardView only have corner radius at the top?

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="10dp"
    >

Body:
You can put your ImageView inside a CardView, and add those properties to the ImageView:

android:cropToPadding="true"
android:paddingBottom="15dp"

That way you will get rid of the rounded bottom corner, but keep in mind that this comes in the price of having a small portion of your image cut off.


问:
Pandas rolling, resample and apply function
I am looking for a way to create on a daily timeindexed dataframe, a rolling window over last two years, resample it every 5th Day and then run functions on the resampled dataframe.

FYI,In this case I want to run regression y~X (as per the dataframe below).

So the output will be a timeindexed series with Beta values for each day(ignoring first 2 years)

Currently I am using a row based loop, but it is extremely slow

Feel there should be easier way to accomplish this.

Thanks in advance

```<code>date_range=pd.date_range('2015-01-01','2019-12-31')

df=pd.DataFrame(np.random.rand(len(date_range),2),index=date_range,columns=['X','y'])

</code>```

Code I am currently using

```<code>
def rolling_stats(X,y,years_window=2):

    idx=X.index

    assert len(X)==len(y)

    x_idx=np.isnan(X).argmin()

    y_idx=np.isnan(y).argmin()

    out_dates = []
    out_beta = []
    out_rsq = []
    out_stderr = []

    df=pd.DataFrame(np.nan,columns=['Beta','RSQ','StdErr'],index=idx)

    for date in idx:

        start_date=date-DateOffset(years=years_window)

        date_range=pd.bdate_range(start_date,date,freq='5D')

        try:

            X_reg=X.loc[X.index.isin(date_range)]
            y_reg=y.loc[y.index.isin(date_range)]

            assert len(X_reg)==len(y_reg)

            X_c=sm.add_constant(X_reg)

            model=sm.OLS(y_reg,X_c)

            result=model.fit()

            df.loc[date,'RSQ']=result.rsquared
            df.loc[date,'Beta']=result.params[1]
            df.loc[date,'StdErr']=np.sqrt(result.mse_resid)

        except Exception:

            df.loc[date,'RSQ']=np.nan
            df.loc[date,'Beta']=np.nan
            df.loc[date,'StdErr']=np.nan

    return df

</code>```

Body:
I am looking for a way to create on a daily timeindexed dataframe, a rolling window over last two years, resample it every 5th Day and then run functions on the resampled dataframe.

FYI,In this case I want to run regression y~X (as per the dataframe below).

So the output will be a timeindexed series with Beta values for each day(ignoring first 2 years)

Currently I am using a row based loop, but it is extremely slow

Feel there should be easier way to accomplish this.

Thanks in advance

date_range=pd.date_range('2015-01-01','2019-12-31')

df=pd.DataFrame(np.random.rand(len(date_range),2),index=date_range,columns=['X','y'])

Code I am currently using

def rolling_stats(X,y,years_window=2):

    idx=X.index

    assert len(X)==len(y)

    x_idx=np.isnan(X).argmin()

    y_idx=np.isnan(y).argmin()

    out_dates = []
    out_beta = []
    out_rsq = []
    out_stderr = []

    df=pd.DataFrame(np.nan,columns=['Beta','RSQ','StdErr'],index=idx)

    for date in idx:

        start_date=date-DateOffset(years=years_window)

        date_range=pd.bdate_range(start_date,date,freq='5D')

        try:

            X_reg=X.loc[X.index.isin(date_range)]
            y_reg=y.loc[y.index.isin(date_range)]

            assert len(X_reg)==len(y_reg)

            X_c=sm.add_constant(X_reg)

            model=sm.OLS(y_reg,X_c)

            result=model.fit()

            df.loc[date,'RSQ']=result.rsquared
            df.loc[date,'Beta']=result.params[1]
            df.loc[date,'StdErr']=np.sqrt(result.mse_resid)

        except Exception:

            df.loc[date,'RSQ']=np.nan
            df.loc[date,'Beta']=np.nan
            df.loc[date,'StdErr']=np.nan

    return df

Body:
The pandas API has a wealth of convenience functions this kind of task:

                   X         y
2015-01-01  0.649573  0.077779
2015-01-02  0.482643  0.358702
2015-01-03  0.710907  0.269485
2015-01-04  0.807316  0.288014
2015-01-05  0.274537  0.287975
...

First, a rolling average over 365 * 2 rows, where there's one row per day. Then we drop the first two years (which are null). Then we resample to five day periods.

df.rolling(365 * 2).mean().dropna(how='all').resample('5D').mean()

                   X         y
2016-12-30  0.505062  0.492843
2017-01-04  0.503317  0.494553
2017-01-09  0.503280  0.495643
2017-01-14  0.501926  0.495538
2017-01-19  0.499519  0.495316
...


问:
Neo4J Cypher conditional where statement depending on parameter
I'm trying to write a query that takes four parameters which are all lists of ids and which should filter the results.

I have nodes called KnowledgeEntry which have multiple KnowledgeRecords attached to them

```<code>(:KnowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)
</code>```

KnowledgeRecords each have four types of relations to nodes of type Location, Community, Function or OrganizationalUnit which all have an id attribute.

I want to retrieve all KnowledgeEntries if they have one or more KnowledgeRecords that have a relation to Location, Community, Function or OU where id matches one of the items in the given list (parameter)

This is what I came up with so far:

```<code>MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT]->(loc:Location)
    WHERE loc.id IN $filters.locationIds
}

RETURN relationship, knowledgeEntry;
</code>```

This only works if all parameters used are set. If for example $filters.locationIds has no entries or is null the where statement should be ignored. I tried this with CASE statement and apoc.when but had no success.

When adding an OR EXISTS for e.g OrganizationalUnit I get an error "There should be at least one pattern expression"

```<code>MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT]->(loc:Location)
    WHERE loc.id IN $locationIds
}

OR EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:RELEVANT_FOR_EMPLOYEES_WITH]->(ou:OrganizationalUnit)
    WHERE ou.id IN $organizationalUnitIds
}

RETURN relationship, knowledgeEntry;
</code>```

答:
It seems you are encountering a possible neo4j bug when there are multiple existential subqueries in a boolean expression.

This query combines your two subqueries, and may work better for you:

```<code>MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
  MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT|RELEVANT_FOR_EMPLOYEES_WITH]->(x)
  WHERE
    (x:OrganizationalUnit AND x.id IN $organizationalUnitIds) OR
    (x:Location AND x.id IN $locationIds)
}
RETURN relationship, knowledgeEntry;
</code>```

Body:
I'm trying to write a query that takes four parameters which are all lists of ids and which should filter the results.

I have nodes called KnowledgeEntry which have multiple KnowledgeRecords attached to them

(:KnowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)

KnowledgeRecords each have four types of relations to nodes of type Location, Community, Function or OrganizationalUnit which all have an id attribute.

I want to retrieve all KnowledgeEntries if they have one or more KnowledgeRecords that have a relation to Location, Community, Function or OU where id matches one of the items in the given list (parameter)

This is what I came up with so far:

MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT]->(loc:Location)
    WHERE loc.id IN $filters.locationIds
}

RETURN relationship, knowledgeEntry;

This only works if all parameters used are set. If for example $filters.locationIds has no entries or is null the where statement should be ignored. I tried this with CASE statement and apoc.when but had no success.

When adding an OR EXISTS for e.g OrganizationalUnit I get an error "There should be at least one pattern expression"

MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT]->(loc:Location)
    WHERE loc.id IN $locationIds
}

OR EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:RELEVANT_FOR_EMPLOYEES_WITH]->(ou:OrganizationalUnit)
    WHERE ou.id IN $organizationalUnitIds
}

RETURN relationship, knowledgeEntry;

Body:
It seems you are encountering a possible neo4j bug when there are multiple existential subqueries in a boolean expression.

This query combines your two subqueries, and may work better for you:

MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
  MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT|RELEVANT_FOR_EMPLOYEES_WITH]->(x)
  WHERE
    (x:OrganizationalUnit AND x.id IN $organizationalUnitIds) OR
    (x:Location AND x.id IN $locationIds)
}
RETURN relationship, knowledgeEntry;


问:
c# xUnit Moq It.IsAny<object> not mocking as expected
Following is the piece of code(simple HTTP post call), I am trying to mock in Azure Function:

```<code>await httpClient.PostAsync("https://url.com", await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json"));
</code>```

Note that the httpClient.PostAsync() function takes two arguments: URL as string and body as object.

Now, in my test, I am mocking this POST call like this:

```<code>httpClientMock.Setup(s => s.PostAsync(It.IsAny<string>(), It.IsAny<object>())).ReturnsAsync(mockedHttpResponse);
</code>```

I was expecting that await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json") would not be called as I set it to work with any object. However, my test case fails with this exception:

Found System.ArgumentNullException with message "Value cannot be null.
  (Parameter 'path1')"
           at System.IO.Path.Combine(String path1, String path2)

When I provide the correct path(even a dummy path doesn't work) by setting up the Environment variable in Test, it works. But that doesn't seem the correct way, as the unit tests are intended to run in various machines and the base path will be different for each one of them.

答: File.ReadAllTextAsync() returns a string, so your MOQ setup should have It.IsAny<string>() as the second param instead of It.IsAny<object>().

Body:
Following is the piece of code(simple HTTP post call), I am trying to mock in Azure Function:

await httpClient.PostAsync("https://url.com", await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json"));

Note that the httpClient.PostAsync() function takes two arguments: URL as string and body as object.

Now, in my test, I am mocking this POST call like this:

httpClientMock.Setup(s => s.PostAsync(It.IsAny<string>(), It.IsAny<object>())).ReturnsAsync(mockedHttpResponse);

I was expecting that await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json") would not be called as I set it to work with any object. However, my test case fails with this exception:

Found System.ArgumentNullException with message "Value cannot be null.
  (Parameter 'path1')"
           at System.IO.Path.Combine(String path1, String path2)

When I provide the correct path(even a dummy path doesn't work) by setting up the Environment variable in Test, it works. But that doesn't seem the correct way, as the unit tests are intended to run in various machines and the base path will be different for each one of them.


答:
You need to override to_representation() function just like below:

```<code>def to_representation(self, instance):
    """Convert `username` to lowercase."""
    ret = super().to_representation(instance)
    ret['username'] = ret['username'].lower()
    return ret
</code>```

The above code is just an example. It will return username in lowercase letters. In your case just change the line

ret['username'] = ret['username'].lower()

to

ret['username'] = self.validated_data['username']

Title: Django REST framework - Serializer relations User.username

Body:
You need to override to_representation() function just like below:

def to_representation(self, instance):
    """Convert `username` to lowercase."""
    ret = super().to_representation(instance)
    ret['username'] = ret['username'].lower()
    return ret

The above code is just an example. It will return username in lowercase letters. In your case just change the line

ret['username'] = ret['username'].lower()

to

ret['username'] = self.validated_data['username']


问:
How do I detect whether or not an input with type=time has any values entered
I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.

However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.

In the below example, timeSelector is the input with type="time".

```<code>if (timeSelector.value == "") {
    timeSelector.classList.add("empty");
} else {
    timeSelector.classList.remove("empty");
}
</code>```

Is there any way to detect this type of thing?

To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.

答:
Per the specification on Input Elements with type time ( HTML Spec ) :

The value attribute, if specified and not empty, must have a value that is a valid time string.

If the value of the element is not a valid time string, then set it to the empty string instead.

This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.

You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.

The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.

By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });

on("keydown");
on("keyup");
on("change");
on("input");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="time"></code>```

The only way to possibly get around the lack of a changing value is to set a default value as below:

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });

on("change");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="time" value="00:00"></code>```

However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.

You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.

Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.

Body:
I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.

However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.

In the below example, timeSelector is the input with type="time".

if (timeSelector.value == "") {
    timeSelector.classList.add("empty");
} else {
    timeSelector.classList.remove("empty");
}

Is there any way to detect this type of thing?

To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.

Body:
Per the specification on Input Elements with type time ( HTML Spec ) :

The value attribute, if specified and not empty, must have a value that is a valid time string.

If the value of the element is not a valid time string, then set it to the empty string instead.

This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.

You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.

The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.

By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });

on("keydown");
on("keyup");
on("change");
on("input");

<input type="time">

The only way to possibly get around the lack of a changing value is to set a default value as below:

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });

on("change");

<input type="time" value="00:00">

However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.

You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.

Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.