问:
Footer overlaps other elements
I am trying to fix this footer.  If i remove positon it works fine but some other pages still have a problem.  I need this footer at the bottom of every page...

```<code>  footer {
   position: absolute;
   bottom: 0;
   left: 0;
   width: 100%;
   padding: 16px;
   background:white;
}

<footer>
  <div class="container text-center"> <span>Copyright © 2017 LeagueOn. all rights reserved </span> </div>
</footer>
</code>```

答:
Try to avoid position: absolute where you don't really need it.

You can achieve this via flexbox. Your footer should be direct child of body:

body {
  margin: 0;

  display: flex;
  flex-direction: column;
  height: 100vh;  /* min-height: 100vh will also work everywhere except IE */
}

footer {
  /* move footer to the bottom */
  margin-top: auto;
}

/* This styles are just for demo */
body {
  background-color: lightsteelblue;
}

footer {
  background-color: lime;
  padding: 16px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>Copyright © 2017 LeagueOn. all rights reserved</footer></code>```

This will work even in case of long page:

body {
  margin: 0;

  display: flex;
  flex-direction: column;
  height: 100vh;  /* min-height: 100vh will also work everywhere except IE */
}

footer {
  /* move footer to the bottom */
  margin-top: auto;
}

/* This styles are just for demo */
body {
  background-color: lightsteelblue;
}

footer {
  background-color: lime;
  padding: 16px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sodales molestie orci vitae facilisis. Duis non urna eget felis blandit facilisis vel sit amet purus. Donec finibus ex eget ultrices ultricies. Sed porttitor lobortis mi dignissim lacinia. Phasellus eget iaculis mauris, quis placerat augue. Quisque luctus condimentum neque, sed feugiat ipsum sagittis at. Mauris ut commodo eros.

Sed vel faucibus lacus, efficitur dapibus lectus. Sed consectetur luctus odio. Sed tempus aliquet enim, ac ullamcorper augue tincidunt at. Pellentesque vehicula iaculis elit eleifend viverra. Etiam scelerisque maximus felis. Aenean mollis nisl non eros faucibus mattis. Phasellus dictum venenatis ex vel ultricies.

Suspendisse auctor, nunc at ullamcorper hendrerit, dui enim laoreet nisl, id ullamcorper elit ex in lorem. Ut malesuada ipsum et euismod fermentum. Etiam euismod feugiat lacus eget luctus. Sed tempor vestibulum lectus. Suspendisse tincidunt ut massa ac interdum. Pellentesque mattis sapien in augue imperdiet, vel imperdiet massa convallis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum nec consectetur nunc.

Mauris vel sodales ex. Aenean at lectus non libero sagittis aliquam nec eget nisi. Proin massa tortor, iaculis in ante ut, hendrerit sodales sem. Aenean blandit vestibulum dolor et viverra. Mauris non nunc eget odio vulputate viverra. Morbi sagittis nisl at risus convallis vestibulum. Aenean pellentesque sit amet nibh id lobortis.

Ut consequat ligula risus, sit amet congue dolor consequat maximus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur ultrices tellus at placerat hendrerit. Fusce ullamcorper ante id urna scelerisque, eget interdum libero feugiat. Sed consectetur eget metus et euismod. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse potenti. Maecenas malesuada interdum mauris, tempor porttitor odio porttitor eu. Vestibulum sollicitudin justo velit, nec porttitor risus luctus non. Fusce tempor dapibus magna a luctus. Donec ex turpis, venenatis vulputate lacus in, pharetra auctor nisi. Pellentesque dictum elit ut mollis vehicula. Donec vulputate suscipit felis vitae accumsan. Ut fermentum aliquam ipsum sit amet condimentum. Phasellus sollicitudin ligula elit, in efficitur leo dignissim a. Quisque dignissim dolor malesuada interdum interdum.

Nulla congue nibh erat, et tincidunt nulla maximus id. Duis placerat suscipit ex. Integer ut tortor sapien. Vestibulum dapibus sed ex at pharetra. Aliquam blandit facilisis erat. Proin imperdiet cursus arcu, non congue neque tempor nec. Maecenas ut nibh semper, dictum velit sit amet, vehicula nisl. Nullam ac tempor libero. Donec elit lorem, luctus et maximus in, iaculis sed neque. Duis vehicula lacus vitae eros congue, at molestie nisi eleifend. Nulla erat diam, dapibus eu consectetur et, rutrum non quam. Duis imperdiet laoreet elit ac varius. Nulla ultricies pellentesque libero, eget tincidunt tortor elementum quis.

Morbi vitae pharetra ante. Aenean maximus rutrum nunc, eget tempor nunc. Aenean nisi erat, egestas a rhoncus ut, tempus non nisl. Donec venenatis aliquam pulvinar. Sed in tortor neque. Fusce sollicitudin arcu vitae justo faucibus, sit amet sodales neque suscipit. Aliquam in sollicitudin diam. Donec a eros magna. Quisque vel posuere ipsum, quis vehicula odio. Morbi non dolor velit. Vivamus varius velit purus, bibendum volutpat magna eleifend ut. Quisque imperdiet pharetra nunc, id efficitur eros interdum sit amet. Sed commodo maximus risus et iaculis.

Fusce facilisis hendrerit leo. Donec a justo vel velit pellentesque congue et convallis sem. Nullam et urna justo. Donec aliquet mi ac turpis lacinia, in faucibus nunc tempor. Mauris at magna vitae ex volutpat blandit. Integer sed faucibus odio, in congue turpis. Vivamus pellentesque condimentum sagittis. Aliquam fermentum consequat massa non imperdiet.

Interdum et malesuada fames ac ante ipsum primis in faucibus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris pellentesque interdum arcu, at tempor tortor tincidunt sed. Aliquam quis odio rhoncus, pharetra ligula vitae, tempus ante. Aenean ultrices ultrices purus eu interdum. Nullam malesuada dui sit amet enim feugiat dignissim. Vestibulum purus orci, fermentum vitae augue ac, semper scelerisque lectus. Etiam congue erat nec eleifend dapibus. Vestibulum vel mattis lacus. Proin urna nunc, sollicitudin quis volutpat varius, posuere vitae elit. Mauris felis ex, elementum et venenatis at, sagittis at quam. Donec nec pulvinar metus. Morbi sit amet tortor tortor.

Sed cursus fermentum nibh, ac fringilla ante dignissim non. Morbi in hendrerit lacus. Nam pulvinar ultricies dolor vitae ultrices. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent at neque sapien. Nam nisi velit, porta nec ultricies venenatis, semper sit amet mauris. Praesent sagittis ullamcorper lorem, imperdiet eleifend nisl vehicula quis. Cras ut vulputate metus. Ut in congue enim, vel efficitur tortor.

Integer velit erat, fringilla tincidunt porttitor gravida, pulvinar nec elit. Pellentesque ornare porttitor lorem ut congue. Pellentesque sagittis libero in est tristique feugiat. Suspendisse et ex fringilla dui tincidunt iaculis. Etiam a mollis enim, in scelerisque orci. Sed accumsan viverra nunc, a varius tellus molestie malesuada. Nam nec fringilla tellus, sed facilisis tortor. Nulla sed est sed orci tincidunt tincidunt. Morbi luctus imperdiet mi, eget molestie purus venenatis vel.

Integer venenatis dignissim nisi vel dignissim. Mauris vitae maximus felis, et tincidunt eros. Vivamus luctus scelerisque ligula, nec semper turpis volutpat ut. Ut vestibulum nisi vel justo iaculis, sed congue ante vulputate. Maecenas suscipit, mi at pulvinar tempus, nisl lorem molestie massa, ac vestibulum risus neque sit amet purus. Cras ultrices vulputate eros, a volutpat urna luctus ac. Curabitur viverra nunc in mauris mattis, pretium faucibus nibh convallis. Vivamus fermentum magna consectetur velit condimentum finibus. Vestibulum luctus dolor ut elit dictum, sed posuere ligula aliquam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tincidunt nisi tellus, nec iaculis tellus feugiat nec. Vivamus sodales molestie velit, quis porta augue rhoncus ac. Sed elementum mi in est venenatis, vitae posuere risus imperdiet.

Pellentesque scelerisque id urna iaculis interdum. Nulla cursus nibh at quam pretium mattis. Quisque at elit metus. Sed pellentesque, lacus et placerat tincidunt, orci metus rutrum ante, pharetra iaculis urna ipsum ac ipsum. Ut maximus ante sit amet finibus vestibulum. Nam lacinia tellus vehicula, gravida tellus vitae, maximus lacus. Integer placerat enim et fringilla commodo.

Cras non accumsan erat, vel dapibus velit. Sed eu dolor tellus. Integer varius mauris nibh, quis pharetra magna congue non. Aliquam libero nisl, suscipit eu congue id, tristique in magna. Maecenas rutrum magna non tincidunt convallis. Aliquam aliquam, mi ut dictum rhoncus, nisl neque lobortis tortor, at mattis odio eros ut justo. Vestibulum egestas risus nec nisl placerat maximus. Nunc orci purus, egestas at rutrum id, eleifend semper erat. In hac habitasse platea dictumst. Vivamus diam ipsum, aliquam ut placerat ac, ultrices nec arcu. Integer eu ultrices dolor, non luctus orci. Proin sodales pulvinar dui, et sollicitudin tellus dapibus nec. Praesent quis consectetur eros, non ornare tortor.

Curabitur vitae lorem vitae est scelerisque facilisis vitae non augue. Duis erat metus, iaculis a velit et, iaculis vehicula nisl. Mauris tristique pellentesque suscipit. Maecenas a nisl dui. In lacus justo, fringilla ut tortor non, dignissim aliquet nisi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam non lectus libero. Proin consequat eleifend justo. Praesent dolor enim, fringilla ut accumsan sit amet, egestas et augue. Nunc mattis dolor quis sodales tempus.

Integer sed ornare dolor. Quisque id dapibus tortor. Quisque ornare, ex quis consequat porttitor, arcu justo aliquet diam, in sollicitudin odio sem laoreet dolor. Ut elit dolor, semper vitae consectetur rutrum, finibus in felis. Nunc volutpat quam ut ligula varius volutpat. Nunc porttitor dictum libero et facilisis. Nam a libero a nisi aliquet mollis. Integer eget ipsum accumsan, interdum elit sit amet, ultrices massa. Nullam nec est id lorem dignissim aliquet nec at urna. Maecenas ante lorem, rutrum ac commodo ac, viverra quis enim. Etiam convallis sapien eu leo dignissim condimentum. Morbi ut ex eu enim fermentum varius at non turpis. Nulla sed libero pharetra, ornare mi sit amet, scelerisque odio. Mauris sit amet mi non mi ornare commodo. Proin eget lacinia erat. Nunc dictum lobortis justo sed vulputate.

Proin ullamcorper finibus nisi egestas aliquam. Sed tempor ornare massa at semper. Integer ultrices diam a libero fringilla faucibus. Proin vitae leo nec neque laoreet imperdiet. Donec mattis gravida massa ac blandit. Aliquam et accumsan urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam rhoncus elementum est nec iaculis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse et sapien orci. Vestibulum ut venenatis velit. Sed sodales volutpat risus vel aliquam. In hac habitasse platea dictumst.

Sed tempus nibh tempus bibendum viverra. Maecenas sit amet magna pretium, pharetra nisl at, ullamcorper elit. Integer ipsum diam, laoreet at consectetur at, rutrum eu mi. Duis et neque mauris. Pellentesque consequat augue et tortor commodo ornare. Nulla sed dui non sem vehicula bibendum vitae nec nibh. Curabitur ut arcu lacus. Donec vel orci dolor. Nam vel nibh a turpis ultricies dapibus rhoncus sit amet lorem. Aliquam condimentum mollis aliquam. Pellentesque laoreet vitae mauris id ornare. In id malesuada nisi.

Phasellus eu aliquam magna, sed efficitur dui. Morbi sagittis tellus vitae velit lacinia, ac molestie massa accumsan. Nullam molestie odio non turpis bibendum rutrum. Donec pellentesque nunc in massa ultrices, a pulvinar ex porta. Curabitur pretium placerat eleifend. Vivamus in dolor id dolor dapibus scelerisque. Etiam pretium placerat laoreet.

Nam at varius nibh, nec ullamcorper tellus. Vivamus ut metus sit amet ligula lobortis ultrices. Vestibulum sed metus id tortor pellentesque dignissim sit amet quis tellus. Integer porta laoreet massa. Fusce tincidunt eros sed neque egestas tristique. Donec eleifend elit volutpat purus sagittis gravida ut vitae purus. Suspendisse a neque id enim euismod egestas et in arcu. Vivamus placerat nulla vel ex dapibus, nec rutrum risus imperdiet. Nam aliquet felis vel turpis varius venenatis. Curabitur a tempus velit, eget vulputate dolor. Nullam feugiat risus risus, in finibus mauris egestas eu.

Donec arcu ligula, pulvinar eu dapibus ut, viverra id ante. Integer in tempus leo, quis finibus felis. Sed sollicitudin libero quis mi vehicula, et blandit tellus porttitor. In in interdum leo. Pellentesque blandit nisi eu quam tempus, vel bibendum augue accumsan. Nam eget suscipit magna, sit amet lacinia velit. Nullam tincidunt, quam a lobortis pharetra, arcu velit pulvinar risus, quis fermentum erat lacus ut neque. Aenean ex elit, feugiat semper vestibulum sed, porttitor at massa.

Proin turpis metus, commodo porta sem non, faucibus hendrerit magna. Nulla sodales gravida quam ac aliquet. Nam posuere lobortis ultricies. Nulla ac odio venenatis, tempor lorem at, varius diam. Suspendisse malesuada lacus vel sapien malesuada, quis faucibus urna eleifend. Donec aliquam erat ut est pellentesque suscipit. Nunc diam lorem, semper et porttitor vitae, commodo eget nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec eu dapibus lorem. Aenean auctor, risus vel efficitur fringilla, neque ex elementum augue, eget aliquam arcu risus quis ligula. Sed viverra mauris tortor, ut tempus risus luctus vitae. Vestibulum tincidunt blandit tortor, eu scelerisque nisl pulvinar et. Ut placerat odio urna, at consequat risus sagittis ac. Fusce imperdiet, enim ut commodo auctor, lectus ante efficitur velit, sed ullamcorper dui purus eu nunc. Nam in mauris venenatis, pretium tortor a, accumsan metus.

Donec efficitur suscipit metus id ullamcorper. Etiam ipsum eros, luctus ut maximus non, pellentesque ut dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tempor leo eu dolor pulvinar, at rutrum nulla volutpat. Curabitur quis mollis augue. Nunc porttitor suscipit odio, laoreet facilisis mi luctus convallis. Nunc urna purus, mattis at sollicitudin eget, pharetra quis sapien. Sed porttitor, lacus sed posuere aliquam, quam odio pellentesque ante, sed volutpat est justo sit amet purus. Aenean consequat condimentum tellus, in sagittis dolor molestie quis. Aenean eget enim sem. Vivamus rutrum mi in magna rutrum, vitae euismod lorem pulvinar. Quisque viverra urna odio, eu tristique orci ultricies eu. Nam facilisis malesuada mattis. Ut tempor nibh eu sapien pellentesque facilisis. Aenean fringilla urna ut lorem viverra, quis condimentum elit iaculis.

Nullam aliquam, leo nec iaculis maximus, nisl nulla pretium leo, vitae iaculis nunc mi sit amet ante. Donec ullamcorper velit vitae dictum placerat. Nulla facilisi. Donec lobortis ut diam et pulvinar. Pellentesque suscipit suscipit aliquet. Nulla et pharetra tellus, nec semper erat. Praesent metus mauris, accumsan ut tempus ut, dignissim eget ante. Nulla eget diam sit amet enim luctus interdum. Quisque volutpat, enim vitae sollicitudin fermentum, odio metus fermentum ante, nec ultrices augue dolor eu eros. Nam eu venenatis dui. Vivamus volutpat accumsan nibh, in tincidunt lorem commodo sit amet.

Ut rhoncus, nunc ut lacinia vulputate, nisi purus efficitur massa, id suscipit ex felis nec mauris. Cras malesuada sapien et congue consectetur. Mauris molestie nisl vel purus convallis rutrum. Sed tristique dictum consectetur. Curabitur justo ante, semper sit amet ultrices at, placerat at lacus. Aenean lorem quam, tempor nec arcu nec, viverra ornare mi. Aenean ante velit, vestibulum non libero a, ullamcorper vulputate lectus. Aenean congue, metus ac lobortis dignissim, elit nunc interdum magna, eu sagittis neque mi vitae nibh. Etiam eget lacus quam. Duis quis augue eget eros congue molestie eget at dui.

<footer>Copyright © 2017 LeagueOn. all rights reserved</footer></code>```

Title: Footer overlaps other elements

Body:
I am trying to fix this footer.  If i remove positon it works fine but some other pages still have a problem.  I need this footer at the bottom of every page...

  footer {
   position: absolute;
   bottom: 0;
   left: 0;
   width: 100%;
   padding: 16px;
   background:white;
}

 Copyright © 2017 LeagueOn. all rights reserved

Body:
Try to avoid position: absolute where you don't really need it.

You can achieve this via flexbox. Your footer should be direct child of body:

body {
  margin: 0;

  display: flex;
  flex-direction: column;
  height: 100vh;  /* min-height: 100vh will also work everywhere except IE */
}

footer {
  /* move footer to the bottom */
  margin-top: auto;
}

/* This styles are just for demo */
body {
  background-color: lightsteelblue;
}

footer {
  background-color: lime;
  padding: 16px;
  text-align: center;
}

<footer>Copyright &copy; 2017 LeagueOn. all rights reserved</footer>

This will work even in case of long page:

body {
  margin: 0;

  display: flex;
  flex-direction: column;
  height: 100vh;  /* min-height: 100vh will also work everywhere except IE */
}

footer {
  /* move footer to the bottom */
  margin-top: auto;
}

/* This styles are just for demo */
body {
  background-color: lightsteelblue;
}

footer {
  background-color: lime;
  padding: 16px;
  text-align: center;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sodales molestie orci vitae facilisis. Duis non urna eget felis blandit facilisis vel sit amet purus. Donec finibus ex eget ultrices ultricies. Sed porttitor lobortis mi dignissim lacinia. Phasellus eget iaculis mauris, quis placerat augue. Quisque luctus condimentum neque, sed feugiat ipsum sagittis at. Mauris ut commodo eros.

Sed vel faucibus lacus, efficitur dapibus lectus. Sed consectetur luctus odio. Sed tempus aliquet enim, ac ullamcorper augue tincidunt at. Pellentesque vehicula iaculis elit eleifend viverra. Etiam scelerisque maximus felis. Aenean mollis nisl non eros faucibus mattis. Phasellus dictum venenatis ex vel ultricies.

Suspendisse auctor, nunc at ullamcorper hendrerit, dui enim laoreet nisl, id ullamcorper elit ex in lorem. Ut malesuada ipsum et euismod fermentum. Etiam euismod feugiat lacus eget luctus. Sed tempor vestibulum lectus. Suspendisse tincidunt ut massa ac interdum. Pellentesque mattis sapien in augue imperdiet, vel imperdiet massa convallis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum nec consectetur nunc.

Mauris vel sodales ex. Aenean at lectus non libero sagittis aliquam nec eget nisi. Proin massa tortor, iaculis in ante ut, hendrerit sodales sem. Aenean blandit vestibulum dolor et viverra. Mauris non nunc eget odio vulputate viverra. Morbi sagittis nisl at risus convallis vestibulum. Aenean pellentesque sit amet nibh id lobortis.

Ut consequat ligula risus, sit amet congue dolor consequat maximus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur ultrices tellus at placerat hendrerit. Fusce ullamcorper ante id urna scelerisque, eget interdum libero feugiat. Sed consectetur eget metus et euismod. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse potenti. Maecenas malesuada interdum mauris, tempor porttitor odio porttitor eu. Vestibulum sollicitudin justo velit, nec porttitor risus luctus non. Fusce tempor dapibus magna a luctus. Donec ex turpis, venenatis vulputate lacus in, pharetra auctor nisi. Pellentesque dictum elit ut mollis vehicula. Donec vulputate suscipit felis vitae accumsan. Ut fermentum aliquam ipsum sit amet condimentum. Phasellus sollicitudin ligula elit, in efficitur leo dignissim a. Quisque dignissim dolor malesuada interdum interdum.

Nulla congue nibh erat, et tincidunt nulla maximus id. Duis placerat suscipit ex. Integer ut tortor sapien. Vestibulum dapibus sed ex at pharetra. Aliquam blandit facilisis erat. Proin imperdiet cursus arcu, non congue neque tempor nec. Maecenas ut nibh semper, dictum velit sit amet, vehicula nisl. Nullam ac tempor libero. Donec elit lorem, luctus et maximus in, iaculis sed neque. Duis vehicula lacus vitae eros congue, at molestie nisi eleifend. Nulla erat diam, dapibus eu consectetur et, rutrum non quam. Duis imperdiet laoreet elit ac varius. Nulla ultricies pellentesque libero, eget tincidunt tortor elementum quis.

Morbi vitae pharetra ante. Aenean maximus rutrum nunc, eget tempor nunc. Aenean nisi erat, egestas a rhoncus ut, tempus non nisl. Donec venenatis aliquam pulvinar. Sed in tortor neque. Fusce sollicitudin arcu vitae justo faucibus, sit amet sodales neque suscipit. Aliquam in sollicitudin diam. Donec a eros magna. Quisque vel posuere ipsum, quis vehicula odio. Morbi non dolor velit. Vivamus varius velit purus, bibendum volutpat magna eleifend ut. Quisque imperdiet pharetra nunc, id efficitur eros interdum sit amet. Sed commodo maximus risus et iaculis.

Fusce facilisis hendrerit leo. Donec a justo vel velit pellentesque congue et convallis sem. Nullam et urna justo. Donec aliquet mi ac turpis lacinia, in faucibus nunc tempor. Mauris at magna vitae ex volutpat blandit. Integer sed faucibus odio, in congue turpis. Vivamus pellentesque condimentum sagittis. Aliquam fermentum consequat massa non imperdiet.

Interdum et malesuada fames ac ante ipsum primis in faucibus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris pellentesque interdum arcu, at tempor tortor tincidunt sed. Aliquam quis odio rhoncus, pharetra ligula vitae, tempus ante. Aenean ultrices ultrices purus eu interdum. Nullam malesuada dui sit amet enim feugiat dignissim. Vestibulum purus orci, fermentum vitae augue ac, semper scelerisque lectus. Etiam congue erat nec eleifend dapibus. Vestibulum vel mattis lacus. Proin urna nunc, sollicitudin quis volutpat varius, posuere vitae elit. Mauris felis ex, elementum et venenatis at, sagittis at quam. Donec nec pulvinar metus. Morbi sit amet tortor tortor.

Sed cursus fermentum nibh, ac fringilla ante dignissim non. Morbi in hendrerit lacus. Nam pulvinar ultricies dolor vitae ultrices. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent at neque sapien. Nam nisi velit, porta nec ultricies venenatis, semper sit amet mauris. Praesent sagittis ullamcorper lorem, imperdiet eleifend nisl vehicula quis. Cras ut vulputate metus. Ut in congue enim, vel efficitur tortor.

Integer velit erat, fringilla tincidunt porttitor gravida, pulvinar nec elit. Pellentesque ornare porttitor lorem ut congue. Pellentesque sagittis libero in est tristique feugiat. Suspendisse et ex fringilla dui tincidunt iaculis. Etiam a mollis enim, in scelerisque orci. Sed accumsan viverra nunc, a varius tellus molestie malesuada. Nam nec fringilla tellus, sed facilisis tortor. Nulla sed est sed orci tincidunt tincidunt. Morbi luctus imperdiet mi, eget molestie purus venenatis vel.

Integer venenatis dignissim nisi vel dignissim. Mauris vitae maximus felis, et tincidunt eros. Vivamus luctus scelerisque ligula, nec semper turpis volutpat ut. Ut vestibulum nisi vel justo iaculis, sed congue ante vulputate. Maecenas suscipit, mi at pulvinar tempus, nisl lorem molestie massa, ac vestibulum risus neque sit amet purus. Cras ultrices vulputate eros, a volutpat urna luctus ac. Curabitur viverra nunc in mauris mattis, pretium faucibus nibh convallis. Vivamus fermentum magna consectetur velit condimentum finibus. Vestibulum luctus dolor ut elit dictum, sed posuere ligula aliquam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tincidunt nisi tellus, nec iaculis tellus feugiat nec. Vivamus sodales molestie velit, quis porta augue rhoncus ac. Sed elementum mi in est venenatis, vitae posuere risus imperdiet.

Pellentesque scelerisque id urna iaculis interdum. Nulla cursus nibh at quam pretium mattis. Quisque at elit metus. Sed pellentesque, lacus et placerat tincidunt, orci metus rutrum ante, pharetra iaculis urna ipsum ac ipsum. Ut maximus ante sit amet finibus vestibulum. Nam lacinia tellus vehicula, gravida tellus vitae, maximus lacus. Integer placerat enim et fringilla commodo.

Cras non accumsan erat, vel dapibus velit. Sed eu dolor tellus. Integer varius mauris nibh, quis pharetra magna congue non. Aliquam libero nisl, suscipit eu congue id, tristique in magna. Maecenas rutrum magna non tincidunt convallis. Aliquam aliquam, mi ut dictum rhoncus, nisl neque lobortis tortor, at mattis odio eros ut justo. Vestibulum egestas risus nec nisl placerat maximus. Nunc orci purus, egestas at rutrum id, eleifend semper erat. In hac habitasse platea dictumst. Vivamus diam ipsum, aliquam ut placerat ac, ultrices nec arcu. Integer eu ultrices dolor, non luctus orci. Proin sodales pulvinar dui, et sollicitudin tellus dapibus nec. Praesent quis consectetur eros, non ornare tortor.

Curabitur vitae lorem vitae est scelerisque facilisis vitae non augue. Duis erat metus, iaculis a velit et, iaculis vehicula nisl. Mauris tristique pellentesque suscipit. Maecenas a nisl dui. In lacus justo, fringilla ut tortor non, dignissim aliquet nisi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam non lectus libero. Proin consequat eleifend justo. Praesent dolor enim, fringilla ut accumsan sit amet, egestas et augue. Nunc mattis dolor quis sodales tempus.

Integer sed ornare dolor. Quisque id dapibus tortor. Quisque ornare, ex quis consequat porttitor, arcu justo aliquet diam, in sollicitudin odio sem laoreet dolor. Ut elit dolor, semper vitae consectetur rutrum, finibus in felis. Nunc volutpat quam ut ligula varius volutpat. Nunc porttitor dictum libero et facilisis. Nam a libero a nisi aliquet mollis. Integer eget ipsum accumsan, interdum elit sit amet, ultrices massa. Nullam nec est id lorem dignissim aliquet nec at urna. Maecenas ante lorem, rutrum ac commodo ac, viverra quis enim. Etiam convallis sapien eu leo dignissim condimentum. Morbi ut ex eu enim fermentum varius at non turpis. Nulla sed libero pharetra, ornare mi sit amet, scelerisque odio. Mauris sit amet mi non mi ornare commodo. Proin eget lacinia erat. Nunc dictum lobortis justo sed vulputate.

Proin ullamcorper finibus nisi egestas aliquam. Sed tempor ornare massa at semper. Integer ultrices diam a libero fringilla faucibus. Proin vitae leo nec neque laoreet imperdiet. Donec mattis gravida massa ac blandit. Aliquam et accumsan urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam rhoncus elementum est nec iaculis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse et sapien orci. Vestibulum ut venenatis velit. Sed sodales volutpat risus vel aliquam. In hac habitasse platea dictumst.

Sed tempus nibh tempus bibendum viverra. Maecenas sit amet magna pretium, pharetra nisl at, ullamcorper elit. Integer ipsum diam, laoreet at consectetur at, rutrum eu mi. Duis et neque mauris. Pellentesque consequat augue et tortor commodo ornare. Nulla sed dui non sem vehicula bibendum vitae nec nibh. Curabitur ut arcu lacus. Donec vel orci dolor. Nam vel nibh a turpis ultricies dapibus rhoncus sit amet lorem. Aliquam condimentum mollis aliquam. Pellentesque laoreet vitae mauris id ornare. In id malesuada nisi.

Phasellus eu aliquam magna, sed efficitur dui. Morbi sagittis tellus vitae velit lacinia, ac molestie massa accumsan. Nullam molestie odio non turpis bibendum rutrum. Donec pellentesque nunc in massa ultrices, a pulvinar ex porta. Curabitur pretium placerat eleifend. Vivamus in dolor id dolor dapibus scelerisque. Etiam pretium placerat laoreet.

Nam at varius nibh, nec ullamcorper tellus. Vivamus ut metus sit amet ligula lobortis ultrices. Vestibulum sed metus id tortor pellentesque dignissim sit amet quis tellus. Integer porta laoreet massa. Fusce tincidunt eros sed neque egestas tristique. Donec eleifend elit volutpat purus sagittis gravida ut vitae purus. Suspendisse a neque id enim euismod egestas et in arcu. Vivamus placerat nulla vel ex dapibus, nec rutrum risus imperdiet. Nam aliquet felis vel turpis varius venenatis. Curabitur a tempus velit, eget vulputate dolor. Nullam feugiat risus risus, in finibus mauris egestas eu.

Donec arcu ligula, pulvinar eu dapibus ut, viverra id ante. Integer in tempus leo, quis finibus felis. Sed sollicitudin libero quis mi vehicula, et blandit tellus porttitor. In in interdum leo. Pellentesque blandit nisi eu quam tempus, vel bibendum augue accumsan. Nam eget suscipit magna, sit amet lacinia velit. Nullam tincidunt, quam a lobortis pharetra, arcu velit pulvinar risus, quis fermentum erat lacus ut neque. Aenean ex elit, feugiat semper vestibulum sed, porttitor at massa.

Proin turpis metus, commodo porta sem non, faucibus hendrerit magna. Nulla sodales gravida quam ac aliquet. Nam posuere lobortis ultricies. Nulla ac odio venenatis, tempor lorem at, varius diam. Suspendisse malesuada lacus vel sapien malesuada, quis faucibus urna eleifend. Donec aliquam erat ut est pellentesque suscipit. Nunc diam lorem, semper et porttitor vitae, commodo eget nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec eu dapibus lorem. Aenean auctor, risus vel efficitur fringilla, neque ex elementum augue, eget aliquam arcu risus quis ligula. Sed viverra mauris tortor, ut tempus risus luctus vitae. Vestibulum tincidunt blandit tortor, eu scelerisque nisl pulvinar et. Ut placerat odio urna, at consequat risus sagittis ac. Fusce imperdiet, enim ut commodo auctor, lectus ante efficitur velit, sed ullamcorper dui purus eu nunc. Nam in mauris venenatis, pretium tortor a, accumsan metus.

Donec efficitur suscipit metus id ullamcorper. Etiam ipsum eros, luctus ut maximus non, pellentesque ut dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tempor leo eu dolor pulvinar, at rutrum nulla volutpat. Curabitur quis mollis augue. Nunc porttitor suscipit odio, laoreet facilisis mi luctus convallis. Nunc urna purus, mattis at sollicitudin eget, pharetra quis sapien. Sed porttitor, lacus sed posuere aliquam, quam odio pellentesque ante, sed volutpat est justo sit amet purus. Aenean consequat condimentum tellus, in sagittis dolor molestie quis. Aenean eget enim sem. Vivamus rutrum mi in magna rutrum, vitae euismod lorem pulvinar. Quisque viverra urna odio, eu tristique orci ultricies eu. Nam facilisis malesuada mattis. Ut tempor nibh eu sapien pellentesque facilisis. Aenean fringilla urna ut lorem viverra, quis condimentum elit iaculis.

Nullam aliquam, leo nec iaculis maximus, nisl nulla pretium leo, vitae iaculis nunc mi sit amet ante. Donec ullamcorper velit vitae dictum placerat. Nulla facilisi. Donec lobortis ut diam et pulvinar. Pellentesque suscipit suscipit aliquet. Nulla et pharetra tellus, nec semper erat. Praesent metus mauris, accumsan ut tempus ut, dignissim eget ante. Nulla eget diam sit amet enim luctus interdum. Quisque volutpat, enim vitae sollicitudin fermentum, odio metus fermentum ante, nec ultrices augue dolor eu eros. Nam eu venenatis dui. Vivamus volutpat accumsan nibh, in tincidunt lorem commodo sit amet.

Ut rhoncus, nunc ut lacinia vulputate, nisi purus efficitur massa, id suscipit ex felis nec mauris. Cras malesuada sapien et congue consectetur. Mauris molestie nisl vel purus convallis rutrum. Sed tristique dictum consectetur. Curabitur justo ante, semper sit amet ultrices at, placerat at lacus. Aenean lorem quam, tempor nec arcu nec, viverra ornare mi. Aenean ante velit, vestibulum non libero a, ullamcorper vulputate lectus. Aenean congue, metus ac lobortis dignissim, elit nunc interdum magna, eu sagittis neque mi vitae nibh. Etiam eget lacus quam. Duis quis augue eget eros congue molestie eget at dui.

<footer>Copyright &copy; 2017 LeagueOn. all rights reserved</footer>


来源: stackexchange

问:
How to arrange money into funds, when funds can share expenses
If I am managing a club which has expenses (e.g. coffee, building repairs, electricity, cake, etc). Every time the club takes on an expense, then a record is added to the 'All Actual Expenses' table:

```<code> ______________________      _______________________
|All Possible Expenses |    |All Actual Expenses    |
-----------------------      -----------------------
| ID                   |    | ID                    |
| Name of expense      |    | AllPossibleExpensesID |
-----------------------     | Date Occured          |
                            | Price                 |
                            -------------------------
</code>```

Expenses can be arranged into funds (like 'Expenses of year 2017', 'Food Expenses', 'Expenses of business meeting held to discuss premises' etc.).

So the tables for funds is:

```<code> ___________      _________________________________________
| Funds     |    | Funds LINK AllActualExpenses            |
------------|    |-----------------------------------------|
| Id        |    | FundID                                  |
| Fund Name |    | AllActualExpensesID that's in this fund |
------------      -----------------------------------------
</code>```

As you can see, funds can 'overlap', so an expense can be part of a few funds.

When money is paid in to the club's coffers, the money can be allocated only to certain funds, like so:

```<code>_________________     _____________________________________
|Payments        |    | Payments LINK Funds                |
-----------------|    |------------------------------------|
| ID             |    | PaymentID                          |
| Date           |    | A FundID that this is allocated to |
| Amount Paid In |    -------------------------------------
| Member ID      |
-----------------|
</code>```

This LOOKS good, but there's a problem I can't for the life of me work out what to do:

How do I show how much money each fund has in it? Remember, some money might be allocated to Funds ONE and TWO, while other money might be allocated to Funds TWO and THREE...so in reality, is there a good way to show how much money is in Funds ONE, how much money is in Fund TWO, and how much money is in Fund THREE?

The problem is, if the program simply shows how much money is in each fund, it will seem to the user that the club has far more money than it really has!

By extension, the following issues also crop up:

What if some money isn't given to any funds...how will the program allocate it? How will the program show this money?

If someone wants to give money towards certain expenses which aren't grouped in one fund alone, should I create a 'custom fund' for them? If I put the money straight towards the expenses, I will violate database theory (I think) because some money will be allocated direct to expenses and some money will be allocated to Funds!

I dunno, maybe I'm overlooking an obvious solution. Has this model been tackled before? Thanks in advance for any ideas.

答:
In "Payments Linked Expenses", you need to include an allocation column.  Then, your query looks like:

```<code>Select flae.fundID, sum(ae.Price * flae.allocation) as price
from fundsLinkActualExpenses as flae join
     ActualExpenses as ae
    on flae.ExpensesID = flae.ExpensesID
group by flae.fundID;
</code>```

You will need to have triggers to ensure that the allocations add up to 100% when new expenses and funds and links are added.

ContentLicense: CC BY-SA 3.0

Body:
If I am managing a club which has expenses (e.g. coffee, building repairs, electricity, cake, etc). Every time the club takes on an expense, then a record is added to the 'All Actual Expenses' table:

 ______________________      _______________________
|All Possible Expenses |    |All Actual Expenses    |
-----------------------      -----------------------
| ID                   |    | ID                    |
| Name of expense      |    | AllPossibleExpensesID |
-----------------------     | Date Occured          |
                            | Price                 |
                            -------------------------

Expenses can be arranged into funds (like 'Expenses of year 2017', 'Food Expenses', 'Expenses of business meeting held to discuss premises' etc.).

So the tables for funds is:

 ___________      _________________________________________
| Funds     |    | Funds LINK AllActualExpenses            |
------------|    |-----------------------------------------|
| Id        |    | FundID                                  |
| Fund Name |    | AllActualExpensesID that's in this fund |
------------      -----------------------------------------

As you can see, funds can 'overlap', so an expense can be part of a few funds.

When money is paid in to the club's coffers, the money can be allocated only to certain funds, like so:

_________________     _____________________________________
|Payments        |    | Payments LINK Funds                |
-----------------|    |------------------------------------|
| ID             |    | PaymentID                          |
| Date           |    | A FundID that this is allocated to |
| Amount Paid In |    -------------------------------------
| Member ID      |
-----------------|

This LOOKS good, but there's a problem I can't for the life of me work out what to do:

How do I show how much money each fund has in it? Remember, some money might be allocated to Funds ONE and TWO, while other money might be allocated to Funds TWO and THREE...so in reality, is there a good way to show how much money is in Funds ONE, how much money is in Fund TWO, and how much money is in Fund THREE?

The problem is, if the program simply shows how much money is in each fund, it will seem to the user that the club has far more money than it really has!

By extension, the following issues also crop up:

What if some money isn't given to any funds...how will the program allocate it? How will the program show this money?

If someone wants to give money towards certain expenses which aren't grouped in one fund alone, should I create a 'custom fund' for them? If I put the money straight towards the expenses, I will violate database theory (I think) because some money will be allocated direct to expenses and some money will be allocated to Funds!

I dunno, maybe I'm overlooking an obvious solution. Has this model been tackled before? Thanks in advance for any ideas.

Body:
In "Payments Linked Expenses", you need to include an allocation column.  Then, your query looks like:

Select flae.fundID, sum(ae.Price * flae.allocation) as price
from fundsLinkActualExpenses as flae join
     ActualExpenses as ae
    on flae.ExpensesID = flae.ExpensesID
group by flae.fundID;

You will need to have triggers to ensure that the allocations add up to 100% when new expenses and funds and links are added.


问:
Can I write an app for my android phone using VB?
I have struggled using Word for this need but it is cryptic.  If I could understand how to use Excel in the phone, it might work.  However, I am beginning to see that I should design my own app and the only programming language I know well enough is Visual BASIC.

Can this work?

答:
I don't believe so.

If you're prepared to jump the gap to C# then Xamarin will interest you. It's bundled with modern versions of Visual Studio so there's lots of examples and support out there on it.

Have a read and see if it's for you: https://www.xamarin.com/getting-started/android

edit: slightly newer link: https://developer.xamarin.com/guides/android/getting_started/hello,android/hello,android_quickstart/

ContentLicense: CC BY-SA 4.0


问:
If cell is touched - move on the another VC [SWIFT]
If cell is touched - move on the another VC, how can i do it?
I tried to do it, but i didn't work.
Here is my code

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData" {
        let destination = segue.destination as! WinnerViewController

        let cell = sender as? UITableViewCell

        if cell == cell {
            let indexPath = tableView.indexPath(for: cell!)
            if indexPath == indexPath {
                let productName = users[(indexPath?.row)!]
                destination.winner = productName.name
            }
        }
    }
</code>```

When i touch each cell - it isn't moving.
Please help

答:
```<code>Hi you can do like this :
take Indexpath as golbal variable eg : var indexPathTemp : IndexPath?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  indexPathTemp = indexPath
  performSegueWithIdentifier("transData", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData" {
        let destination = segue.destination as! WinnerViewController
                let productName = users[(indexPath?.row)!]
                destination.winner = productName.name
            }

    }
