问:
Fluid Content next to fixed sidebar with variable width
I'm trying to implement a switchable sidebar (as in toggle between short and long form sidebar) using bootstrap, a bunch of examples and other works online.

The sidebar changes width when toggled and I want the content to appear next to it despite it being "long" or "short".

I am using a section per each page and would like each section to appear full width on screen (like so)

$(document).ready(function() {
  $("#sidebarCollapse").click(function() {
    $("#sidebar").toggleClass("active");
    $(this).toggleClass('active');
  });
});
$("#aboutbutton").click(function() {
  $('html, body').animate({
    scrollTop: $("#aboutDiv").offset().top
  }, 2000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'Poppins', sans-serif;
  background: #fafafa;
}

p {
  font-family: 'Poppins', sans-serif;
  font-size: 0.1em;
  font-weight: 300;
  line-height: 1.7em;
  color: #3498db;
}

a,
a:hover,
a:focus {
  color: inherit!important;
  text-decoration: none!important;
  transition: all 0.3s;
}

.wrapper {
  display: flex;
}

#sidebar {
  min-width: 250px;
  max-width: 250px;
  background: #2980b9;
  color: #ecf0f1;
  transition: all 0.3s;
  height: 100%;
  min-height: 100vh;
  position: fixed;
}

#sidebar.active {
  min-width: 80px;
  max-width: 80px;
  text-align: center;
}

#sidebar ul.components {
  padding: 20px 0;
}

#sidebar ul p {
  color: #fff;
  padding: 10px;
}

#sidebar ul li a {
  padding: 10px;
  font-size: 1.6em;
  display: block;
  text-align: left;
}

#sidebar ul li a:hover {
  color: #ecf0f1;
  background: #3498db;
}

#sidebar .active ul li a {
  padding: 20px 10px;
  text-align: center;
  font-size: 0.85em;
}

#sidebar .active i {
  font-size: 1em;
}

#sidebar .active ul li a i {
  margin-right: 0;
  display: block;
  font-size: 1.8em;
  margin-bottom: 5px;
}

#sidebar ul li.active>a,
a[aria-expanded="true"] {
  color: #ecf0f1;
  background: #3498db;
}

ul ul a {
  font-size: 0.9em !important;
  padding-left: 30px !important;
  background: #ecf0f1;
}

#sidebarCollapse {
  width: 100%;
  height: 80%;
  background: #2980b9;
  padding: 20px 0;
  font-size: 1.6em;
  display: block;
  border: 0;
}

#sidebarCollapse-wrapper {
  padding-top: 5%;
  padding-bottom: 5%;
}

#sidebarCollapse span {
  width: 30%;
  height: 2px;
  margin: 0 auto;
  display: block;
  background: #fff;
  transition: all 0.8s cubic-bezier(0.810, -0.330, 0.345, 1.375);
}

#sidebarCollapse span:first-of-type {
  /* rotate first one */
  transform: rotate(45deg) translate(2px, 2px);
}

#sidebarCollapse span:nth-of-type(2) {
  /* second one is not visible */
  opacity: 0;
}

#sidebarCollapse span:last-of-type {
  /* rotate third one */
  transform: rotate(-45deg) translate(1px, -1px);
}

#sidebarCollapse.active span {
  /* no rotation */
  transform: none;
  /* all bars are visible */
  opacity: 1;
  margin: 5px auto;
}

section {
  min-height: 100vh;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
}</code>```

<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
<link href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.4.3/css/mdb.min.css" rel="stylesheet" />

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>José Gomes - Website</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link rel="stylesheet" href="css/mdb.min.css">

  <link rel="stylesheet" href="css/jquery.mCustomScrollbar.css">

  <link rel="stylesheet" href="css/custom.css">

  <link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css">

        <button type="button" id="sidebarCollapse" class="navbar-btn waves-effect waves-light">

      </button>

  Home

 Page1

   Page2

   Page3

        Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST -

        Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST -

        Section 3 TEST - Section 3 TEST - Section 3 TEST - Section 3 TEST

```

Here's the jsfiddle of the above code

I've tried a content wrapper and setting a margin for the content class but it still pushes the content down below the sidebar or inside it.

答:
Something like this ?

$(document).ready(function() {
  $("#sidebarCollapse").click(function() {
    $("#sidebar").toggleClass("active");
    $(this).toggleClass('active');
  });
});
$("#aboutbutton").click(function() {
  $('html, body').animate({
    scrollTop: $("#aboutDiv").offset().top
  }, 2000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'Poppins', sans-serif;
  background: #fafafa;
}

p {
  font-family: 'Poppins', sans-serif;
  font-size: 0.1em;
  font-weight: 300;
  line-height: 1.7em;
  color: #3498db;
}

a,
a:hover,
a:focus {
  color: inherit!important;
  text-decoration: none!important;
  transition: all 0.3s;
}

.wrapper {
  display: flex;
}

#sidebar {
  min-width: 250px;
  max-width: 250px;
  background: #2980b9;
  color: #ecf0f1;
  transition: all 0.3s;
  height: 100%;
  min-height: 100vh;
  position: fixed;
}

#sidebar.active {
  min-width: 80px;
  max-width: 80px;
  text-align: center;
}

#sidebar ul.components {
  padding: 20px 0;
}

#sidebar ul p {
  color: #fff;
  padding: 10px;
}

#sidebar ul li a {
  padding: 10px;
  font-size: 1.6em;
  display: block;
  text-align: left;
}

#sidebar ul li a:hover {
  color: #ecf0f1;
  background: #3498db;
}

#sidebar .active ul li a {
  padding: 20px 10px;
  text-align: center;
  font-size: 0.85em;
}

#sidebar .active i {
  font-size: 1em;
}

#sidebar .active ul li a i {
  margin-right: 0;
  display: block;
  font-size: 1.8em;
  margin-bottom: 5px;
}

#sidebar ul li.active>a,
a[aria-expanded="true"] {
  color: #ecf0f1;
  background: #3498db;
}

ul ul a {
  font-size: 0.9em !important;
  padding-left: 30px !important;
  background: #ecf0f1;
}

#sidebarCollapse {
  width: 100%;
  height: 80%;
  background: #2980b9;
  padding: 20px 0;
  font-size: 1.6em;
  display: block;
  border: 0;
}

#sidebarCollapse-wrapper {
  padding-top: 5%;
  padding-bottom: 5%;
}

#sidebarCollapse span {
  width: 30%;
  height: 2px;
  margin: 0 auto;
  display: block;
  background: #fff;
  transition: all 0.8s cubic-bezier(0.810, -0.330, 0.345, 1.375);
}

#sidebarCollapse span:first-of-type {
  /* rotate first one */
  transform: rotate(45deg) translate(2px, 2px);
}

#sidebarCollapse span:nth-of-type(2) {
  /* second one is not visible */
  opacity: 0;
}

#sidebarCollapse span:last-of-type {
  /* rotate third one */
  transform: rotate(-45deg) translate(1px, -1px);
}

#sidebarCollapse.active span {
  /* no rotation */
  transform: none;
  /* all bars are visible */
  opacity: 1;
  margin: 5px auto;
}

.sidebar-nav.active + div#content{
margin-left:80px;
}
.sidebar-nav:not(.active) + div#content{
margin-left:250px;
}

section {
  min-height: 100vh;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
}</code>```

<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
<link href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.4.3/css/mdb.min.css" rel="stylesheet" />

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>José Gomes - Website</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link rel="stylesheet" href="css/mdb.min.css">

  <link rel="stylesheet" href="css/jquery.mCustomScrollbar.css">

  <link rel="stylesheet" href="css/custom.css">

  <link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css">

        <button type="button" id="sidebarCollapse" class="navbar-btn waves-effect waves-light">

      </button>

  Home

 Page1

   Page2

   Page3

        Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST -

        Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST -

        Section 3 TEST - Section 3 TEST - Section 3 TEST - Section 3 TEST

```

Body:
I'm trying to implement a switchable sidebar (as in toggle between short and long form sidebar) using bootstrap, a bunch of examples and other works online.

The sidebar changes width when toggled and I want the content to appear next to it despite it being "long" or "short".

I am using a section per each page and would like each section to appear full width on screen (like so)

$(document).ready(function() {
  $("#sidebarCollapse").click(function() {
    $("#sidebar").toggleClass("active");
    $(this).toggleClass('active');
  });
});
$("#aboutbutton").click(function() {
  $('html, body').animate({
    scrollTop: $("#aboutDiv").offset().top
  }, 2000);
});

body {
  font-family: 'Poppins', sans-serif;
  background: #fafafa;
}

p {
  font-family: 'Poppins', sans-serif;
  font-size: 0.1em;
  font-weight: 300;
  line-height: 1.7em;
  color: #3498db;
}

a,
a:hover,
a:focus {
  color: inherit!important;
  text-decoration: none!important;
  transition: all 0.3s;
}

.wrapper {
  display: flex;
}

#sidebar {
  min-width: 250px;
  max-width: 250px;
  background: #2980b9;
  color: #ecf0f1;
  transition: all 0.3s;
  height: 100%;
  min-height: 100vh;
  position: fixed;
}

#sidebar.active {
  min-width: 80px;
  max-width: 80px;
  text-align: center;
}

#sidebar ul.components {
  padding: 20px 0;
}

#sidebar ul p {
  color: #fff;
  padding: 10px;
}

#sidebar ul li a {
  padding: 10px;
  font-size: 1.6em;
  display: block;
  text-align: left;
}

#sidebar ul li a:hover {
  color: #ecf0f1;
  background: #3498db;
}

#sidebar .active ul li a {
  padding: 20px 10px;
  text-align: center;
  font-size: 0.85em;
}

#sidebar .active i {
  font-size: 1em;
}

#sidebar .active ul li a i {
  margin-right: 0;
  display: block;
  font-size: 1.8em;
  margin-bottom: 5px;
}

#sidebar ul li.active>a,
a[aria-expanded="true"] {
  color: #ecf0f1;
  background: #3498db;
}

ul ul a {
  font-size: 0.9em !important;
  padding-left: 30px !important;
  background: #ecf0f1;
}

#sidebarCollapse {
  width: 100%;
  height: 80%;
  background: #2980b9;
  padding: 20px 0;
  font-size: 1.6em;
  display: block;
  border: 0;
}

#sidebarCollapse-wrapper {
  padding-top: 5%;
  padding-bottom: 5%;
}