</code>```

Body:
If cell is touched - move on the another VC, how can i do it?
I tried to do it, but i didn't work.
Here is my code

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData" {
        let destination = segue.destination as! WinnerViewController

        let cell = sender as? UITableViewCell

        if cell == cell {
            let indexPath = tableView.indexPath(for: cell!)
            if indexPath == indexPath {
                let productName = users[(indexPath?.row)!]
                destination.winner = productName.name
            }
        }
    }

When i touch each cell - it isn't moving.
Please help


问:
Trigger .onclick() on hover over another element
I'm trying to trigger an .onclick() event when I hover over another div.

The element that needs to trigger the .onclick() event has the ID #exp_des_p_trig.

.

The element that needs to be triggered has the href value #exp_des_p in an a tag.

.

I can understand the basics/read JS but I can't write it (yet), I'm thinking something like this:

```<code><script>
jQuery('#exp_des_p_trig').hover();
    jQuery('#exp_des_p').onclick();
</script>
</code>```

Can anyone help me correct this so that it works?

UPDATE:

I emailed Visual Composer support about this and this is the response I got:

Instead of triggering a click event you can try attaching vc_active class to the tour vc_tta-tab and vc_tta-panel via js. The vc_active class is responsible for opening a tour content for display.

Thank you for the answers below, it seems that this is a Visual Composer related issue which I will address elsewhere.

答:
Check out trigger method

var red = $('#clickAbleElement').click(function(){
  alert('You have clicked on red');
})

var green = $('#hoverMe').hover(function(){
  red.trigger('click');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#clickAbleElement {
  width:100px;
  height:100px;
  background-color:red;
}

#hoverMe {
  width:100px;
  height:100px;
  background-color:green;
}</code>```

Click Me

Hover Me
```

Body:
I'm trying to trigger an .onclick() event when I hover over another div.

The element that needs to trigger the .onclick() event has the ID #exp_des_p_trig.

.

The element that needs to be triggered has the href value #exp_des_p in an a tag.

.

I can understand the basics/read JS but I can't write it (yet), I'm thinking something like this:

Can anyone help me correct this so that it works?

UPDATE:

I emailed Visual Composer support about this and this is the response I got:

Instead of triggering a click event you can try attaching vc_active class to the tour vc_tta-tab and vc_tta-panel via js. The vc_active class is responsible for opening a tour content for display.

Thank you for the answers below, it seems that this is a Visual Composer related issue which I will address elsewhere.

Body:
Check out trigger method

var red = $('#clickAbleElement').click(function(){
  alert('You have clicked on red');
})

var green = $('#hoverMe').hover(function(){
  red.trigger('click');
})

#clickAbleElement {
  width:100px;
  height:100px;
  background-color:red;
}

#hoverMe {
  width:100px;
  height:100px;
  background-color:green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickAbleElement">Click Me</div>
<div id="hoverMe">Hover Me</div>


问:
Google API: use offline access token in javascript
I started a project using the Google API signin mixed with an angularJS+Firebase app.

What I would like to do is to be able to send an e-mail from one person to another programmatically.

Example: John is logged in, clicks on a button which sends an email to Rachel. But that email is sent using the stored token from Ted, not John's account.

It seems possible using the php library which is not an option here.

So far, I get the token easily using these few lines:

```<code>var GoogleAuth = gapi.auth2.getAuthInstance();
                GoogleAuth.grantOfflineAccess({
                    scope: 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/drive https://mail.google.com/ profile email'
                }).then(function(resp) {
                    console.log(resp);
                    this.storeToken(resp.code);
                });