#sidebarCollapse span {
  width: 30%;
  height: 2px;
  margin: 0 auto;
  display: block;
  background: #fff;
  transition: all 0.8s cubic-bezier(0.810, -0.330, 0.345, 1.375);
}

#sidebarCollapse span:first-of-type {
  /* rotate first one */
  transform: rotate(45deg) translate(2px, 2px);
}

#sidebarCollapse span:nth-of-type(2) {
  /* second one is not visible */
  opacity: 0;
}

#sidebarCollapse span:last-of-type {
  /* rotate third one */
  transform: rotate(-45deg) translate(1px, -1px);
}

#sidebarCollapse.active span {
  /* no rotation */
  transform: none;
  /* all bars are visible */
  opacity: 1;
  margin: 5px auto;
}

section {
  min-height: 100vh;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
}

<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
<link href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.4.3/css/mdb.min.css" rel="stylesheet" />

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>José Gomes - Website</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link rel="stylesheet" href="css/mdb.min.css">

  <link rel="stylesheet" href="css/jquery.mCustomScrollbar.css">

  <link rel="stylesheet" href="css/custom.css">

  <link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css">

        <button type="button" id="sidebarCollapse" class="navbar-btn waves-effect waves-light">

      </button>

  Home

 Page1

   Page2

   Page3

        Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST -

        Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST -

        Section 3 TEST - Section 3 TEST - Section 3 TEST - Section 3 TEST

Here's the jsfiddle of the above code

I've tried a content wrapper and setting a margin for the content class but it still pushes the content down below the sidebar or inside it.

Body:
Something like this ?

$(document).ready(function() {
  $("#sidebarCollapse").click(function() {
    $("#sidebar").toggleClass("active");
    $(this).toggleClass('active');
  });
});
$("#aboutbutton").click(function() {
  $('html, body').animate({
    scrollTop: $("#aboutDiv").offset().top
  }, 2000);
});

body {
  font-family: 'Poppins', sans-serif;
  background: #fafafa;
}

p {
  font-family: 'Poppins', sans-serif;
  font-size: 0.1em;
  font-weight: 300;
  line-height: 1.7em;
  color: #3498db;
}

a,
a:hover,
a:focus {
  color: inherit!important;
  text-decoration: none!important;
  transition: all 0.3s;
}

.wrapper {
  display: flex;
}

#sidebar {
  min-width: 250px;
  max-width: 250px;
  background: #2980b9;
  color: #ecf0f1;
  transition: all 0.3s;
  height: 100%;
  min-height: 100vh;
  position: fixed;
}

#sidebar.active {
  min-width: 80px;
  max-width: 80px;
  text-align: center;
}

#sidebar ul.components {
  padding: 20px 0;
}

#sidebar ul p {
  color: #fff;
  padding: 10px;
}

#sidebar ul li a {
  padding: 10px;
  font-size: 1.6em;
  display: block;
  text-align: left;
}

#sidebar ul li a:hover {
  color: #ecf0f1;
  background: #3498db;
}

#sidebar .active ul li a {
  padding: 20px 10px;
  text-align: center;
  font-size: 0.85em;
}

#sidebar .active i {
  font-size: 1em;
}

#sidebar .active ul li a i {
  margin-right: 0;
  display: block;
  font-size: 1.8em;
  margin-bottom: 5px;
}

#sidebar ul li.active>a,
a[aria-expanded="true"] {
  color: #ecf0f1;
  background: #3498db;
}

ul ul a {
  font-size: 0.9em !important;
  padding-left: 30px !important;
  background: #ecf0f1;
}

#sidebarCollapse {
  width: 100%;
  height: 80%;
  background: #2980b9;
  padding: 20px 0;
  font-size: 1.6em;
  display: block;
  border: 0;
}

#sidebarCollapse-wrapper {
  padding-top: 5%;
  padding-bottom: 5%;
}

#sidebarCollapse span {
  width: 30%;
  height: 2px;
  margin: 0 auto;
  display: block;
  background: #fff;
  transition: all 0.8s cubic-bezier(0.810, -0.330, 0.345, 1.375);
}

#sidebarCollapse span:first-of-type {
  /* rotate first one */
  transform: rotate(45deg) translate(2px, 2px);
}

#sidebarCollapse span:nth-of-type(2) {
  /* second one is not visible */
  opacity: 0;
}

#sidebarCollapse span:last-of-type {
  /* rotate third one */
  transform: rotate(-45deg) translate(1px, -1px);
}

#sidebarCollapse.active span {
  /* no rotation */
  transform: none;
  /* all bars are visible */
  opacity: 1;
  margin: 5px auto;
}

.sidebar-nav.active + div#content{
margin-left:80px;
}
.sidebar-nav:not(.active) + div#content{
margin-left:250px;
}

section {
  min-height: 100vh;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
}

<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
<link href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.4.3/css/mdb.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.1/js/tether.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.4.3/js/mdb.min.js"></script>

<!DOCTYPE html>
<html lang="en">

<head>

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>José Gomes - Website</title>
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <!-- Material Design Bootstrap -->
  <link rel="stylesheet" href="css/mdb.min.css">
  <!-- Scrollbar Custom CSS -->
  <link rel="stylesheet" href="css/jquery.mCustomScrollbar.css">
  <!-- Our Custom CSS -->
  <link rel="stylesheet" href="css/custom.css">

  <!-- in your header -->
  <link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css">
</head>

<body>

  <!-- Content will go here -->
    <!-- Sidebar -->
    <nav class="sidebar-nav" data-spy="affix" id="sidebar">
      <!-- Sidebar Header -->
      <div id="sidebarCollapse-wrapper">
        <button type="button" id="sidebarCollapse" class="navbar-btn waves-effect waves-light">
        <span></span>
        <span></span>
        <span></span>
      </button>
      </div>
      <!-- Sidebar Links -->
      <ul class="list-unstyled components">
        <li class="active waves-effect waves-light" id="aboutbutton"><a href="#"><i class="fa fa-user-circle" aria-hidden="true"></i>  Home</a></li>
        <li class="waves-effect waves-light"><a href="#"><i class="fa fa-briefcase" aria-hidden="true"></i> Page1
          </a></li>
        <li class="waves-effect waves-light"><a href="#"><i class="fa fa-cogs" aria-hidden="true"></i>   Page2</a></li>
        <li class="waves-effect waves-light"><a href="#"><i class="fa fa-home" aria-hidden="true"></i>   Page3</a></li>
      </ul>
    </nav>

  <!-- Page Content -->
  <div id="content" class="p-0">

    <div class="d-flex flex-column">
      <section class="p-3 p-lg-5 content-page" id="Section1">
        Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST - Section 1 TEST -
      </section>
      <section class="p-3 content-page">
        Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST - Section 2 TEST -
      </section>
      <section class="p-3 content-page">
        Section 3 TEST - Section 3 TEST - Section 3 TEST - Section 3 TEST</section>
    </div>

  </div>

  </div>


来源: stackexchange

问:
How rabbitmq internally stores message and how to retrieve back in original form?
I am trying to publish rabbitmq message with following python script--

```<code>import findspark
findspark.init("/home/spark/spark-2.2.0")
from pyspark.sql import SparkSession
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue_durable', durable=True)
message="Hello_Hbase!"
channel.basic_publish(exchange='',routing_key='queue1',body=message)
print(" [x] Sent %r" % message)
connection.close()
</code>```

next, this is the subscriber script. In this script I want to retrieve the message from routing_queue='queue1' and want to store that message somewhere else..

```<code>import findspark
findspark.init("/home/spark/spark-2.2.0")
from pyspark.sql import SparkSession

import time
import pika
import happybase
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='queue1', durable=True)
print(' [*] Waiting for messages. To exit press CTRL+C')

connection = happybase.Connection(host='localhost', port=9090)
table = connection.table('blogpost')
print(connection.tables())

    def callback(ch, method, body):
        print(" [x] Received %r" % body)
        time.sleep(body.count('.'))
        print(" [x] Done")
        ch.basic_ack(delivery_tag=method.delivery_tag)
        #return(body)

channel.basic_qos(prefetch_count=1)
body=channel.basic_consume( callback,queue='queue1')
print(body) ## here it is giving some encrypted msg, how to retrieve in original form
# here in the body,I am getting this - ctag1.587a9ab83301436195fc3f653c2f6db0
table.put('1', {'post:status': body})
print("hbase insertion done")
#channel.start_consuming()
</code>```

Can someone let me know how to retrieve msg from rabbitmq queue in its original form?

答:
basic_consume doesn't return the body of the message.

That is accessible within the callback function, as the body parameter, which you are already correctly using. You should do your database manipulation there too.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to publish rabbitmq message with following python script--

import findspark
findspark.init("/home/spark/spark-2.2.0")
from pyspark.sql import SparkSession
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue_durable', durable=True)
message="Hello_Hbase!"
channel.basic_publish(exchange='',routing_key='queue1',body=message)
print(" [x] Sent %r" % message)
connection.close()

next, this is the subscriber script. In this script I want to retrieve the message from routing_queue='queue1' and want to store that message somewhere else..

import findspark
findspark.init("/home/spark/spark-2.2.0")
from pyspark.sql import SparkSession

import time
import pika
import happybase
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='queue1', durable=True)
print(' [*] Waiting for messages. To exit press CTRL+C')

connection = happybase.Connection(host='localhost', port=9090)
table = connection.table('blogpost')
print(connection.tables())

    def callback(ch, method, body):
        print(" [x] Received %r" % body)
        time.sleep(body.count('.'))
        print(" [x] Done")
        ch.basic_ack(delivery_tag=method.delivery_tag)
        #return(body)

channel.basic_qos(prefetch_count=1)
body=channel.basic_consume( callback,queue='queue1')
print(body) ## here it is giving some encrypted msg, how to retrieve in original form
# here in the body,I am getting this - ctag1.587a9ab83301436195fc3f653c2f6db0
table.put('1', {'post:status': body})
print("hbase insertion done")
#channel.start_consuming()

Can someone let me know how to retrieve msg from rabbitmq queue in its original form?


问:
Incorrect output in Depth First Search Implementation
Recently, I was looking at a code for Depth First Search in a website (https://brilliant.org/wiki/depth-first-search-dfs/). However their implementation is not completly correct.This is the code they posted

```<code>def depth_first_search(graph):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited
</code>```

As you can see, the logic they applied is correct but they used set operation which changes the output everytime the program runs.

This is my complete program

```<code>graph = {'A': {'B', 'S'}, 'B': {'A'}, 'C': {'S', 'F', 'D', 'E'},
     'D': {'C'}, 'E': {'H', 'C'}, 'F': {'C', 'G'}, 'G': {'S', 'F', 'H'},
     'H': {'G', 'E'}, 'S': {'A', 'G', 'C'}}

def depth_first_search(graph, root):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

print(depth_first_search(graph, 'A'))
</code>```

Below are the outputs I get evertime I run the program

```<code>{'H', 'C', 'B', 'A', 'D', 'S', 'F', 'E', 'G'}
{'D', 'E', 'C', 'H', 'G', 'S', 'A', 'B', 'F'}
{'G', 'F', 'C', 'H', 'E', 'D', 'B', 'S', 'A'} and so on....
</code>```

The reason for using set especially makes sense for the below line of code as we want the stack to store only the vertices that are unexplored.

```<code>stack.extend(graph[vertex] - visited)
</code>```

So performing set difference operation achieves that objective.But it comes at a cost as mentioned above.So I tweaked the code a bit to avoid using set and make do with lists

```<code>graph = {'A': ['B', 'S'], 'B': ['A'], 'C': ['S', 'F', 'D', 'E'],
 'D': ['C'], 'E': ['H', 'C'], 'F': ['C', 'G'], 'G': ['S', 'F', 'H'],
  'H': ['G', 'E'], 'S': ['A', 'G', 'C']}

def depth_first_search(graph, root):
    visited, stack = [], [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.append(vertex)
            neighbours = graph[vertex]
            for neighbour in neighbours:
                # ensures we only add unexplored nodes to the stack
                if neighbour not in visited:
                    stack.append(neighbour)
    return visited

print(depth_first_search(graph, 'A'))
</code>```

But I get a wrong result

```<code>['A', 'S', 'C', 'E', 'H', 'G', 'F', 'D', 'B']
</code>```

The correct result must be

```<code>['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']
</code>```

What am I doing wrong?

答:
It looks like the initial code sample you have isn't intended to produce an topological sort, but simply to list all nodes that can be reached from the root. Probably important to note that it's not incorrect, it's just not supposed to give you an order.

Your code does basically what it says it should, and the output you're getting is as correct as the one you're expecting. As long as you just want a DFS that is.

I think what you're missing is that when you call vertex = stack.pop() you're forgetting that it always returns the last, (i.e. right-most element) and when you call stack.append(neighbour), you're pushing the children onto the stack in order from left to right.

If you want a DFS that specifically goes down the "left-most" branch first then you need to reverse the order of the neighbours/children before you add them to the stack.

EDIT: I don't have enough rep to comment freely yet, but my answer is essentially the same as glibdud's. It seems like the issue you're running into is that you're applying additional restrictions in your head that aren't actually part of a basic DFS.

Body:
Recently, I was looking at a code for Depth First Search in a website (https://brilliant.org/wiki/depth-first-search-dfs/). However their implementation is not completly correct.This is the code they posted

def depth_first_search(graph):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

As you can see, the logic they applied is correct but they used set operation which changes the output everytime the program runs.

This is my complete program

graph = {'A': {'B', 'S'}, 'B': {'A'}, 'C': {'S', 'F', 'D', 'E'},
     'D': {'C'}, 'E': {'H', 'C'}, 'F': {'C', 'G'}, 'G': {'S', 'F', 'H'},
     'H': {'G', 'E'}, 'S': {'A', 'G', 'C'}}

def depth_first_search(graph, root):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

print(depth_first_search(graph, 'A'))

Below are the outputs I get evertime I run the program

{'H', 'C', 'B', 'A', 'D', 'S', 'F', 'E', 'G'}
{'D', 'E', 'C', 'H', 'G', 'S', 'A', 'B', 'F'}
{'G', 'F', 'C', 'H', 'E', 'D', 'B', 'S', 'A'} and so on....

The reason for using set especially makes sense for the below line of code as we want the stack to store only the vertices that are unexplored.

stack.extend(graph[vertex] - visited)

So performing set difference operation achieves that objective.But it comes at a cost as mentioned above.So I tweaked the code a bit to avoid using set and make do with lists

graph = {'A': ['B', 'S'], 'B': ['A'], 'C': ['S', 'F', 'D', 'E'],
 'D': ['C'], 'E': ['H', 'C'], 'F': ['C', 'G'], 'G': ['S', 'F', 'H'],
  'H': ['G', 'E'], 'S': ['A', 'G', 'C']}

def depth_first_search(graph, root):
    visited, stack = [], [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.append(vertex)
            neighbours = graph[vertex]
            for neighbour in neighbours:
                # ensures we only add unexplored nodes to the stack
                if neighbour not in visited:
                    stack.append(neighbour)
    return visited

print(depth_first_search(graph, 'A'))

But I get a wrong result

['A', 'S', 'C', 'E', 'H', 'G', 'F', 'D', 'B']

The correct result must be

['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']

What am I doing wrong?


问:
Split string into multiple alpha and numeric segments
I have a string like "ABCD232ERE44RR". How can I split it into separate segments by letters/numbers. I need:
Segment1: ABCD
Segment2: 232
Segment3: ERE
Segment4: 44

There could be any number of segments. I am thinking go Regex but don't understand how to write it properly

答:
Try something like:</p>

```<code>((A-Z)+(\d)*)+
</code>```

Body:
Try something like:

((A-Z)+(\d)*)+


问:
How to exit the Vim editor when :q or :x doesn't work
Newbie to vi / vim, I normally use pico but using a locked down box (for now) that only has these 2 editors.

I am having trouble getting it to save a file or even just quit. I see others having the same issue and they were told to use :x but even that doesn't work, just throws up an error message.

Is there an exit command that JUST works?

thanks

答:
:q should work, unless the file hasn't been saved.

:q! will work.

:wq will attempt to save and quit, but won't quit if it can't save.

:wq! will attempt to save, and then quit whether or not it can save.

E: Credit to @GregoryNisbet for reminding me: if you have multiple files open, there is a series of 'all' quit commands:

:qa should quit all buffers (open files, more or less).

:qa! will quit all buffers regardless of if they have been saved.

:wqa will attempt to save and quit all buffers.

:wqa! will attempt to save all buffers, and then quit whether or not they are saved.


问:
Use selectInput For Deciding Which Column in Data Fame To Use In Calculation
A user selects a column name from a selectInput and I would like to use it in a calculation that will be shown in a leaflet map. The general idea is that upon selection of a column we do:

```<code>EduAtt_df$percent <- reactive({100*(EduAtt_df$COLUMNSELECTED/EduAtt_df$total)});
</code>```

I have tried:

```<code>EduAtt_df$percent <- reactive({100*(EduAtt_df$[input$x]/EduAtt_df$total)});
</code>```

This produces error:

Warning: Error in rep: attempt to replicate an object of type
  'closure' Stack trace (innermost first):
      39: $<-.data.frame
      38: $<- [C:\Users\lrichards\Documents\RShiny\ACSEduAttain\ACSEduAttain/app.R#128]
      37: server [C:\Users\lrichards\Documents\RShiny\ACSEduAttain\ACSEduAttain/app.R#128]
       1: runApp Error in rep(value, length.out = nrows) :    attempt to replicate an object of type 'closure'

How can I use selectInput selection to "pick" a column to use in a calculation?

Here is my current code. This does require a Census API key to use.

```<code># Load packages -----------------------------------------------------
library(rgdal)
library(sp)
library(leaflet)
library(dplyr)
library(ggplot2)
library(tigris)
library(acs)
library(stringr)

# Load data ---------------------------------------------------------
api.key.install(key="YourCensusKey");
counties <- c(103);
tracts <- tracts(state = 'FL', county = counties, cb=TRUE);
geo<-geo.make(state=c("FL"), county=counties, tract="*");

EduAtt<-acs.fetch(endyear = 2015, span = 5, geography = geo, table.number = "B15003", col.names = "pretty");

EduAtt_df <- data.frame(
    paste0(
        str_pad(EduAtt@geography$state, 2, "left", pad="0"),
        str_pad(EduAtt@geography$county, 3, "left", pad="0"),
        str_pad(EduAtt@geography$tract, 6, "left", pad="0")),
    EduAtt@estimate[,c(
        "Educational Attainment for the Population 25 Years and Over: Total:",
        "Educational Attainment for the Population 25 Years and Over: No schooling completed",
        "Educational Attainment for the Population 25 Years and Over: Nursery school",
        "Educational Attainment for the Population 25 Years and Over: Kindergarten",
        "Educational Attainment for the Population 25 Years and Over: 1st grade",
        "Educational Attainment for the Population 25 Years and Over: 2nd grade",
        "Educational Attainment for the Population 25 Years and Over: 3rd grade",
        "Educational Attainment for the Population 25 Years and Over: 4th grade",
        "Educational Attainment for the Population 25 Years and Over: 5th grade",
        "Educational Attainment for the Population 25 Years and Over: 6th grade",
        "Educational Attainment for the Population 25 Years and Over: 7th grade",
        "Educational Attainment for the Population 25 Years and Over: 8th grade",
        "Educational Attainment for the Population 25 Years and Over: 9th grade",
        "Educational Attainment for the Population 25 Years and Over: 10th grade",
        "Educational Attainment for the Population 25 Years and Over: 11th grade",
        "Educational Attainment for the Population 25 Years and Over: 12th grade, no diploma",
        "Educational Attainment for the Population 25 Years and Over: Regular high school diploma",
        "Educational Attainment for the Population 25 Years and Over: GED or alternative credential",
        "Educational Attainment for the Population 25 Years and Over: Some college, less than 1 year",
        "Educational Attainment for the Population 25 Years and Over: Some college, 1 or more years, no degree",
        "Educational Attainment for the Population 25 Years and Over: Associate's degree",
        "Educational Attainment for the Population 25 Years and Over: Bachelor's degree",
        "Educational Attainment for the Population 25 Years and Over: Master's degree",
        "Educational Attainment for the Population 25 Years and Over: Professional school degree",
        "Educational Attainment for the Population 25 Years and Over: Doctorate degree")
        ],
    stringsAsFactors = FALSE);

rownames(EduAtt_df) <- 1:nrow(EduAtt_df);
names(EduAtt_df)<-c("GEOID", "total", "no_school","Nursery", "Kindergarten", "g1st", "g2nd", "g3rd", "g4th", "g5th", "g6th", "g7th", "g8th", "g9th", "g10th", "g11th", "g12th", "HS", "GED", "col_less1", "col_1nodegree", "AS", "BA", "MA", "Prof", "PHd");

# Initial page load calculation
EduAtt_df$percent <- 100*(EduAtt_df$g12th/EduAtt_df$total);

EduAtt_merged<- geo_join(tracts, EduAtt_df, "GEOID", "GEOID");
EduAtt_merged <- EduAtt_merged[EduAtt_merged$ALAND>0,];

popup <- paste0("GEOID: ", EduAtt_merged$GEOID, "<br>", "Percent of Population With AS: ", round(EduAtt_merged$percent,2));
pal <- colorNumeric(palette = "RdPu", domain = EduAtt_merged$percent);
map3<-leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%
    addPolygons(data = EduAtt_merged, fillColor = ~pal(percent), color = "#b2aeae", fillOpacity = 0.7, weight = 1, smoothFactor = 0.2, popup = popup) %>%
    addLegend(pal = pal, values = EduAtt_merged$percent, position = "bottomright", title = "Percent of Population<br>With AS", labFormat = labelFormat(suffix = "%"));

# UI ----------------------------------------------------------------
ui <- fluidPage(

  # App title -------------------------------------------------------
  titlePanel("Educational Attainment By Population"),

  # Sidebar layout with a input and output definitions --------------
  sidebarLayout(

    # Inputs --------------------------------------------------------
    sidebarPanel(
      selectInput('x', 'X', names(EduAtt_df))
    ),

    # Output --------------------------------------------------------
    mainPanel(
      textOutput("testvar"),
      leafletOutput("map", height = "600px", width = "700px")
    )

  )
)

# SERVER ------------------------------------------------------------
server <- function(input, output) {
  output$testvar = renderText(input$x);
  EduAtt_df$percent <- reactive({100*(EduAtt_df[input$x]/EduAtt_df$total)});

  # Map -------------------------------------------------------
  output$map <- renderLeaflet({
    map3
    });
}

# Run app -----------------------------------------------------------
shinyApp(ui = ui, server = server);
</code>```

答:
You are trying to assign a reactive function to a column of a data frame, that does not work. A long explanation can be found on the Shiny website. A minimal reproducible example for your case would be:

```<code>library(shiny)

ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(selectInput("x", "Pick a column", choices = names(mtcars))),
      mainPanel(tableOutput("result")))
)

mtcars$new_column <- reactive(100 * mtcars[[input$x]])

server <- function(input, output) {
   output$result <- renderTable({
     return(mtcars)
   })
}

shinyApp(ui = ui, server = server)
</code>```

You can move the calculation into a reactive context and remove the call to reactive. In your case probably the renderLeaflet function, in the example above like this:

```<code>library(shiny)

ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(selectInput("x", "Pick a column", choices = names(mtcars))),
      mainPanel(tableOutput("result")))
)

server <- function(input, output) {
   output$result <- renderTable({
     mtcars$new_column <- 100 * mtcars[[input$x]]
     return(mtcars)
   })
}

shinyApp(ui = ui, server = server)
</code>```

Body:
A user selects a column name from a selectInput and I would like to use it in a calculation that will be shown in a leaflet map. The general idea is that upon selection of a column we do:

EduAtt_df$percent <- reactive({100*(EduAtt_df$COLUMNSELECTED/EduAtt_df$total)});

I have tried:

EduAtt_df$percent <- reactive({100*(EduAtt_df$[input$x]/EduAtt_df$total)});

This produces error:

Warning: Error in rep: attempt to replicate an object of type
  'closure' Stack trace (innermost first):
      39: $<-.data.frame
      38: $<- [C:\Users\lrichards\Documents\RShiny\ACSEduAttain\ACSEduAttain/app.R#128]
      37: server [C:\Users\lrichards\Documents\RShiny\ACSEduAttain\ACSEduAttain/app.R#128]
       1: runApp Error in rep(value, length.out = nrows) :    attempt to replicate an object of type 'closure'

How can I use selectInput selection to "pick" a column to use in a calculation?

Here is my current code. This does require a Census API key to use.

# Load packages -----------------------------------------------------
library(rgdal)
library(sp)
library(leaflet)
library(dplyr)
library(ggplot2)
library(tigris)
library(acs)
library(stringr)

# Load data ---------------------------------------------------------
api.key.install(key="YourCensusKey");
counties <- c(103);
tracts <- tracts(state = 'FL', county = counties, cb=TRUE);
geo<-geo.make(state=c("FL"), county=counties, tract="*");

EduAtt<-acs.fetch(endyear = 2015, span = 5, geography = geo, table.number = "B15003", col.names = "pretty");

EduAtt_df <- data.frame(
    paste0(
        str_pad(EduAtt@geography$state, 2, "left", pad="0"),
        str_pad(EduAtt@geography$county, 3, "left", pad="0"),
        str_pad(EduAtt@geography$tract, 6, "left", pad="0")),
    EduAtt@estimate[,c(
        "Educational Attainment for the Population 25 Years and Over: Total:",
        "Educational Attainment for the Population 25 Years and Over: No schooling completed",
        "Educational Attainment for the Population 25 Years and Over: Nursery school",
        "Educational Attainment for the Population 25 Years and Over: Kindergarten",
        "Educational Attainment for the Population 25 Years and Over: 1st grade",
        "Educational Attainment for the Population 25 Years and Over: 2nd grade",
        "Educational Attainment for the Population 25 Years and Over: 3rd grade",
        "Educational Attainment for the Population 25 Years and Over: 4th grade",
        "Educational Attainment for the Population 25 Years and Over: 5th grade",
        "Educational Attainment for the Population 25 Years and Over: 6th grade",
        "Educational Attainment for the Population 25 Years and Over: 7th grade",
        "Educational Attainment for the Population 25 Years and Over: 8th grade",
        "Educational Attainment for the Population 25 Years and Over: 9th grade",
        "Educational Attainment for the Population 25 Years and Over: 10th grade",
        "Educational Attainment for the Population 25 Years and Over: 11th grade",
        "Educational Attainment for the Population 25 Years and Over: 12th grade, no diploma",
        "Educational Attainment for the Population 25 Years and Over: Regular high school diploma",
        "Educational Attainment for the Population 25 Years and Over: GED or alternative credential",
        "Educational Attainment for the Population 25 Years and Over: Some college, less than 1 year",
        "Educational Attainment for the Population 25 Years and Over: Some college, 1 or more years, no degree",
        "Educational Attainment for the Population 25 Years and Over: Associate's degree",
        "Educational Attainment for the Population 25 Years and Over: Bachelor's degree",
        "Educational Attainment for the Population 25 Years and Over: Master's degree",
        "Educational Attainment for the Population 25 Years and Over: Professional school degree",
        "Educational Attainment for the Population 25 Years and Over: Doctorate degree")
        ],
    stringsAsFactors = FALSE);

rownames(EduAtt_df) <- 1:nrow(EduAtt_df);
names(EduAtt_df)<-c("GEOID", "total", "no_school","Nursery", "Kindergarten", "g1st", "g2nd", "g3rd", "g4th", "g5th", "g6th", "g7th", "g8th", "g9th", "g10th", "g11th", "g12th", "HS", "GED", "col_less1", "col_1nodegree", "AS", "BA", "MA", "Prof", "PHd");

# Initial page load calculation
EduAtt_df$percent <- 100*(EduAtt_df$g12th/EduAtt_df$total);

EduAtt_merged<- geo_join(tracts, EduAtt_df, "GEOID", "GEOID");
EduAtt_merged <- EduAtt_merged[EduAtt_merged$ALAND>0,];

popup <- paste0("GEOID: ", EduAtt_merged$GEOID, "
", "Percent of Population With AS: ", round(EduAtt_merged$percent,2));
pal <- colorNumeric(palette = "RdPu", domain = EduAtt_merged$percent);
map3<-leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%
    addPolygons(data = EduAtt_merged, fillColor = ~pal(percent), color = "#b2aeae", fillOpacity = 0.7, weight = 1, smoothFactor = 0.2, popup = popup) %>%
    addLegend(pal = pal, values = EduAtt_merged$percent, position = "bottomright", title = "Percent of Population
With AS", labFormat = labelFormat(suffix = "%"));

# UI ----------------------------------------------------------------
ui <- fluidPage(

  # App title -------------------------------------------------------
  titlePanel("Educational Attainment By Population"),

  # Sidebar layout with a input and output definitions --------------
  sidebarLayout(

    # Inputs --------------------------------------------------------
    sidebarPanel(
      selectInput('x', 'X', names(EduAtt_df))
    ),

    # Output --------------------------------------------------------
    mainPanel(
      textOutput("testvar"),
      leafletOutput("map", height = "600px", width = "700px")
    )

  )
)

# SERVER ------------------------------------------------------------
server <- function(input, output) {
  output$testvar = renderText(input$x);
  EduAtt_df$percent <- reactive({100*(EduAtt_df[input$x]/EduAtt_df$total)});

  # Map -------------------------------------------------------
  output$map <- renderLeaflet({
    map3
    });
}

# Run app -----------------------------------------------------------
shinyApp(ui = ui, server = server);

Body:
You are trying to assign a reactive function to a column of a data frame, that does not work. A long explanation can be found on the Shiny website. A minimal reproducible example for your case would be:

library(shiny)

ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(selectInput("x", "Pick a column", choices = names(mtcars))),
      mainPanel(tableOutput("result")))
)

mtcars$new_column <- reactive(100 * mtcars[[input$x]])

server <- function(input, output) {
   output$result <- renderTable({
     return(mtcars)
   })
}

shinyApp(ui = ui, server = server)

You can move the calculation into a reactive context and remove the call to reactive. In your case probably the renderLeaflet function, in the example above like this:

library(shiny)

ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(selectInput("x", "Pick a column", choices = names(mtcars))),
      mainPanel(tableOutput("result")))
)

server <- function(input, output) {
   output$result <- renderTable({
     mtcars$new_column <- 100 * mtcars[[input$x]]
     return(mtcars)
   })
}

shinyApp(ui = ui, server = server)


问:
How do I share objects on GCS without being billed for downloads?
When objects are uploaded into a GCS bucket and shared publicly, the owner of the bucket is responsible for all of the costs of users downloading these objects. How do I change that so that the downloaders are billed instead of me?</p>

答:
This feature is called "Requester Pays." Its documentation is here: https://cloud.google.com/storage/docs/requester-pays

The idea is that you mark a bucket as being a "requester pays" bucket. Once you've done that, your project is only responsible for the price of storing the objects in the bucket (and, if it's a nearline or coldline bucket, any early deletion fees). Anyone that wants to download an object from this bucket (or upload a new object, copy an object, etc) must specify which of their projects GCS should bill for the operation.

This is a very useful configuration for situations where you wish to make objects publicly available but don't want to be responsible for the cost of distributing it to many end users.

To enable Requester Pays on a bucket, open the Cloud Storage browser, find your bucket, and click the "off" button in the "Requester Pays" column, and follow the prompts. You can also set this flag in other ways, see the docs: https://cloud.google.com/storage/docs/using-requester-pays#enable

Downloading objects from requester pays buckets requires a Google Cloud project with billing enabled. Once you have that, you can download the object from the cloud console or using gsutil:

```<code>$> gsutil -u [PROJECT_ID] cp gs://[BUCKET_NAME]/[OBJECT_NAME] [OBJECT_DESTINATION]
</code>```

The trick to this command is the -u [PROJECT_ID] bit, which specifies which project should be billed for the download.

You can also download the object using our other APIs or with the cloud console. More in the docs: https://cloud.google.com/storage/docs/using-requester-pays#using

Body:
This feature is called "Requester Pays." Its documentation is here: https://cloud.google.com/storage/docs/requester-pays

The idea is that you mark a bucket as being a "requester pays" bucket. Once you've done that, your project is only responsible for the price of storing the objects in the bucket (and, if it's a nearline or coldline bucket, any early deletion fees). Anyone that wants to download an object from this bucket (or upload a new object, copy an object, etc) must specify which of their projects GCS should bill for the operation.

This is a very useful configuration for situations where you wish to make objects publicly available but don't want to be responsible for the cost of distributing it to many end users.

To enable Requester Pays on a bucket, open the Cloud Storage browser, find your bucket, and click the "off" button in the "Requester Pays" column, and follow the prompts. You can also set this flag in other ways, see the docs: https://cloud.google.com/storage/docs/using-requester-pays#enable

Downloading objects from requester pays buckets requires a Google Cloud project with billing enabled. Once you have that, you can download the object from the cloud console or using gsutil:

$> gsutil -u [PROJECT_ID] cp gs://[BUCKET_NAME]/[OBJECT_NAME] [OBJECT_DESTINATION]

The trick to this command is the -u [PROJECT_ID] bit, which specifies which project should be billed for the download.

You can also download the object using our other APIs or with the cloud console. More in the docs: https://cloud.google.com/storage/docs/using-requester-pays#using


问:
Convert Long Date / Time to user friendly one PHP
well I have an api returning a date in this format

2010-10-22 07:00:00 Etc/GMT

how can I change that so it's

October 22, 2010

using php

Thanks! :D

答:
```<code>print strftime('%B %e, %Y',strtotime('2010-10-22 07:00:00 Etc/GMT'));
</code>```

Outputs: "October 22, 2010"

How's that? :)

ContentLicense: CC BY-SA 2.5

Body:
print strftime('%B %e, %Y',strtotime('2010-10-22 07:00:00 Etc/GMT'));

Outputs: "October 22, 2010"

How's that? :)


问:
Fastest way to negate a std::vector
Assume I have a std::vector of double, namely

```<code>std::vector<double> MyVec(N);
</code>```

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

```<code>std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());
</code>```

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

答:
First, a generic negate function for arithmetic type vectors as an example:

```<code>#include <type_traits>
#include <vector>

...

template <typename arithmetic_type> std::vector<arithmetic_type> &
negate (std::vector<arithmetic_type> & v)
{
    static_assert(std::is_arithmetic<arithmetic_type>::value,
        "negate: not an arithmetic type vector");

    for (auto & vi : v) vi = - vi;

    // note: anticipate that a range-based for may be more amenable
    // to loop-unrolling, vectorization, etc., due to fewer compiler
    // template transforms, and contiguous memory / stride.

    // in theory, std::transform may generate the same code, despite
    // being less concise. very large vectors *may* possibly benefit
    // from C++17's 'std::execution::par_unseq' policy?

    return v;
}
</code>```

Your wish for a canonical unary operator - function is going to require a the creation of a temporary, in the form:

```<code>std::vector<double> operator - (const std::vector<double> & v)
{
    auto ret (v); return negate(ret);
}
</code>```

Or generically:

```<code>template <typename arithmetic_type> std::vector<arithmetic_type>
operator - (const std::vector<arithmetic_type> & v)
{
    auto ret (v); return negate(ret);
}
</code>```

Do not be tempted to implement the operator as:

```<code>template <typename arithmetic_type> std::vector<arithmetic_type> &
operator - (std::vector<arithmetic_type> & v)
{
    return negate(v);
}
</code>```

While (- v) will negate the elements and return the modified vector without the need for a temporary, it breaks mathematical conventions by effectively setting: v = - v; If that's your goal, then use the negate function. Don't break expected operator evaluation!

clang, with avx512 enabled, generates this loop, negating an impressive 64 doubles per iteration - between pre/post length handling:

```<code>        vpbroadcastq    LCPI0_0(%rip), %zmm0
        .p2align        4, 0x90
LBB0_21:
        vpxorq  -448(%rsi), %zmm0, %zmm1
        vpxorq  -384(%rsi), %zmm0, %zmm2
        vpxorq  -320(%rsi), %zmm0, %zmm3
        vpxorq  -256(%rsi), %zmm0, %zmm4
        vmovdqu64       %zmm1, -448(%rsi)
        vmovdqu64       %zmm2, -384(%rsi)
        vmovdqu64       %zmm3, -320(%rsi)
        vmovdqu64       %zmm4, -256(%rsi)
        vpxorq  -192(%rsi), %zmm0, %zmm1
        vpxorq  -128(%rsi), %zmm0, %zmm2
        vpxorq  -64(%rsi), %zmm0, %zmm3
        vpxorq  (%rsi), %zmm0, %zmm4
        vmovdqu64       %zmm1, -192(%rsi)
        vmovdqu64       %zmm2, -128(%rsi)
        vmovdqu64       %zmm3, -64(%rsi)
        vmovdqu64       %zmm4, (%rsi)
        addq    $512, %rsi              ## imm = 0x200
        addq    $-64, %rdx
        jne     LBB0_21
</code>```

gcc-7.2.0 generates a similar loop, but appears to insist on indexed addressing.

Title: Fastest way to negate a std::vector

Body:
Assume I have a std::vector of double, namely

std::vector<double> MyVec(N);

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

Body:
First, a generic negate function for arithmetic type vectors as an example:

#include <type_traits>
#include <vector>

...

template <typename arithmetic_type> std::vector<arithmetic_type> &
negate (std::vector<arithmetic_type> & v)
{
    static_assert(std::is_arithmetic<arithmetic_type>::value,
        "negate: not an arithmetic type vector");

    for (auto & vi : v) vi = - vi;

    // note: anticipate that a range-based for may be more amenable
    // to loop-unrolling, vectorization, etc., due to fewer compiler
    // template transforms, and contiguous memory / stride.

    // in theory, std::transform may generate the same code, despite
    // being less concise. very large vectors *may* possibly benefit
    // from C++17's 'std::execution::par_unseq' policy?

    return v;
}

Your wish for a canonical unary operator - function is going to require a the creation of a temporary, in the form:

std::vector<double> operator - (const std::vector<double> & v)
{
    auto ret (v); return negate(ret);
}

Or generically:

template <typename arithmetic_type> std::vector<arithmetic_type>
operator - (const std::vector<arithmetic_type> & v)
{
    auto ret (v); return negate(ret);
}

Do not be tempted to implement the operator as:

template <typename arithmetic_type> std::vector<arithmetic_type> &
operator - (std::vector<arithmetic_type> & v)
{
    return negate(v);
}

While (- v) will negate the elements and return the modified vector without the need for a temporary, it breaks mathematical conventions by effectively setting: v = - v; If that's your goal, then use the negate function. Don't break expected operator evaluation!

clang, with avx512 enabled, generates this loop, negating an impressive 64 doubles per iteration - between pre/post length handling:

        vpbroadcastq    LCPI0_0(%rip), %zmm0
        .p2align        4, 0x90
LBB0_21:
        vpxorq  -448(%rsi), %zmm0, %zmm1
        vpxorq  -384(%rsi), %zmm0, %zmm2
        vpxorq  -320(%rsi), %zmm0, %zmm3
        vpxorq  -256(%rsi), %zmm0, %zmm4
        vmovdqu64       %zmm1, -448(%rsi)
        vmovdqu64       %zmm2, -384(%rsi)
        vmovdqu64       %zmm3, -320(%rsi)
        vmovdqu64       %zmm4, -256(%rsi)
        vpxorq  -192(%rsi), %zmm0, %zmm1
        vpxorq  -128(%rsi), %zmm0, %zmm2
        vpxorq  -64(%rsi), %zmm0, %zmm3
        vpxorq  (%rsi), %zmm0, %zmm4
        vmovdqu64       %zmm1, -192(%rsi)
        vmovdqu64       %zmm2, -128(%rsi)
        vmovdqu64       %zmm3, -64(%rsi)
        vmovdqu64       %zmm4, (%rsi)
        addq    $512, %rsi              ## imm = 0x200
        addq    $-64, %rdx
        jne     LBB0_21

gcc-7.2.0 generates a similar loop, but appears to insist on indexed addressing.


问:
How to force JavaScript integer to keep a zero before numbers?
How can I force JavaScript to keep 0 before numbers in the Int type?

I have some numeric map codes which all starting by 0 so I need to pass them as a part of the number for each code.

```<code>var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(mapcode);
</code>```

答:
As has been said, javascript just keeps the integer and therefore prepending zeros are 'removed' because they are meaningless to a number. (i.e. 42 = 042 = 0042 = 0000000042).

So what you need is to either keep these numbers as strings, in which case every character (including prepended zeros) are meaningful. Or you will need to prepend the appropriate number of zeros to the number before displaying it.

You can see this question to find several methods for prepending zeros to a number for printing.

ContentLicense: CC BY-SA 4.0

Body:
How can I force JavaScript to keep 0 before numbers in the Int type?

I have some numeric map codes which all starting by 0 so I need to pass them as a part of the number for each code.

var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(mapcode);


问:
swift usesPreciseCollisionDetection does not work?
i have made an app where you need to shoot on an enemy but sometimes the bullet goes through the enemy. swift sprite kit game when I shoot on a enemy sometimes the bullet goes trough the enemy, how can I fix this?

so i added usesPreciseCollisionDetection = true.
but the bullet sometimes still goes trough the enemy. so my question was did i do something wrong or is usesPreciseCollisionDetection not working?

thank you for reading my question I hope someone can help me.

答: I had similar problem that is collision was sometimes not detected even when usesPreciseCollisionDetection was set to true and both SKPhysicsBody were rectangles. In my case usesPreciseCollisionDetection for some reason started working much better when I changed one of the SKPhysicsBody to circle instead of rectangle. Try changing your bullet physics body to circle, it seems that collision detection algorithm with circles is more precise so that might help you.</p>


问:
How do String oops and mirror oops generate by Hotspot VM?
In openjdk8 source code, I find that some java.lang.String oop do not go through bytecode engine and allocate by jvm itself. As hotspot/src/share/vm/classfile/javaClasses.cpp:185 says:

```<code>Handle java_lang_String::create_from_unicode(jchar* unicode, int length, TRAPS) {
  Handle h_obj = basic_create(length, CHECK_NH); // alloc size of java.lang.String oop
  typeArrayOop buffer = value(h_obj());
  for (int index = 0; index < length; index++) {
    buffer->char_at_put(index, unicode[index]);  // put a char[] into this oop...
  }
  return h_obj;
}
</code>```

As above, a fake String is created... however, java.lang.String has five member variables (fields), how do they initialize? In other words, how does these fake String oop become the real java.lang.String object?

Same as java.lang.String, java.lang.Class also does this things. At hotspot/src/share/vm/classfile/javaClasses.cpp:553 says:

```<code>oop java_lang_Class::create_mirror(KlassHandle k, Handle protection_domain, TRAPS) {
    ...
    Handle mirror = InstanceMirrorKlass::cast(SystemDictionary::Class_klass())->allocate_instance(k, CHECK_0);
    ...
    // if `k` holds a InstanceKlass, it will initialize the static fields by constant value attribute. else do nothing...
}
</code>```

I was very confused by this. Only alloc memory, if it is java.lang.String's object, put a char[] into it; but when do the other fields in java.lang.String and java.lang.Class fills in to the oop? Thank you.

答:
java_lang_String::basic_create() allocates String object and initializes its value field:

```<code>    obj = InstanceKlass::cast(SystemDictionary::String_klass())->allocate_instance(CHECK_NH);

    // Create the char array.  The String object must be handlized here
    // because GC can happen as a result of the allocation attempt.
    Handle h_obj(THREAD, obj);
    typeArrayOop buffer;
      buffer = oopFactory::new_charArray(length, CHECK_NH);

    // Point the String at the char array
    obj = h_obj();
    set_value(obj, buffer);   <<<--- char[] value is set here
  // No need to zero the offset, allocation zero'ed the entire String object
  assert(offset(obj) == 0, "initial String offset should be zero");
//set_offset(obj, 0);
  set_count(obj, length);
</code>```

hash field is computed lazily. At allocation time it has the default value 0 since allocate_instance clears the entire object. There are no other String instance fields in JDK 8.

As to java.lang.Class, it has no fields to initialize at allocation time, because all its fields are kind of caches. They are set in Java code when needed. Again, the entire Class instance is zeroed by allocation routine.

Body:
In openjdk8 source code, I find that some java.lang.String oop do not go through bytecode engine and allocate by jvm itself. As hotspot/src/share/vm/classfile/javaClasses.cpp:185 says:

Handle java_lang_String::create_from_unicode(jchar* unicode, int length, TRAPS) {
  Handle h_obj = basic_create(length, CHECK_NH); // alloc size of java.lang.String oop
  typeArrayOop buffer = value(h_obj());
  for (int index = 0; index < length; index++) {
    buffer->char_at_put(index, unicode[index]);  // put a char[] into this oop...
  }
  return h_obj;
}

As above, a fake String is created... however, java.lang.String has five member variables (fields), how do they initialize? In other words, how does these fake String oop become the real java.lang.String object?

Same as java.lang.String, java.lang.Class also does this things. At hotspot/src/share/vm/classfile/javaClasses.cpp:553 says:

oop java_lang_Class::create_mirror(KlassHandle k, Handle protection_domain, TRAPS) {
    ...
    Handle mirror = InstanceMirrorKlass::cast(SystemDictionary::Class_klass())->allocate_instance(k, CHECK_0);
    ...
    // if `k` holds a InstanceKlass, it will initialize the static fields by constant value attribute. else do nothing...
}

I was very confused by this. Only alloc memory, if it is java.lang.String's object, put a char[] into it; but when do the other fields in java.lang.String and java.lang.Class fills in to the oop? Thank you.

Body:
java_lang_String::basic_create() allocates String object and initializes its value field:

    obj = InstanceKlass::cast(SystemDictionary::String_klass())->allocate_instance(CHECK_NH);

    // Create the char array.  The String object must be handlized here
    // because GC can happen as a result of the allocation attempt.
    Handle h_obj(THREAD, obj);
    typeArrayOop buffer;
      buffer = oopFactory::new_charArray(length, CHECK_NH);

    // Point the String at the char array
    obj = h_obj();
    set_value(obj, buffer);   <<<--- char[] value is set here
  // No need to zero the offset, allocation zero'ed the entire String object
  assert(offset(obj) == 0, "initial String offset should be zero");
//set_offset(obj, 0);
  set_count(obj, length);

hash field is computed lazily. At allocation time it has the default value 0 since allocate_instance clears the entire object. There are no other String instance fields in JDK 8.

As to java.lang.Class, it has no fields to initialize at allocation time, because all its fields are kind of caches. They are set in Java code when needed. Again, the entire Class instance is zeroed by allocation routine.


问:
Pause and resume animation in the same keyframe
Is it possible to pause animation of SCNNode (animaton with model from .dae collada) and then resume in the same keyframe which it was paused?</p>

答:
Will using the isPaused property on the SCNNode work for your needs?

Example:

self.childNode.isPaused = true


问:
How to solve SIGSEGV, Segmentation fault in C?
I am working on a program to read data from a text file and encode it with a Huffman encoding.  I've run it 2-3 times, and it shows nothing but an error message:

```<code>Program received signal SIGSEGV, Segmentation fault.
__strcpy_sse2 () at ../sysdeps/x86_64/multiarch/../strcpy.S:57
57    ../sysdeps/x86_64/multiarch/../strcpy.S: No such file or directory.
</code>```

When I debugged the program,  I traced the problem to the following function:

```<code>// walk the tree and put 0s and 1s
void build_bcode_from_tree(node n, char *s, int len)
{
    static char *out = buf;
    if (n->c) {
        s[len] = 0;
        strcpy(out, s);
        code[n->c] = out;
        out += len + 1;
        return;
    }

    s[len] = '0'; build_bcode_from_tree(n->left,  s, len + 1);
    s[len] = '1'; build_bcode_from_tree(n->right, s, len + 1);
}
</code>```

What am I doing wrong?

Here is the full code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct node_t {
    struct node_t *left, *right;
    int freq;
    char c;
} *node;

struct node_t pool[256] = {{0}};
node qqq[255], *q = qqq - 1;
int n_nodes = 0, qend = 1;
char *code[128] = {0}, buf[1024];

//creating tree
node create_tree(int freq, char c, node a, node b)
{
    node n = pool + n_nodes++;
    if (freq) n->c = c, n->freq = freq;
    else {
        n->left = a, n->right = b;
        n->freq = a->freq + b->freq;
    }
    return n;
}

// priority queue according to frequency
void qinsert(node n)
{
    int j, i = qend++;
    while ((j = i / 2)) {
        if (q[j]->freq <= n->freq) break;
        q[i] = q[j], i = j;
    }
    q[i] = n;
}

node qremove()
{
    int i, l;
    node n = q[i = 1];

    if (qend < 2) return 0;
    qend--;
    while ((l = i * 2) < qend) {
        if (l + 1 < qend && q[l + 1]->freq < q[l]->freq) l++;
        q[i] = q[l], i = l;
    }
    q[i] = q[qend];
    return n;
}

// walk the tree and put 0s and 1s
void build_bcode_from_tree(node n, char *s, int len)
{
    static char *out = buf;
    if (n->c) {
        s[len] = 0;
        strcpy(out, s);
        code[n->c] = out;
        out += len + 1;
        return;
    }

    s[len] = '0'; build_bcode_from_tree(n->left,  s, len + 1);
    s[len] = '1'; build_bcode_from_tree(n->right, s, len + 1);
}

// individual binary representation
void ind_repre(const char *s)
{
    int i, freq[128] = {0};
    char c[16];

    while (*s) freq[(int)*s++]++;

    for (i = 0; i < 128; i++)
        if (freq[i]) qinsert(create_tree(freq[i], i, 0, 0));

    while (qend > 2)
        qinsert(create_tree(0, 0, qremove(), qremove()));

    build_bcode_from_tree(q[1], c, 0);
}

// endode the whole file data
void compress(const char *s, char *out)
{
    while (*s) {
        strcpy(out, code[*s]);
        out += strlen(code[*s++]);
    }
}

//showing decode data
void decompress(const char *s, node t)
{
    FILE *filew;
    filew = fopen("output.txt", "w");
    node n = t;
    while (*s) {
        if (*s++ == '0') n = n->left;
        else n = n->right;
        // if (n->c) putchar(n->c), n = t;
        if (n->c) fprintf(filew,"%c", n->c), n = t;
    }
    putchar('\n');
    if (t != n) printf("wrong input\n");
  fclose(filew);

}

// main function
int main(void)
{
    int i;
    const char *str;
  char buff[1024];
    // read from file
    char txt[1024];
    FILE *file;
    size_t nread;

    file = fopen("index.html", "r");
    if (file == NULL) {
            printf("There is no file with this name!!\n");
            exit(-1);
    } else {

            while ((nread = fread(txt, 1, sizeof txt, file)) > 0)
                    fwrite(txt, 1, nread, stdout);
            if (ferror(file)) {

            }
            fclose(file);
    }

 str = txt;
    ind_repre(str);
    for (i = 0; i < 128; i++)
        if (code[i]) printf("'%c': %s\n", i, code[i]);

    compress(str, buff);
    printf("compressedData: %s\n", buff);

    decompress(buff, q[1]);
    printf("decoding done ! check output file\n");

    return 0;
}
</code>```

答:
The debugger message shows, that indeed the call to strcpy() is the culprit:

__strcpy_sse2 () at ../sysdeps/x86_64/multiarch/../strcpy.S:57

Judging from the code you share, the buffer buf to which out points does not seem to be large enough to hold a string of length len, which you try to copy into it. Alternatively it could be possible, that buf is not in a writable part of your process memory.

In any case, make sure that out points to a writable buffer, which is large enough, perhaps by allocating some space to it, for example with:

```<code>static char *out = NULL;

if (out == NULL)
    out = malloc(len);
</code>```

This should solve your issue.

Body:
I am working on a program to read data from a text file and encode it with a Huffman encoding.  I've run it 2-3 times, and it shows nothing but an error message:

Program received signal SIGSEGV, Segmentation fault.
__strcpy_sse2 () at ../sysdeps/x86_64/multiarch/../strcpy.S:57
57    ../sysdeps/x86_64/multiarch/../strcpy.S: No such file or directory.

When I debugged the program,  I traced the problem to the following function:

// walk the tree and put 0s and 1s
void build_bcode_from_tree(node n, char *s, int len)
{
    static char *out = buf;
    if (n->c) {
        s[len] = 0;
        strcpy(out, s);
        code[n->c] = out;
        out += len + 1;
        return;
    }

    s[len] = '0'; build_bcode_from_tree(n->left,  s, len + 1);
    s[len] = '1'; build_bcode_from_tree(n->right, s, len + 1);
}

What am I doing wrong?

Here is the full code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct node_t {
    struct node_t *left, *right;
    int freq;
    char c;
} *node;

struct node_t pool[256] = {{0}};
node qqq[255], *q = qqq - 1;
int n_nodes = 0, qend = 1;
char *code[128] = {0}, buf[1024];

//creating tree
node create_tree(int freq, char c, node a, node b)
{
    node n = pool + n_nodes++;
    if (freq) n->c = c, n->freq = freq;
    else {
        n->left = a, n->right = b;
        n->freq = a->freq + b->freq;
    }
    return n;
}

// priority queue according to frequency
void qinsert(node n)
{
    int j, i = qend++;
    while ((j = i / 2)) {
        if (q[j]->freq <= n->freq) break;
        q[i] = q[j], i = j;
    }
    q[i] = n;
}

node qremove()
{
    int i, l;
    node n = q[i = 1];

    if (qend < 2) return 0;
    qend--;
    while ((l = i * 2) < qend) {
        if (l + 1 < qend && q[l + 1]->freq < q[l]->freq) l++;
        q[i] = q[l], i = l;
    }
    q[i] = q[qend];
    return n;
}

// walk the tree and put 0s and 1s
void build_bcode_from_tree(node n, char *s, int len)
{
    static char *out = buf;
    if (n->c) {
        s[len] = 0;
        strcpy(out, s);
        code[n->c] = out;
        out += len + 1;
        return;
    }

    s[len] = '0'; build_bcode_from_tree(n->left,  s, len + 1);
    s[len] = '1'; build_bcode_from_tree(n->right, s, len + 1);
}

// individual binary representation
void ind_repre(const char *s)
{
    int i, freq[128] = {0};
    char c[16];

    while (*s) freq[(int)*s++]++;

    for (i = 0; i < 128; i++)
        if (freq[i]) qinsert(create_tree(freq[i], i, 0, 0));

    while (qend > 2)
        qinsert(create_tree(0, 0, qremove(), qremove()));

    build_bcode_from_tree(q[1], c, 0);
}

// endode the whole file data
void compress(const char *s, char *out)
{
    while (*s) {
        strcpy(out, code[*s]);
        out += strlen(code[*s++]);
    }
}

//showing decode data
void decompress(const char *s, node t)
{
    FILE *filew;
    filew = fopen("output.txt", "w");
    node n = t;
    while (*s) {
        if (*s++ == '0') n = n->left;
        else n = n->right;
        // if (n->c) putchar(n->c), n = t;
        if (n->c) fprintf(filew,"%c", n->c), n = t;
    }
    putchar('\n');
    if (t != n) printf("wrong input\n");
  fclose(filew);

}

// main function
int main(void)
{
    int i;
    const char *str;
  char buff[1024];
    // read from file
    char txt[1024];
    FILE *file;
    size_t nread;

    file = fopen("index.html", "r");
    if (file == NULL) {
            printf("There is no file with this name!!\n");
            exit(-1);
    } else {

            while ((nread = fread(txt, 1, sizeof txt, file)) > 0)
                    fwrite(txt, 1, nread, stdout);
            if (ferror(file)) {

            }
            fclose(file);
    }

 str = txt;
    ind_repre(str);
    for (i = 0; i < 128; i++)
        if (code[i]) printf("'%c': %s\n", i, code[i]);

    compress(str, buff);
    printf("compressedData: %s\n", buff);

    decompress(buff, q[1]);
    printf("decoding done ! check output file\n");

    return 0;
}

Body:
The debugger message shows, that indeed the call to strcpy() is the culprit:

__strcpy_sse2 () at ../sysdeps/x86_64/multiarch/../strcpy.S:57

Judging from the code you share, the buffer buf to which out points does not seem to be large enough to hold a string of length len, which you try to copy into it. Alternatively it could be possible, that buf is not in a writable part of your process memory.

In any case, make sure that out points to a writable buffer, which is large enough, perhaps by allocating some space to it, for example with:

static char *out = NULL;

if (out == NULL)
    out = malloc(len);

This should solve your issue.


问:
Nested vue instance not returning computed: function values
I'm using twig and in my base I have a new Vue instance that assigns everything to #app, which is a section right after the body tag.

In users.html page, I extend this base.twig, reason why I can't have the same code onto the base.twig is because some data is only passed to the vue on the users controller, so I get errors on any other pages since the users data isn't set.

This is what I have on my base.twig

```<code>new Vue({
    el: '#app',
    data: {
        hideNav: false,
        userMenuDropdown: false,

        showModal: false
    }
});
</code>```

And in my users.html I have:

```<code>var UsersPage = new Vue({
    el: '.users__main',
    data: {
        search_users: '',
        users: {{ users|raw }}
    },
    computed: {
        filteredUsers,
    }
});

function filteredUsers(){
    var self = this;
    return this.users.filter(function(cust){
        return cust.first_name.toLowerCase().indexOf(self.search_users.toLowerCase())>=0;
    });
}
</code>```

I'm simply trying to search for an user, everything works if I take off the first vue instance that references #app, not .users__main.

I have setup a jsfiddle to further explain the exact issue, this version (does not work) has both vue instances, one in the base.twig and the other in the user.html file, this version does not contain both instances (works).

I was messing with components for this but I wasn't able to get that going.

答:
So, I was able to figure it out after reading the documentation, I wound up using a component with inline-template.

In my base.twig I create one and only 1 instance of Vue.

```<code>new Vue({
    el: '#app',
});
</code>```

And now in my user.html file that extends the base.twig I created a component.

This wound up being the component and how it was used to have a search function working that I provided in the jsfiddle example in the question.

```<code>Vue.component('user-search', {
    data: function () {
        return {
            search_users: '',
            users: {{ users|raw }} // this here is json_encoded data from twig passed from the php framework controller
        }
    },
    computed: {
        filteredUsers,
    }
});

function filteredUsers(){
    var self = this;
    return this.users.filter(function(cust){
        return cust.first_name.toLowerCase().indexOf(self.search_users.toLowerCase())>=0;
    });
}
</code>```

And to use the component(showing how to use it based on my code):

```<code><user-search inline-template>
    <input type="text" v-model="search_users">
    <!-- rest of the code with the for loop -->
</user-search>
</code>```

Body:
I'm using twig and in my base I have a new Vue instance that assigns everything to #app, which is a section right after the body tag.

In users.html page, I extend this base.twig, reason why I can't have the same code onto the base.twig is because some data is only passed to the vue on the users controller, so I get errors on any other pages since the users data isn't set.

This is what I have on my base.twig

new Vue({
    el: '#app',
    data: {
        hideNav: false,
        userMenuDropdown: false,

        showModal: false
    }
});

And in my users.html I have:

var UsersPage = new Vue({
    el: '.users__main',
    data: {
        search_users: '',
        users: {{ users|raw }}
    },
    computed: {
        filteredUsers,
    }
});

function filteredUsers(){
    var self = this;
    return this.users.filter(function(cust){
        return cust.first_name.toLowerCase().indexOf(self.search_users.toLowerCase())>=0;
    });
}

I'm simply trying to search for an user, everything works if I take off the first vue instance that references #app, not .users__main.

I have setup a jsfiddle to further explain the exact issue, this version (does not work) has both vue instances, one in the base.twig and the other in the user.html file, this version does not contain both instances (works).

I was messing with components for this but I wasn't able to get that going.

Body:
So, I was able to figure it out after reading the documentation, I wound up using a component with inline-template.

In my base.twig I create one and only 1 instance of Vue.

new Vue({
    el: '#app',
});

And now in my user.html file that extends the base.twig I created a component.

This wound up being the component and how it was used to have a search function working that I provided in the jsfiddle example in the question.

Vue.component('user-search', {
    data: function () {
        return {
            search_users: '',
            users: {{ users|raw }} // this here is json_encoded data from twig passed from the php framework controller
        }
    },
    computed: {
        filteredUsers,
    }
});

function filteredUsers(){
    var self = this;
    return this.users.filter(function(cust){
        return cust.first_name.toLowerCase().indexOf(self.search_users.toLowerCase())>=0;
    });
}

And to use the component(showing how to use it based on my code):

<user-search inline-template>
    <input type="text" v-model="search_users">
    <!-- rest of the code with the for loop -->
</user-search>


问:
What's the time to release the image of the imageView?
I create a UIImage and set to the property of the imageView, then I release the currentImg,
whether there is a problem in these code ?

```<code>self.currentContentImv = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, 1024, 768)];
UIImage *currentImg = [[UIImage alloc] initWithContentsOfFile: @"whatever..."]];
self.currentContentImv.image = currentImg;
[currentImg release];
</code>```

Sometimes it will be crash, so in this situation how could I write it?

Thanks very much!

答:
You can always use autorelease.

```<code>UIImage *currentImg = [[[UIImage alloc] initWithContentsOfFile: @"whatever..."] autorelease];
</code>```

Also, you should read over Apple's Memory Management Programming Guide.

Body:
I create a UIImage and set to the property of the imageView, then I release the currentImg,
whether there is a problem in these code ?

self.currentContentImv = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, 1024, 768)];
UIImage *currentImg = [[UIImage alloc] initWithContentsOfFile: @"whatever..."]];
self.currentContentImv.image = currentImg;
[currentImg release];

Sometimes it will be crash, so in this situation how could I write it?

Thanks very much!

Body:
You can always use autorelease.

UIImage *currentImg = [[[UIImage alloc] initWithContentsOfFile: @"whatever..."] autorelease];

Also, you should read over Apple's Memory Management Programming Guide.


问:
Print out an array in uppercase Java
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

```<code>package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}
</code>```

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

答:
Change

```<code>// prints out the array in lowercase
System.out.println(Arrays.toString(names10));
</code>```

to:

```<code>// prints out the array in uppercase
System.out.println(Arrays.toString(names10).toUpperCase());
</code>```

Title: Print out an array in uppercase Java

Body:
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

Body:
Change

// prints out the array in lowercase
System.out.println(Arrays.toString(names10));

to:

// prints out the array in uppercase
System.out.println(Arrays.toString(names10).toUpperCase());


问:
swift3 get the array in side closure
I would like to get the final result joblist array to use outside closure. Because I would like to setup a tableview by using Joblist array. .</p>

```<code>let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(address) { (placemarks, error) in
    if error == nil && (placemarks?.count)! > 0 {

        let location2 = placemarks?[0].location

        if let location1 = self.locationManager?.location {
            let distanceInMeters = location1.distance(from: location2!)
            let IntDis = Int(distanceInMeters)
            //print(IntDis)

            if IntDis < 40000 {

                //print(address)

                if let activityid       = infoDictionary["ActivityID"] {self.newJob.ActivityID=activityid}
                if let companyname      = infoDictionary["CompanyName"] {self.newJob.CompanyName=companyname}
                if let quantity         = infoDictionary["Quantity"] {self.newJob.Quantity=quantity}
                if let coupontitle      = infoDictionary["Title"] {self.newJob.CouponTitle=coupontitle}
                if let couponterms      = infoDictionary["Terms"] {self.newJob.CouponTerms=couponterms}
                if let expirdate        = infoDictionary["ExpirDate"] {self.newJob.ExpirDate=expirdate}
                if let contactperson    = infoDictionary["ContactPerson"] {self.newJob.ContactPerson=contactperson}
                if let tel              = infoDictionary["TEL"] {self.newJob.TEL=tel}

                self.joblist.append(self.newJob)
                //print(self.joblist)
                //self.tableView.reloadData()

            }
        }
    }
}
</code>```

答:
You can do this in two ways:

Make the joblist variable global so it can be accessed from multiple places

Use a callback, which calls a new function while passing on previously gathered data. This is especially useful when the original "data getting" proces is a network task with a delay.

Global variables:

```<code>let geoCoder = CLGeocoder()
var jobList = [AnyClass]() //make a global array
geoCoder.geocodeAddressString(address) { (placemarks, error) in
   ...filtering code ...
   joblist.append(self.newJob)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
   cell.textLabel = jobList[indexPath.row].ActivityID //or something else with the data
}
</code>```

Using a callback(simple version which doesn't pass on itself to the next function):

```<code>geoCoder.geocodeAddressString(address) { (placemarks, error) in
   ...filtering code ...
   doTableViewStuff(data: joblist)
}