</code>```

Is it actually possible ?
A quick search just got me results for php or about how you get a token with the JS library... not how to use it !

答:
From my understanding you want to use a refresh token ( offline access ) to send an email from Ted's account via Javascript.

Sadly this is not possible client side. What your code gives you is a 'code' that you can send to your server using a $http.post () and trade with Google server side for a refresh token.

Here is a guide for how to change that code into a refresh token.
 While you can do this client side it would involve exposing your client secret which you should never do.(https://developers.google.com/identity/sign-in/web/server-side-flow)

Every time John wants to send an email from Ted's account your application will have to send a request to your server that:

Sends a request to google with the refresh token and generates an access token (https://developers.google.com/identity/protocols/OAuth2WebServer#offline)

Sends a seccond request to google using the access token to send the email from Ted's account

I hope that this helped.

Body:
I started a project using the Google API signin mixed with an angularJS+Firebase app.

What I would like to do is to be able to send an e-mail from one person to another programmatically.

Example: John is logged in, clicks on a button which sends an email to Rachel. But that email is sent using the stored token from Ted, not John's account.

It seems possible using the php library which is not an option here.

So far, I get the token easily using these few lines:

var GoogleAuth = gapi.auth2.getAuthInstance();
                GoogleAuth.grantOfflineAccess({
                    scope: 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/drive https://mail.google.com/ profile email'
                }).then(function(resp) {
                    console.log(resp);
                    this.storeToken(resp.code);
                });

Is it actually possible ?
A quick search just got me results for php or about how you get a token with the JS library... not how to use it !


问:
python unbroundlocalerror local variable 'chances' referenced before assignment
the following code shows error while i execute it, isn't that i have do the assisgnment in the second line before the Looper() executed? However when i add chances = 5 into the first line of Looper(), it works</p>

```<code>import random

chances = 5
def Looper():
    if chances != 0:
        if real_answer == user_answer:
            print("Gotcha")
            exit()
        elif real_answer < user_answer:
            chances -= 1
            print("Too large")
        else:
            chances -= 1
            print("Too small")
real_answer = random.randint(1, 1000)
user_answer = int(input("This is a guessing game, please guess a         number from 1 to 1000. You have 5 chances"))

Looper()
</code>```

答:
Besides the point that you want chances to be a parameter of Looper (e.g. def looper(chances=5):), you can use global chances inside the function to grab a reference to the outside variable.

Better:

```<code>def looper(chances=5):
    if chances != 0:
        ...
</code>```

Also possible, but global state

```<code>CHANCES = 5
def looper():
    global CHANCES
    if CHANCES != 0:
        ...
</code>```

Full story:

```<code>import random

def looper(real_answer, chances=5):
    for _ in range(chances):
        user_answer = int(input("This is a guessing game, please guess a number from 1 to 1000. You have %i chances" % (chances, )))
        if real_answer == user_answer:
            return True
        elif real_answer < user_answer:
            print("Too large")
        else:
            print("Too small")

if __name__ == '__main__':
    real_answer = random.randint(1, 1000)
    if looper(real_answer):
        print("Gotcha")
</code>```

Body:
the following code shows error while i execute it, isn't that i have do the assisgnment in the second line before the Looper() executed? However when i add chances = 5 into the first line of Looper(), it works

import random

chances = 5
def Looper():
    if chances != 0:
        if real_answer == user_answer:
            print("Gotcha")
            exit()
        elif real_answer < user_answer:
            chances -= 1
            print("Too large")
        else:
            chances -= 1
            print("Too small")
real_answer = random.randint(1, 1000)
user_answer = int(input("This is a guessing game, please guess a         number from 1 to 1000. You have 5 chances"))

Looper()

Body:
Besides the point that you want chances to be a parameter of Looper (e.g. def looper(chances=5):), you can use global chances inside the function to grab a reference to the outside variable.

Better:

def looper(chances=5):
    if chances != 0:
        ...

Also possible, but global state

CHANCES = 5
def looper():
    global CHANCES
    if CHANCES != 0:
        ...

Full story:

import random

def looper(real_answer, chances=5):
    for _ in range(chances):
        user_answer = int(input("This is a guessing game, please guess a number from 1 to 1000. You have %i chances" % (chances, )))
        if real_answer == user_answer:
            return True
        elif real_answer < user_answer:
            print("Too large")
        else:
            print("Too small")

if __name__ == '__main__':
    real_answer = random.randint(1, 1000)
    if looper(real_answer):
        print("Gotcha")


问:
Sidebar is in the wrong place when desktop, but not when mobile
I have a problem with the website I'm currently making for my art
theyoungillustrations.com

I have absolutely no experience in coding, so please explain like I'm five

I'm altering a excisting code, but I experience a problem with the sidebar. Because I made a banner (at the top), the sidebar is currently under it and I can't find out how I can fix that without ruining the mobile-sidebar.

This here seems to be the target, but the style-ing part is the one I'm unsure of.

```<code> <div id="sidebar" class="{select:Header Text Case} ">

<div class="inner animated slow">
    <div class="wrap">

        <nav class="sidebar-navigation cl">
            <ul>

                {block:IfHomeLink}
                    <li><a href="/">Home</a></li>
                {/block:IfHomeLink}

                {block:HasPages}
                    {block:Pages}
                    <li> <a href="{URL}">{Label}</a></li>
                    {/block:Pages}
                {/block:HasPages}

            </ul>
        </nav>

    </div>
</div>
</div>

<div id="header" class="{select:Header Text Case} ">
<div class="wrap">
    <div class="inner">

        <div class="logo">
            {block:ifnotlogoimage}
                <a href="/" title="{lang:Home}">{Title}</a>
            {/block:ifnotlogoimage}
            {block:iflogoimage}
                <a href="/"><img src="{image:Logo}" alt="logo" /></a>
            {/block:iflogoimage}
        </div>

        <nav class="navigation cl">
            <ul>
                {block:HasPages}
                    {block:Pages}
                    <li> <a href="{URL}">{Label}</a></li>
                    {/block:Pages}
                {/block:HasPages}

            </ul>
        </nav>

        </div>
        </div>

        <div class="sidebar-toggle">
            Menu
        </div>

        <div class="close-mobile-modal">
            <svg width="16px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                    <path d="M7.172,10 L3.642,6.47 L0.102,2.93 L2.928,0.1 L10,7.173 L17.07,0.103 L19.9,2.93 L12.827,10 L19.897,17.07 L17.07,19.9 L10,12.827 L2.93,19.897 L0.1,17.07 L7.173,10 L7.172,10 Z"></path>
                </g>
            </svg>
        </div>
    </div>
</div>
</div>
</code>```

Then I have this:

```<code> }
    #sidebar h3 {
        margin-bottom:20px;
        color:{color:Header Text};
        font-size:13px;
    }
    #sidebar-navigation {
       color:{color:Header Text};
        background:{color:Header Background};
        font-size:{text:Header Size};
    }