func doTableViewStuff(data: [Jobs]) { //or whatever type of data
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
       cell.textLabel = data[indexPath.row].ActivityID //or something else with the data
   }
}
</code>```

Title: swift3 get the array in side closure

Body:
I would like to get the final result joblist array to use outside closure. Because I would like to setup a tableview by using Joblist array. .

let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(address) { (placemarks, error) in
    if error == nil && (placemarks?.count)! > 0 {

        let location2 = placemarks?[0].location

        if let location1 = self.locationManager?.location {
            let distanceInMeters = location1.distance(from: location2!)
            let IntDis = Int(distanceInMeters)
            //print(IntDis)

            if IntDis < 40000 {

                //print(address)

                if let activityid       = infoDictionary["ActivityID"] {self.newJob.ActivityID=activityid}
                if let companyname      = infoDictionary["CompanyName"] {self.newJob.CompanyName=companyname}
                if let quantity         = infoDictionary["Quantity"] {self.newJob.Quantity=quantity}
                if let coupontitle      = infoDictionary["Title"] {self.newJob.CouponTitle=coupontitle}
                if let couponterms      = infoDictionary["Terms"] {self.newJob.CouponTerms=couponterms}
                if let expirdate        = infoDictionary["ExpirDate"] {self.newJob.ExpirDate=expirdate}
                if let contactperson    = infoDictionary["ContactPerson"] {self.newJob.ContactPerson=contactperson}
                if let tel              = infoDictionary["TEL"] {self.newJob.TEL=tel}

                self.joblist.append(self.newJob)
                //print(self.joblist)
                //self.tableView.reloadData()

            }
        }
    }
}

Body:
You can do this in two ways:

Make the joblist variable global so it can be accessed from multiple places

Use a callback, which calls a new function while passing on previously gathered data. This is especially useful when the original "data getting" proces is a network task with a delay.

Global variables:

let geoCoder = CLGeocoder()
var jobList = [AnyClass]() //make a global array
geoCoder.geocodeAddressString(address) { (placemarks, error) in
   ...filtering code ...
   joblist.append(self.newJob)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
   cell.textLabel = jobList[indexPath.row].ActivityID //or something else with the data
}

Using a callback(simple version which doesn't pass on itself to the next function):

geoCoder.geocodeAddressString(address) { (placemarks, error) in
   ...filtering code ...
   doTableViewStuff(data: joblist)
}

func doTableViewStuff(data: [Jobs]) { //or whatever type of data
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
       cell.textLabel = data[indexPath.row].ActivityID //or something else with the data
   }
}


问:
How to nest container class in simple project with SASS?
HTML:

```<code><section>
  <div class="container"></div>