</code>```

But I'm clueless. Thanks for helping.

答: This is because you need to add a breakpoint for various devices ,you can take help of this url :https://www.w3schools.com/css/css_rwd_mediaqueries.asp</p>

Body:
I have a problem with the website I'm currently making for my art
theyoungillustrations.com

I have absolutely no experience in coding, so please explain like I'm five

I'm altering a excisting code, but I experience a problem with the sidebar. Because I made a banner (at the top), the sidebar is currently under it and I can't find out how I can fix that without ruining the mobile-sidebar.

This here seems to be the target, but the style-ing part is the one I'm unsure of.

                {block:IfHomeLink}

Home

                {/block:IfHomeLink}

                {block:HasPages}
                    {block:Pages}

 {Label}

                    {/block:Pages}
                {/block:HasPages}

            {block:ifnotlogoimage}
                {Title}
            {/block:ifnotlogoimage}
            {block:iflogoimage}

            {/block:iflogoimage}

                {block:HasPages}
                    {block:Pages}

 {Label}

                    {/block:Pages}
                {/block:HasPages}

            Menu

            <svg width="16px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                    <path d="M7.172,10 L3.642,6.47 L0.102,2.93 L2.928,0.1 L10,7.173 L17.07,0.103 L19.9,2.93 L12.827,10 L19.897,17.07 L17.07,19.9 L10,12.827 L2.93,19.897 L0.1,17.07 L7.173,10 L7.172,10 Z"></path>
                </g>
            </svg>

Then I have this:

 }
    #sidebar h3 {
        margin-bottom:20px;
        color:{color:Header Text};
        font-size:13px;
    }
    #sidebar-navigation {
       color:{color:Header Text};
        background:{color:Header Background};
        font-size:{text:Header Size};
    }

But I'm clueless. Thanks for helping.


问:
Is there a Java equivalent for Python's map function?
I would like to easily transform a collection (list) of objects of class A to a collection of objects of class B, just as Python's map function does it. Is there any "well-known" implementation of this (some kind of library)? I've already searched for it in Apache's commons-lang but with no luck. </p>

答:
Could take a look at Google's Guava library:

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Maps.html

ContentLicense: CC BY-SA 2.5


问:
How do I register for systemd service lifecycle events?
I want to be informed about all state changes of service units. I know there is the DBUS API which gives me signals for UnitNew and UnitRemoved, but the semantic is still unclear to me. Also the signals doesn't provide the informations I need.

I'm using go and tried the go-systemd lib from coreos. They provide a way to "subscribe" but it's in fact polling all the unit information available in the system. I do not want to do so every few milliseconds, just to get informed about statechanges.

I also tried the default org.freedesktop.DBus.Properties but I can not get this working.

Please help If you can, I'm out of ideas.

答:
The systemd APIs that contain information about the start or stop of service units are:

The systemd journal. You can listen to it by executing journalctl or forwarding it via network to your program or watching for changes to the files on disk. E.g.: execute journalctl --follow -o json-pretty _PID=1 (you can add various filters like UNIT=gdm.service to only get those for one service) and then parse stdout according to the systemd journal json output format to get the journal messages of systemd. Use the MESSAGE_ID to match what the event means and watch for unknown messages to know when an existing message got replaced with a new one. While this might work robustly enough, log messages are not primarily intended as an API. As such I would recommend to use the below options.

Linux cgroup notifications as they get generated when systemd uses cgroups to start a service.

systemd units via their dependencies (like Wants=)


答:
Your 29 should be a 30, since you are effectively cutting off the last date. Instead of hard coding the last row number, it is best to replace it with a function such as:</p>

```<code>ts ( df [, -1], start = df [1, 1], end = df [nrow (df), 1] )
</code>```

Title: convert data frame to time series in R

Body:
I have monthly data fro last two and half year. I want to convert my data frame to time series. So that I should have

Start :: 2015-01-01

End :: 2017-06-01

Frequency : 1

I have tried

ts (df [, -1], start = df [1, 1], end = df [29, 1])

But I get this really wired output from this.

    Time Series:
    Start = 16436
    End = 17287
   Frequency = 1

            date inflow
   1  2015-01-01   6434

   2  2015-02-01   5595

   3  2015-03-01   3101

   4  2015-04-01   3475

   5  2015-05-01   6519

   6  2015-06-01   7251

   7  2015-07-01   4200

   8  2015-08-01   3622

   9  2015-09-01   4782

   10 2015-10-01   6503

   11 2015-11-01   9460

   12 2015-12-01  15623

   13 2016-01-01  18393

   14 2016-02-01  14410

   15 2016-03-01  11210

   16 2016-04-01  10582

   17 2016-05-01  14316

   18 2016-06-01  11876

   19 2016-07-01  13676

   20 2016-08-01  12466

   21 2016-09-01  17326

   22 2016-10-01  15845

   23 2016-11-01  15569

   24 2016-12-01  24933

   25 2017-01-01  35050

   26 2017-02-01  26008

   27 2017-03-01  25767

   28 2017-04-01  17858

   29 2017-05-01  21089

dput(df)
structure(list(date = structure(c(16436, 16467, 16495, 16526,
16556, 16587, 16617, 16648, 16679, 16709, 16740, 16770, 16801,
16832, 16861, 16892, 16922, 16953, 16983, 17014, 17045, 17075,
17106, 17136, 17167, 17198, 17226, 17257, 17287, 17318), class = "Date"),
    inflow = c(6434L, 5595L, 3101L, 3475L, 6519L, 7251L, 4200L,
    3622L, 4782L, 6503L, 9460L, 15623L, 18393L, 14410L, 11210L,
    10582L, 14316L, 11876L, 13676L, 12466L, 17326L, 15845L, 15569L,
    24933L, 35050L, 26008L, 25767L, 17858L, 21089L, 13570L)), row.names = c(NA,
-30L), class = "data.frame", .Names = c("date", "inflow"))

Many thanks in advance!!

Body:
Your 29 should be a 30, since you are effectively cutting off the last date. Instead of hard coding the last row number, it is best to replace it with a function such as:

ts ( df [, -1], start = df [1, 1], end = df [nrow (df), 1] )


问:
Javafx TableView data refresh
I have combobox, tableview as TableView<Person> and 3 columns.
I want to populate the updated data in TableView as per item I select in combobox.

My Issue: every time I select the item in combobox, the data in table view is added. I want the details to be displayed for the selected item only.

Code:

```<code>public class MyTableController {

    private TableView<Person> personTableView;
    private ObservableList<Person> personTableViewData= FXCollections.observableArrayList();

    initialize() {
        comboBox.valueProperty().addListener(new ChangeListener<String>() {
            @Override public void changed(ObservableValue ov, String oldValue, String newValue) {
                List<Person> filteredPersonList =
                               personList.stream().filter(person -> person.getFirstName().contains(newValue)).collect(Collectors.toList());

                personTableViewData.addAll(filteredPersonList);
                personTableView.setItems(personTableViewData);

            }
        }
</code>```

答:
Use ObservableList.setAll instead of ObservableList.addAll or alternatively create a new ObservableList. Otherwise you're adding new items to the same list on every change instead of replacing the items:

```<code>initialize() {
    personTableView.setItems(personTableViewData);

    comboBox.valueProperty().addListener(new ChangeListener<String>() {
        @Override public void changed(ObservableValue ov, String oldValue, String newValue) {
            List<Person> filteredPersonList =
                           personList.stream().filter(person -> person.getFirstName().contains(newValue)).collect(Collectors.toList());

            personTableViewData.setAll(filteredPersonList);
        }
    }
</code>```

Title: Javafx TableView data refresh

Body:
I have combobox, tableview as TableView<Person> and 3 columns.
I want to populate the updated data in TableView as per item I select in combobox.

My Issue: every time I select the item in combobox, the data in table view is added. I want the details to be displayed for the selected item only.

Code:

public class MyTableController {

    private TableView<Person> personTableView;
    private ObservableList<Person> personTableViewData= FXCollections.observableArrayList();

    initialize() {
        comboBox.valueProperty().addListener(new ChangeListener<String>() {
            @Override public void changed(ObservableValue ov, String oldValue, String newValue) {
                List<Person> filteredPersonList =
                               personList.stream().filter(person -> person.getFirstName().contains(newValue)).collect(Collectors.toList());

                personTableViewData.addAll(filteredPersonList);
                personTableView.setItems(personTableViewData);

            }
        }

Body:
Use ObservableList.setAll instead of ObservableList.addAll or alternatively create a new ObservableList. Otherwise you're adding new items to the same list on every change instead of replacing the items:

initialize() {
    personTableView.setItems(personTableViewData);

    comboBox.valueProperty().addListener(new ChangeListener<String>() {
        @Override public void changed(ObservableValue ov, String oldValue, String newValue) {
            List<Person> filteredPersonList =
                           personList.stream().filter(person -> person.getFirstName().contains(newValue)).collect(Collectors.toList());

            personTableViewData.setAll(filteredPersonList);
        }
    }


问:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: ; <an identifier>
I am executing an update query

```<code>begin

 update active_cus
 set Global_indicator = 'Y' where cust_id = '3311' ;

end;
</code>```

I get the sql error

PLS-00103: Encountered the symbol "end-of-file" when expecting one of
  the following:

;   The symbol
  ";" was substituted for "end-of-file" to continue.

答:
begin
update set ... where ...;
end
commit;

this works for me

Title: PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: ; <an identifier> <a double-quoted delimited-identifier>

Body:
I am executing an update query

begin

 update active_cus
 set Global_indicator = 'Y' where cust_id = '3311' ;

end;

I get the sql error

PLS-00103: Encountered the symbol "end-of-file" when expecting one of
  the following:

;   The symbol
  ";" was substituted for "end-of-file" to continue.


问:
Generate URL client-side for jQuery Grid from json field?
We are using Struts 2 and want a jQuery Grid showing a list of accounts.  When a user clicks an account we want to take them to a page specific to that account.

At this point I'm looking for suggestions as to the best way to do this.  Currently I'm building a URL server side which I then return but this isn't optimal since I don't have access to <s:url>.

One idea I've had is to combine <s:url> and each row Id on the client side but I haven't found a way to do this.  Is there a grid would that allow this? or a better way?

Updated Explanation Attempt:

I am returning a json list to jQuery grid.  One column in the grid is a url but I can't build that in the service level.  Instead I'd love to have a way to use <s:url> when my json results are returned.  Is there anyway to do this?

答:
You cannot use <s:url> client side.
The Struts2-Tags get used serverside
to generate the HTML, so there's
basically no difference if you
construct them yourself or let JSP
construct the HTML.

There's the struts2-jQuery Plugin and with it the jQuery grid plugin. Find out more about it here:
https://code.google.com/p/struts2-jquery/

If you know the actionName and have the ID in the list you're iterating over, you can just code the necessary link yourself (if the object in the list has a getter named getId()):

href="http://host:port/webapp/actionName?id=<s:property value='id' />">

Hope that helps, if not please show the code of the page and / or dredefine your question.

Body:
You cannot use <s:url> client side.
The Struts2-Tags get used serverside
to generate the HTML, so there's
basically no difference if you
construct them yourself or let JSP
construct the HTML.

There's the struts2-jQuery Plugin and with it the jQuery grid plugin. Find out more about it here:
https://code.google.com/p/struts2-jquery/

If you know the actionName and have the ID in the list you're iterating over, you can just code the necessary link yourself (if the object in the list has a getter named getId()):

<a href="http://host:port/webapp/actionName?id=<s:property value='id' />">

Hope that helps, if not please show the code of the page and / or dredefine your question.


问:
how to replace a character INSIDE the text content of many files automatically?
I have a folder /myfolder containing many latex tables.

I need to replace a character in each of them, namely replacing any minus sign -, by an en dash –.

Just to be sure: we are replacing hypens INSIDE all of the tex file in that folder. I dont care about the tex file names.

Doing that manually would be a nightmare (too many files, too many minuses). Is there a way to loop over the files automatically and do the replacement? A solution in Python/R would be great.

Thanks!

答:
Python Solution

```<code>import os
directory = os.getcwd()
for filename in os.listdir(directory):
  if "-" in filename:
    os.rename(os.path.join(directory,filename),os.path.join(directory,filename.replace("-","-")))
</code>```

New solution to replace characters inside a file

u2212 is unicode character for minus and u2014 for en-dash.

```<code>import os
directory = os.getcwd()
import fnmatch

def _changefiletext(fileName):
  with open(fileName,'r') as file:
    str = file.read()
    str = str.decode("utf-8").replace(u"\u2212",u"\u2014").encode("utf-8")
  with open(fileName,'wb') as file:
    file.write(str)

# Filter the files on which you want to run the replace code (*.txt in this case)

matches = []
for root, dirnames, filenames in os.walk(directory):
    for filename in fnmatch.filter(filenames, '*.txt'):
        matches.append(os.path.join(root, filename))

for filename in matches:
  print "Converting file %s" %(filename)
  _changefiletext(filename)
</code>```

Body:
Python Solution

import os
directory = os.getcwd()
for filename in os.listdir(directory):
  if "-" in filename:
    os.rename(os.path.join(directory,filename),os.path.join(directory,filename.replace("-","-")))

New solution to replace characters inside a file

u2212 is unicode character for minus and u2014 for en-dash.

import os
directory = os.getcwd()
import fnmatch

def _changefiletext(fileName):
  with open(fileName,'r') as file:
    str = file.read()
    str = str.decode("utf-8").replace(u"\u2212",u"\u2014").encode("utf-8")
  with open(fileName,'wb') as file:
    file.write(str)

# Filter the files on which you want to run the replace code (*.txt in this case)

matches = []
for root, dirnames, filenames in os.walk(directory):
    for filename in fnmatch.filter(filenames, '*.txt'):
        matches.append(os.path.join(root, filename))

for filename in matches:
  print "Converting file %s" %(filename)
  _changefiletext(filename)


问:
ClassCastException, casting Integer to Double
```<code>ArrayList marks = new ArrayList();
Double sum = 0.0;
sum = ((Double)marks.get(i));
</code>```

Everytime I try to run my program, I get a ClassCastException that states: java.lang.Integer cannot be cast to java.lang.Double

答:
2 things to understand here -

1) If you are casting Primitive interger to Primitive double . It works. e.g. It works fine.

int pri=12; System.out.println((double)pri);

2) if you try to Cast Integer object to Double object or vice - versa , It fails.

```<code>Integer a = 1; Double b = (double) a; // WRONG. Fails with class cast excptn
</code>```

Solution -

```<code>Soln 1) Integer i = 1; Double b = new Double(i);
soln 2) Double d = 2.0; Integer x = d.intValue();
</code>```

Body:
ArrayList marks = new ArrayList();
Double sum = 0.0;
sum = ((Double)marks.get(i));

Everytime I try to run my program, I get a ClassCastException that states: java.lang.Integer cannot be cast to java.lang.Double

Body:
2 things to understand here -

1) If you are casting Primitive interger to Primitive double . It works. e.g. It works fine.

int pri=12; System.out.println((double)pri);

2) if you try to Cast Integer object to Double object or vice - versa , It fails.

Integer a = 1; Double b = (double) a; // WRONG. Fails with class cast excptn

Solution -

Soln 1) Integer i = 1; Double b = new Double(i);
soln 2) Double d = 2.0; Integer x = d.intValue();


问:
Does HTTP2 server push only works for web assets?
Its been sometime I heard about server push,

Will HTTP/2 server push only works for web assets ?

or will it work for other JSON data also ?

答:
It can be used for any cacheable resource which will be used by that page.

Note however that there have been reports of confusion on how exactly to enable it for XHR resources as discussed here: HTTP2 Push XMLHttpRequest Cache Miss in Chrome

If you mean however for general JSON rather than XHR JSON that will be used by the page then no, that is not what HTTP/2 push is for. See here for more details: HTTP/2 Push JSON Payload


问:
Unit testing cookies in PHP
The default practice for unit testing functionality that relies on session/cookie information is to use an abstraction library. But what if I want to write and unit test this abstraction library? The documentation for the PHP setcookiefunction says that the cookie will be available on the next request. Using a command line tool for testing, there is no such thing as a "request". So how can I unit test the correct cookie settings?

I want to test if all the parameters of the setcookie function are set correctly by my abstraction library. Those parameters will be set according to certain conditions and method calls.

The only solution I can think of is to mock the setcookie function with the runkit extension, which I don't want to install. Other ideas?

答:
You can set a value directly into the current $_COOKIE array:

```<code><?php
$_COOKIE['test']='hello';
print_r($_COOKIE);
run_tests();
</code>```

(this works in CLI mode too). Note that $_REQUEST will not be updated by this.

However if you're only trying to manipulate cookies so you can subsequently access the session, why not just access the session directly:

```<code><?php
$_SESSION['auth_user']='root';
run_tests();
</code>```

But we're talking about unit testing here - not integration testing - which suggests that the code is not very well structured.

Title: Unit testing cookies in PHP

Body:
You can set a value directly into the current $_COOKIE array:

<?php
$_COOKIE['test']='hello';
print_r($_COOKIE);
run_tests();

(this works in CLI mode too). Note that $_REQUEST will not be updated by this.

However if you're only trying to manipulate cookies so you can subsequently access the session, why not just access the session directly:

<?php
$_SESSION['auth_user']='root';
run_tests();

But we're talking about unit testing here - not integration testing - which suggests that the code is not very well structured.


问:
How to add animation while changing the hidden mode of a uiview?
I want to add animation to a view while changing its hidden mode i.e

```<code>my_view.hidden=YES;
</code>```

I have added a button in navigationbar. When we click on it the new view is set to be unhide. It draws at the upper of the navigation table.

答:
Here is the code I used to model a view "growing" and "shrinking" on a "show more..." and "show less ..." button click.  Modeled off the answer from Palyancodr

This approach allows me to create both views in the storyboard so that the constraints work as expected on the different iOS devices and I don't need to custom code all the constraints.

```<code>@IBAction func showMoreOrLessAction(_ sender: Any) {
    // if small view showing
    if showMoreLargeView.isHidden {
        showMoreSmallView.isHidden = true

        //showMoreLargeView.isHidden = false
        UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
            self.showMoreLargeView.alpha = 1 // Here you will get the animation you want
        }, completion: { _ in
            self.showMoreLargeView.isHidden = false // Here you hide it when animation done
        })
    }
    else { // large view showing
        //showMoreSmallView.isHidden = false
        UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
            self.showMoreSmallView.alpha = 1 // Here you will get the animation you want
        }, completion: { _ in
            self.showMoreSmallView.isHidden = false // Here you hide it when animation done
        })

        showMoreLargeView.isHidden = true
    }
}
</code>```

Body:
I want to add animation to a view while changing its hidden mode i.e

my_view.hidden=YES;

I have added a button in navigationbar. When we click on it the new view is set to be unhide. It draws at the upper of the navigation table.

Body:
Here is the code I used to model a view "growing" and "shrinking" on a "show more..." and "show less ..." button click.  Modeled off the answer from Palyancodr

This approach allows me to create both views in the storyboard so that the constraints work as expected on the different iOS devices and I don't need to custom code all the constraints.

@IBAction func showMoreOrLessAction(_ sender: Any) {
    // if small view showing
    if showMoreLargeView.isHidden {
        showMoreSmallView.isHidden = true

        //showMoreLargeView.isHidden = false
        UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
            self.showMoreLargeView.alpha = 1 // Here you will get the animation you want
        }, completion: { _ in
            self.showMoreLargeView.isHidden = false // Here you hide it when animation done
        })
    }
    else { // large view showing
        //showMoreSmallView.isHidden = false
        UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
            self.showMoreSmallView.alpha = 1 // Here you will get the animation you want
        }, completion: { _ in
            self.showMoreSmallView.isHidden = false // Here you hide it when animation done
        })

        showMoreLargeView.isHidden = true
    }
}


问:
Multiple requests to OSRM at once (using docker)
I would like to push multiple requests to the OSRM backend (see https://github.com/Project-OSRM/osrm-backend) at once. Currently, for me to get the distance between two points, I do something like this:

```<code>curl "http://127.0.0.1:5000/route/v1/driving/10,50;13,52?overview=false"
</code>```

However, I need to do this for more than 2m rows... So I would like to know if I can send the docker image multiple requests at the same time?

Or if anyone has a better idea, it would be great!

答:
I think what you are looking for is the table service which allows you to compute many-to-many queries and returns the duration between each pair. (also allows for asymmetric tables if you need that)

Other then that, keep in mind OSRM is already multi-threaded. If you send multiple HTTP requests at the same time it will use all available cores on your system to compute those queries.

If the HTTP layer is too much overhead, you could try our node bindings or write your own C++ code and link against libosrm.

Body:
I would like to push multiple requests to the OSRM backend (see https://github.com/Project-OSRM/osrm-backend) at once. Currently, for me to get the distance between two points, I do something like this:

curl "http://127.0.0.1:5000/route/v1/driving/10,50;13,52?overview=false"

However, I need to do this for more than 2m rows... So I would like to know if I can send the docker image multiple requests at the same time?

Or if anyone has a better idea, it would be great!


问:
How to count P & A in SQL Server
Please help someone!

I have a table View_SMS_Mark_Attendance which contains columns like

```<code>[Class] | [S_Adm_No] |  [Alias], | [DateTime]
</code>```

My question is how can I count P and A separately like.

```<code>Class | S_Adm_NO | Month | 1 | 2 | 3 | 4 | 5 | 6 | 7 | Total_P  | Total_A
Nur-A | 1101     | April | A | P | P | P | P | A | A |  4       | 3
Nur-A | 1102     | April | P | P | P | P | P | A | A |  5       | 2
Nur-A | 1103     | April | A | P | A | P | P | A | A |  3       | 4
</code>```

To get my result I am using a SQL query like

```<code>SELECT *
FROM
    (SELECT
         [Class], [S_Adm_No], [Alias],
         DATENAME(M, [DateTime])as [Month],
         DAY([DateTime]) as [DayValue]
     FROM
         [View_SMS_Mark_Attendance]) AS Composite
     PIVOT
         (MAX([Alias])
            FOR [DayValue] IN ([1], [2], [3], [4],[5], [6], [7], [8], [9], [10], [11], [12], [13],[14],[15],[16], [17], [18], [19],
                               [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31])) AS pt
LEFT JOIN
    (SELECT
         [Class], [S_Adm_No],
         SUM(CASE WHEN [Alias] = 'P' THEN 1 ELSE 0 END) AS SumOfP,
         SUM(CASE WHEN [Alias] = 'A' THEN 1 ELSE 0 END) AS SumOfA
     FROM
         [View_SMS_Mark_Attendance]
     GROUP BY
         [Class], [S_Adm_No]) AS at ON pt.[Class] = at.[Class]
                                    AND pt.[S_Adm_No] = at.[S_Adm_No]
</code>```

I want to get result only particular month and class by using 'WHERE month & class'

Please help someone!

答:
Just use conditional aggregation:</p>

```<code>SELECT [Class], [S_Adm_No], [Alias], DATENAME(MONTH, [DateTime]) as [Month],
       MAX(CASE WHEN DAY([DateTime]) = 1 THEN Alias END) as [1],
       MAX(CASE WHEN DAY([DateTime]) = 2 THEN Alias END) as [2],
       . . .,
       MAX(CASE WHEN DayValue = 31 THEN Alias END) as [31],
       SUM(CASE WHEN Alias = 'P' THEN 1 ELSE 0 END) as NumPs,
       SUM(CASE WHEN Alias = 'P' THEN 1 ELSE 0 END) as NumAs,
FROM View_SMS_Mark_Attendance
GROUP BY [Class], [S_Adm_No], [Alias], DATENAME(MONTH, [DateTime]);
</code>```

Title: How to count P & A in SQL Server

Body:
Please help someone!

I have a table View_SMS_Mark_Attendance which contains columns like

[Class] | [S_Adm_No] |  [Alias], | [DateTime]

My question is how can I count P and A separately like.

Class | S_Adm_NO | Month | 1 | 2 | 3 | 4 | 5 | 6 | 7 | Total_P  | Total_A
Nur-A | 1101     | April | A | P | P | P | P | A | A |  4       | 3
Nur-A | 1102     | April | P | P | P | P | P | A | A |  5       | 2
Nur-A | 1103     | April | A | P | A | P | P | A | A |  3       | 4

To get my result I am using a SQL query like

SELECT *
FROM
    (SELECT
         [Class], [S_Adm_No], [Alias],
         DATENAME(M, [DateTime])as [Month],
         DAY([DateTime]) as [DayValue]
     FROM
         [View_SMS_Mark_Attendance]) AS Composite
     PIVOT
         (MAX([Alias])
            FOR [DayValue] IN ([1], [2], [3], [4],[5], [6], [7], [8], [9], [10], [11], [12], [13],[14],[15],[16], [17], [18], [19],
                               [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31])) AS pt
LEFT JOIN
    (SELECT
         [Class], [S_Adm_No],
         SUM(CASE WHEN [Alias] = 'P' THEN 1 ELSE 0 END) AS SumOfP,
         SUM(CASE WHEN [Alias] = 'A' THEN 1 ELSE 0 END) AS SumOfA
     FROM
         [View_SMS_Mark_Attendance]
     GROUP BY
         [Class], [S_Adm_No]) AS at ON pt.[Class] = at.[Class]
                                    AND pt.[S_Adm_No] = at.[S_Adm_No]

I want to get result only particular month and class by using 'WHERE month & class'

Please help someone!

Body:
Just use conditional aggregation:

SELECT [Class], [S_Adm_No], [Alias], DATENAME(MONTH, [DateTime]) as [Month],
       MAX(CASE WHEN DAY([DateTime]) = 1 THEN Alias END) as [1],
       MAX(CASE WHEN DAY([DateTime]) = 2 THEN Alias END) as [2],
       . . .,
       MAX(CASE WHEN DayValue = 31 THEN Alias END) as [31],
       SUM(CASE WHEN Alias = 'P' THEN 1 ELSE 0 END) as NumPs,
       SUM(CASE WHEN Alias = 'P' THEN 1 ELSE 0 END) as NumAs,
FROM View_SMS_Mark_Attendance
GROUP BY [Class], [S_Adm_No], [Alias], DATENAME(MONTH, [DateTime]);


问:
How to redirect Powershell output from a script run by TaskScheduler and override default width of 80 characters
I have a powershell script which is invoked by the task scheduler. The task's definition also redirects the output using >> to a log file. The PowerShell script invokes a C# console program which generates output which is longer than 80 characters in width. However, the resultant output in the log file is wrapping all the output from the C# program to 80- characters. Note that only the output from the C# program is wrapped. All other output from the script (generated by Write-Host) is not wrapped. Also note that this wrapping only occurs when the script is run by the task scheduler.

Here is the script calling chain:

The task definition invokes a .cmd script (RunWidthTest.cmd)

RunWidthTest.cmd:
powershell -File .\RunReports.ps1 >> C:\Log\output.log

RunReports.ps1 (snippet):

Write-Host "======================================================== Running reports for date file for $valueDate"

.\ReportRunner.exe --ValueDate $valueDate | Out-Default

Note that piping the outout to Out-Default is required to avoid another powershell error that occurs due to the fact that an executable's output is attempting to write to the same stream as the powershell script without powershell being aware of it (Write-Host : The OS handle's position is not what FileStream expected. Do not use a handle simultaneously
in one FileStream and in Win32 code or another FileStream. This may cause data loss.)

So in this case here, the string output by the Write-Host line is not wrapped, however, any output generated by ReportRunner.exe is wrapped to 80 characters and it only occurs when run with the task scheduler! The same behaviour occurs if you change the point at which the redirection occurs, ie if you redirect in the definition the task (the task's command line instead of inside the script)

Any clues as to why this would occur and how to override this width restriction.

Thanks.

答:
Did you try </p>

```<code>| Out-File C:\Log\output.log -width 120 # or whatever size  you need
</code>```

Body:
Did you try

| Out-File C:\Log\output.log -width 120 # or whatever size  you need


问:
how to get value from other script? (in html)
I want to get value from other script.

(about socket.io) A script -> (about highchart) B script

this is A script

```<code><script>
var socket = io();

socket.on('currTemp', function(data){
    document.getElementById("temp").innerHTML = "Temperature : " + data;
                   ***// I WANT 'data'.***
}); </script>
</code>```

and this is B script

```<code><script type="text/javascript">

....
code
....

setInterval(function () {
var point,
    newVal,
    inc;

if (chartRpm) {
    point = chartRpm.series[0].points[0];
    inc = ------> ***I want 'inc = data '***
    newVal = inc;

    if (newVal < 0 || newVal > 1200) {
        newVal = point.y - inc;
    }

    point.update(newVal);
}}, 2000); </script>
</code>```

this code is in same file. how to do that ?

答:
You options are:

1- Global Variable: By Assigning window.data = data in A script and use it in B script by using inc = window.data

2- Use global events where A script fires an event with data attached to it and it will caught by B script.

3- Use any JS state management lib to share data between "components"

Body:
I want to get value from other script.

(about socket.io) A script -> (about highchart) B script

this is A script

and this is B script

this code is in same file. how to do that ?


问:
Loop ggplot for different variables in dataframe
I want to loop ggplot and obtain a graph for each variable code is below. I get an error in aes

```<code>df <- data.frame(ID = c("a", "b"), A = rnorm(2), B = runif(2), C = rlnorm(2))
for(i in df[,2:ncol(df)]){
 plt<-ggplot(data=df, aes(x=df$ID, y = df[,2:ncol(df)]$i))+
    geom_bar()
  print(plt)
}
</code>```

What is the problem?

I know I could use facet_grid.

```<code>ggplot(df_melt, aes(x=ID,y=value)) + geom_bar(stat="identity") + facet_grid(~variable)
</code>```

答:
```<code>df <- data.frame(ID = c("a", "b"), A = rnorm(2), B = runif(2), C = rlnorm(2))

for (colname in names(df)[-1]) {
  plt <- ggplot(data = df, aes_string("ID", y = colname)) +
    geom_bar(stat = "identity")
  print(plt)
}
</code>```

Body:
I want to loop ggplot and obtain a graph for each variable code is below. I get an error in aes

df <- data.frame(ID = c("a", "b"), A = rnorm(2), B = runif(2), C = rlnorm(2))
for(i in df[,2:ncol(df)]){
 plt<-ggplot(data=df, aes(x=df$ID, y = df[,2:ncol(df)]$i))+
    geom_bar()
  print(plt)
}

What is the problem?

I know I could use facet_grid.

ggplot(df_melt, aes(x=ID,y=value)) + geom_bar(stat="identity") + facet_grid(~variable)


问:
How to rotate two objects thus they would point to each other in the 2D plane?

On the initial image, you can see two triangles pointing upwards. By how much in degrees I have to rotate them thus they would point to each other? How can I calculate angles?

Calculating dot product gives only the angle difference between the triangles, but it is not the right value to rotate.

答:
You are taking the dot products of the wrong vectors. You should dot the direction of each object with the displacement vector to the other object. This will give the required angle to rotate through.

But this alone is not enough - how would you know which direction to rotate in, clockwise or anti-clockwise? You can obtain this using the cross-product:

A x B = A.x * B.y - B.x * A.y

If this quantity is negative, then A is anti-clockwise relative to B, and vice versa. Therefore if cross(direction, displacement) is negative, then rotate clockwise by the calculated angle θ, and vice versa.


问:
Inserting element into array using c#
```<code>        int[] arr = {4,3,6,7,9,12};

        int n = arr.Length;
        n = n + 1;

        for (int i =n;i>2;i--) {
        arr[i-1] = arr[i-2];

        }

        arr[0] = 4;