</section>
<nav>
  <div class="container"></div>
</nav>
</code>```

How to nest container class?
Probably not like this:

```<code>section {
  .container {
  }
}

nav {
 .continer {
 }
}
</code>```

Because I don't want to double style for .container.
And not like this:

```<code>.container {
  section {
  }
  nav {
  }
}
</code>```

Because container is in section, not section in container. So how?

I can use " & " but:

```<code>body {
  .container {
     section & {
     }
  }
}
</code>```

will compile to:

```<code> section body .container {
 }
</code>```

but i need:

```<code>body section .container {
}
</code>```

答:
To add styles to the container div that will display within both section and nav:

```<code>section, nav {
  .container {
      color: red;
  }
}
</code>```

which compiles to

```<code>section .container {color: red;}
nav .container {color: red;}
</code>```

Body:
HTML:

How to nest container class?
Probably not like this:

section {
  .container {
  }
}

nav {
 .continer {
 }
}

Because I don't want to double style for .container.
And not like this:

.container {
  section {
  }
  nav {
  }
}

Because container is in section, not section in container. So how?

I can use " & " but:

body {
  .container {
     section & {
     }
  }
}

will compile to:

 section body .container {
 }

but i need:

body section .container {
}

Body:
To add styles to the container div that will display within both section and nav:

section, nav {
  .container {
      color: red;
  }
}

which compiles to

section .container {color: red;}
nav .container {color: red;}


问:
Importing modules twice in python with different names
I did import the module with a name, and import it again without a name and both seems to be working fine and gives the same class type.

```<code>>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>

>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>
</code>```

How does that works in python, is that a single object points to the same reference?
Also why not that the previous name import got overwritten or removed.

I'm not sure about the terminology as well

答:
If you take a look at the disassembled code, you can see that it does load the same object. (line 2 and line 14)

```<code>>>> import dis
>>> codeObj = compile("from collections import Counter as c; from collections import Counter", "foo", "exec")
>>> dis.dis(codeObj)
  1           0 LOAD_CONST               0 (0)
              2 LOAD_CONST               1 (('Counter',))
              4 IMPORT_NAME              0 (collections)
              6 IMPORT_FROM              1 (Counter)
              8 STORE_NAME               2 (c)
             10 POP_TOP
             12 LOAD_CONST               0 (0)
             14 LOAD_CONST               1 (('Counter',))
             16 IMPORT_NAME              0 (collections)
             18 IMPORT_FROM              1 (Counter)
             20 STORE_NAME               1 (Counter)
             22 POP_TOP
             24 LOAD_CONST               2 (None)
             26 RETURN_VALUE
</code>```

And as others have mentioned, you can use id(c) == id(Counter) or c is Counter to test if they have the same reference.

Body:
I did import the module with a name, and import it again without a name and both seems to be working fine and gives the same class type.

>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>

>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>

How does that works in python, is that a single object points to the same reference?
Also why not that the previous name import got overwritten or removed.

I'm not sure about the terminology as well

Body:
If you take a look at the disassembled code, you can see that it does load the same object. (line 2 and line 14)

>>> import dis
>>> codeObj = compile("from collections import Counter as c; from collections import Counter", "foo", "exec")
>>> dis.dis(codeObj)
  1           0 LOAD_CONST               0 (0)
              2 LOAD_CONST               1 (('Counter',))
              4 IMPORT_NAME              0 (collections)
              6 IMPORT_FROM              1 (Counter)
              8 STORE_NAME               2 (c)
             10 POP_TOP
             12 LOAD_CONST               0 (0)
             14 LOAD_CONST               1 (('Counter',))
             16 IMPORT_NAME              0 (collections)
             18 IMPORT_FROM              1 (Counter)
             20 STORE_NAME               1 (Counter)
             22 POP_TOP
             24 LOAD_CONST               2 (None)
             26 RETURN_VALUE

And as others have mentioned, you can use id(c) == id(Counter) or c is Counter to test if they have the same reference.