</code>```

The above code returning

indexOutOfRangeexception.

答:
```<code>int n = arr.Length //n=6
n=n+1 //n=7
for(int i=n;i>2;i--){ //i=7
  arr[i-1] //arr[6]
</code>```

While clearly the last element is arr[5].
In C# arrays are of constant length, you can't change them, the only way to do that is to create a new array, or a better solution would be using List<>

Title: Inserting element into array using c#

Body:
        int[] arr = {4,3,6,7,9,12};

        int n = arr.Length;
        n = n + 1;

        for (int i =n;i>2;i--) {
        arr[i-1] = arr[i-2];

        }

        arr[0] = 4;

The above code returning

indexOutOfRangeexception.

Body:
int n = arr.Length //n=6
n=n+1 //n=7
for(int i=n;i>2;i--){ //i=7
  arr[i-1] //arr[6]

While clearly the last element is arr[5].
In C# arrays are of constant length, you can't change them, the only way to do that is to create a new array, or a better solution would be using List<>


问:
How do I change a JSON array to JSON elements with Jackson
Can Jackson has a simpler way to deserialize a java object with a list into elements using Annotation?

Instead of this

```<code>{
[{id: 1, name: 'a'},{id: 2, name: 'b'}]
}
</code>```

I want this

```<code>{
   "1": {name: 'a'},
   "2": {name: 'b'}
}
</code>```

答:
I used a custom serializer to do it</p>

```<code> public static class CustomListSerializer extends StdSerializer<List> {

    public CustomListSerializer() {
        this(null);
    }

    public CustomListSerializer(Class<List> t) {
        super(t);
    }

    @Override
    public void serialize(
            List list,
            JsonGenerator generator,
            SerializerProvider provider)
            throws IOException, JsonProcessingException {
        generator.writeStartObject();
        int index = 1;
        for (Object item : list) {
            generator.writeObjectField(String.valueOf(index), item);
            index++;
        }
        generator.writeEndObject();
    }
}
</code>```

Body:
Can Jackson has a simpler way to deserialize a java object with a list into elements using Annotation?

Instead of this

{
[{id: 1, name: 'a'},{id: 2, name: 'b'}]
}

I want this

{
   "1": {name: 'a'},
   "2": {name: 'b'}
}

Body:
I used a custom serializer to do it

 public static class CustomListSerializer extends StdSerializer<List> {

    public CustomListSerializer() {
        this(null);
    }

    public CustomListSerializer(Class<List> t) {
        super(t);
    }

    @Override
    public void serialize(
            List list,
            JsonGenerator generator,
            SerializerProvider provider)
            throws IOException, JsonProcessingException {
        generator.writeStartObject();
        int index = 1;
        for (Object item : list) {
            generator.writeObjectField(String.valueOf(index), item);
            index++;
        }
        generator.writeEndObject();
    }
}


答:
Of course it will because of these</p>

```<code>n = n + 1; // n = 7
for (int i =n;i>2;i--) {  //Assining 7 to i
arr[i-1] = arr[i-2]; // trying to access arr[6] which is not valid
</code>```

Title: Inserting element into array using c#

Body:
Of course it will because of these

n = n + 1; // n = 7
for (int i =n;i>2;i--) {  //Assining 7 to i
arr[i-1] = arr[i-2]; // trying to access arr[6] which is not valid


问:
400 ERROR: Invalid URI when uploading new PyPI package (twine)
I followed the official documentation for uploading packages to PyPI, as well as the information provided in PyPI readme, but I get a HTTP 400 error each time:

```<code>$ twine upload dist/*
Uploading distributions to https://upload.pypi.org/legacy/
Enter your username: bradaallen
Enter your password:
Uploading brad_nlp_helpers-0.1.1-py3-none-any.whl
HTTPError: 400 Client Error: home_page: Invalid URI for url:
https://upload.pypi.org/legacy/
</code>```

I am using a ~/.pypirc

```<code>[distutils]
index-servers =
  pypi
  pypitest

[pypi]
username=bradaallen
password=[password]

[pypitest]
username=bradaallen
password=[password]
</code>```

For packages, I am using twine version 1.9.1 (pkginfo: 1.4.1, requests: 2.12.4, setuptools: 27.2.0, requests-toolbelt: 0.8.0, tqdm: 4.14.0)

When I use python setup.py sdist bdist_wheel upload I get the same issue:

```<code>Submitting dist\brad_nlp_helpers-0.1.1.tar.gz to
https://upload.pypi.org/legacy/ Upload failed (400): home_page: Invalid URI
error: Upload failed (400): home_page: Invalid URI
</code>```

I have not specified the repository, as that is recommendation that is given by the API when uploading. I am seeing a 404 error at the link that PyPI recommends and am not seeing an alternative site I should use!

This is my first package, and I am not seeing this error elsewhere on the internet. Any thoughts re: what's going on?

答:
Just a few minutes ago tried to upload a package and got this problem. :-) To fix: upgrade pip, setuptools and twine to the very latest versions:

```<code>pip install -U pip setuptools twine
</code>```

Remove or comment out repository from ~/.pypirc:

```<code>[distutils]
index-servers =
    pypi

[pypi]
#repository:
username: …
</code>```

twine upload now works!

Body:
I followed the official documentation for uploading packages to PyPI, as well as the information provided in PyPI readme, but I get a HTTP 400 error each time:

$ twine upload dist/*
Uploading distributions to https://upload.pypi.org/legacy/
Enter your username: bradaallen
Enter your password:
Uploading brad_nlp_helpers-0.1.1-py3-none-any.whl
HTTPError: 400 Client Error: home_page: Invalid URI for url:
https://upload.pypi.org/legacy/

I am using a ~/.pypirc

[distutils]
index-servers =
  pypi
  pypitest

[pypi]
username=bradaallen
password=[password]

[pypitest]
username=bradaallen
password=[password]

For packages, I am using twine version 1.9.1 (pkginfo: 1.4.1, requests: 2.12.4, setuptools: 27.2.0, requests-toolbelt: 0.8.0, tqdm: 4.14.0)

When I use python setup.py sdist bdist_wheel upload I get the same issue:

Submitting dist\brad_nlp_helpers-0.1.1.tar.gz to
https://upload.pypi.org/legacy/ Upload failed (400): home_page: Invalid URI
error: Upload failed (400): home_page: Invalid URI

I have not specified the repository, as that is recommendation that is given by the API when uploading. I am seeing a 404 error at the link that PyPI recommends and am not seeing an alternative site I should use!

This is my first package, and I am not seeing this error elsewhere on the internet. Any thoughts re: what's going on?

Body:
Just a few minutes ago tried to upload a package and got this problem. :-) To fix: upgrade pip, setuptools and twine to the very latest versions:

pip install -U pip setuptools twine

Remove or comment out repository from ~/.pypirc:

[distutils]
index-servers =
    pypi

[pypi]
#repository:
username: …

twine upload now works!


问:
Best way for Bootstrap customization
After going through many articles in the web, we've concluded that there are some different ways to custom twitter bootstrap:

Using the http://getbootstrap.com/customize/ site , to predefine settings , before downloading bootstrap

Modifying bootstrap less files after downloading bootstrap to our app.

Add our own custom.css file which will override the bootstrap css files.

Our question is what's the difference between them, In which case is each of them useful?

Thank you!

答:
The only answer I can offer that isn't purely opinion-based would be minimizing and maximizing your performance overhead. By pre-configuring your Bootstrap CSS to your specific needs you omit the need to write additional classes or have additional CSS that overrides existing Bootstrap specifications.

That plays out, ultimately, to fewer HTTP requests.  It also reduces the chance that you'll have inconsistent CSS (ie. an override that works on one component, but not another).

...

On the flip side; if you keep with the out-of-the-box Bootstrap you can easily link to it via CDN, which increases the likelihood that your user will already have a cache of the asset on hand.

And at that point we really delve into opinion-based, which isn't really suitable for SO.

Title: Best way for Bootstrap customization


问:
How to convert timestamp locally according to our location
```<code>startTime := time.Unix(logUserDetail[k].LogTime, 0)
startTimeOfLog := startTime.String()[11:16]
</code>```

I have time in timestamp format and it is in UTC time zone. I want to convert this time to the local timezone according to our location.

logUserDetail[k].LogTime is in timestamp(1499335473)

答: You can use (t Time) In() (Golang documentation) to convert startTime to use your local timezone.

Body:
startTime := time.Unix(logUserDetail[k].LogTime, 0)
startTimeOfLog := startTime.String()[11:16]

I have time in timestamp format and it is in UTC time zone. I want to convert this time to the local timezone according to our location.

logUserDetail[k].LogTime is in timestamp(1499335473)


问:
How to write Union All query in Query DSL
Need to implement sql query like:

```<code>SELECT A.class, A.section
FROM
STUDENT A
INNER JOIN DEPARTMENT on A.student_id = B.id
WHERE DEPT_NBR is not null
UNION ALL
SELECT A.class, A.section
FROM
TEACHER A
INNER JOIN DEPARTMENT on A.teacher_id = B.id
WHERE DEPT_NBR is not null
</code>```

How can I write such statement with QueryDSL ? ( I am not using any JPA). Any help/hint is much appreciated!

答:
There are many examples that can help you.

```<code>public void union_multiple_columns() throws SQLException {
        SubQueryExpression<Tuple> sq1 = query().from(employee).select(employee.firstname, employee.lastname);
        SubQueryExpression<Tuple> sq2 = query().from(employee).select(employee.lastname, employee.firstname);
        List<Tuple> list = query().union(sq1, sq2).fetch();
        assertFalse(list.isEmpty());
        for (Tuple row : list) {
            assertNotNull(row.get(0, Object.class));
            assertNotNull(row.get(1, Object.class));
        }
    }
</code>```

This example was taken from the project itself:
https://github.com/querydsl/querydsl/blob/8f96f416270d0353f90a6551547906f3c217833a/querydsl-sql/src/test/java/com/querydsl/sql/UnionBase.java#L73

Body:
Need to implement sql query like:

SELECT A.class, A.section
FROM
STUDENT A
INNER JOIN DEPARTMENT on A.student_id = B.id
WHERE DEPT_NBR is not null
UNION ALL
SELECT A.class, A.section
FROM
TEACHER A
INNER JOIN DEPARTMENT on A.teacher_id = B.id
WHERE DEPT_NBR is not null

How can I write such statement with QueryDSL ? ( I am not using any JPA). Any help/hint is much appreciated!

Body:
There are many examples that can help you.

public void union_multiple_columns() throws SQLException {
        SubQueryExpression<Tuple> sq1 = query().from(employee).select(employee.firstname, employee.lastname);
        SubQueryExpression<Tuple> sq2 = query().from(employee).select(employee.lastname, employee.firstname);
        List<Tuple> list = query().union(sq1, sq2).fetch();
        assertFalse(list.isEmpty());
        for (Tuple row : list) {
            assertNotNull(row.get(0, Object.class));
            assertNotNull(row.get(1, Object.class));
        }
    }

This example was taken from the project itself:
https://github.com/querydsl/querydsl/blob/8f96f416270d0353f90a6551547906f3c217833a/querydsl-sql/src/test/java/com/querydsl/sql/UnionBase.java#L73