问:
Object property returning undefined when using ternary operator
I'm building an object literal and using the if-else shorthand to set the value of one of my properties, but it keeps returning undefined and I don't understand why:

```<code>var cca = cca || {};

var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        site_title: (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle,
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
};
</code>```

When I evaluate with a break-point the evaluation returns the proper value but it's not getting saved to the property. However, I'm setting another property in a similar way (cca.language) and that's working fine.

答:
You can solve it with promises also. Take a look at this code:

var test = {
    a: 'aaa',
    b: Promise.resolve(test).then(()=>test.b = test.a)
}

async function show() {
 await test.b;
 console.log(test);
}
show();```
</div>
</div>
</p>

<p>so you would do: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var cca = cca || {};

_spPageContextInfo = { currentLanguage: 1033};

var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        site_title: Promise.resolve(cca).then(()=>
            cca.site_title = (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle),
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
};

async function show() {
 await cca.site_title;
 console.log(cca);
}
initialization();
show();</code>```

please understand that the

```<code>async function show() {
    await cca.site_title;
    console.log(cca);
}
show();
</code>```

part is just for you to be able to see the complete object as it won't be available immediately after the cca declaration due to it's now asynchronous nature.

But as this is resolved in microseconds, you can continue normally with the execution of your code and don't worry about it.

Body:
I'm building an object literal and using the if-else shorthand to set the value of one of my properties, but it keeps returning undefined and I don't understand why:

var cca = cca || {};

var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        site_title: (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle,
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
};

When I evaluate with a break-point the evaluation returns the proper value but it's not getting saved to the property. However, I'm setting another property in a similar way (cca.language) and that's working fine.

Body:
You can solve it with promises also. Take a look at this code:

var test = {
    a: 'aaa',
    b: Promise.resolve(test).then(()=>test.b = test.a)
}

async function show() {
 await test.b;
 console.log(test);
}
show();

so you would do:

var cca = cca || {};

_spPageContextInfo = { currentLanguage: 1033};

var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        site_title: Promise.resolve(cca).then(()=>
            cca.site_title = (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle),
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
};

async function show() {
 await cca.site_title;
 console.log(cca);
}
initialization();
show();

please understand that the

async function show() {
    await cca.site_title;
    console.log(cca);
}
show();

part is just for you to be able to see the complete object as it won't be available immediately after the cca declaration due to it's now asynchronous nature.

But as this is resolved in microseconds, you can continue normally with the execution of your code and don't worry about it.


来源: stackexchange

问:
Sharing constant data between views in Google Chrome extension
Suppose we have Chrome extension, that uses background page, popup page, maybe some other views and content scripts. There is some constant data relating to the subject area, that has to be accessible from all views and content scripts.

What is the best practice to share this data?

答:
As @BorisSmus mentioned, you can create a separate constants.js file that you include everywhere you need it.

For example, in your manifest.json:

```<code>"content_scripts": [
    {
        "js": ["constants.js", /* ... your other content scripts ... */]
    }
],
</code>```

And the following at the top of  on your popup and background pages:

```<code><script src="constants.js"></script>
</code>```

This also has the benefit of not resulting in issues if one of the users of constants.js accidentally modifies a variable from it, since each user has their own copy.

ContentLicense: CC BY-SA 3.0

Body:
As @BorisSmus mentioned, you can create a separate constants.js file that you include everywhere you need it.

For example, in your manifest.json:

"content_scripts": [
    {
        "js": ["constants.js", /* ... your other content scripts ... */]
    }
],

And the following at the top of <head> on your popup and background pages:

<script src="constants.js"></script>

This also has the benefit of not resulting in issues if one of the users of constants.js accidentally modifies a variable from it, since each user has their own copy.


问:
How can I centre my nav bar text using bootstrap?
Q1

I was wondering if I wanted to centre text on the navigation bar using bootstrap what code I use. I have tried using center-block. However, this didn't work for me. This is the text  I'm trying to centre
Liam Docherty's Digital Portfolio
.

Site code

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
   </head>

   <body>
      <nav class="navbar navbar-default navbar-fixed-top">
         <div class="container-fluid">
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
               <img src="http://i1126.photobucket.com/albums/l611/ldocherty1/logo1_zpsep8qps5m.png" alt="Logo design">
               <h1 class="nav-title centre-block">Liam Docherty's Digital Portfolio</h1>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
               <ul class="nav navbar-nav">
                  <li>Home
                  </li>
                  <li class="dropdown">
                     Units <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>Unit 6
                        </li>
                        <li>Unit 14
                        </li>
                        <li>Unit 7
                        </li>
                        <li>Unit 1
                        </li>
                     </ul>
                  </li>
                  <li class="dropdown">
                     About <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>About Me
                        </li>
                        <li>CV
                        </li>
                        <li>Education
                        </li>
                     </ul>
                  </li>
                  <li>Contact Me
                  </li>
               </ul>
            </div>
         </div>
      </nav>
      <div id="sections">
         <div class="section one">
            <div class="shape"></div>
            <div class="hero"></div>
            <h1 class="s1-text center-block">WELCOME TO MY</h1>
            <h1 class="s2-text center-block">PORTFOLIO</h1>
             <i class="fa fa-angle-down" style="font-size:100px;"></i>
         </div>
         <section id="contact-me" class="section two">
             <i class="fa fa-angle-up" style="font-size:100px;"></i>
      </div>
      <script>
         $(document).ready(function() {
           $('#sections').fullpage();
         });
      </script>
   </body>
</html></code>```

答:
To achieve this you need to use some tricks. Firstly you need to give your logo a width and a height. Then I have two
Liam Docherty's Digital Portfolio

 one in the brand section and one within main nav-navbar ul. For nav-navbar ul I have used hidden-xs to hide it in small screens and for brand section I have used hidden-sm hidden-lg hidden-md so that it remains hidden for all devices having screen width more than 767px.

After this use the following css--

```<code>#nav_a {
  width:25%;

  }
   #nav_img {
  width:100%;
height: 30px;
  }
@media (min-width: 768px) {
.navbar-nav.navbar-center {
position: absolute;
left: 50%;
transform: translatex(-50%);
 }
 }
</code>```

#nav_a {
      width:25%;

      }
       #nav_img {
      width:100%;
    height: 30px;
      }
 @media (min-width: 768px) {
   .navbar-nav.navbar-center {
    position: absolute;
    left: 50%;
    transform: translatex(-50%);
  }
}
      .body {
      font-family: 'Roboto', sans-serif;
      color: black;
      }
      .navbar.navbar-default {
      background-color: #FFFFFF;
      height: 10vh;
      z-index: 100;
      }
      .navbar.navbar-default ul {
      list-style-type: none;
      text-align: right;
      }
      .navbar.navbar-default ul li {
      display: inline-block;
      }
      .dropdown-menu li {
      text-align: center;
      }
      .dropdown .dropdown-menu {
      background-color: #FFFFFF;
      }
      .dropdown .dropdown-menu a {
      color: white;
      }
      .navbar.navbar-default ul li a {
      display: inline-block;
      padding: 3.5vh 8px 4px;
      color: black;
      text-decoration: none;
      font-size: 14pt;
      }
      .navbar.navbar-default ul li:after {
      content: '';
      position: absolute;
      right: 50%;
      bottom: 0;
      left: 50%;
      height: 3px;
      background-color: black;
      border-radius: 9px;
      transition: all .2s;
      }
      .nav.navbar-nav,
      .nav.navbar-nav>li {
      float: none;
      }
      .navbar.navbar-default ul li:hover:after {
      right: 0;
      left: 0;
      }
      .navbar.navbar-default ul.dropdown-menu li,
      .navbar.navbar-default ul.dropdown-menu li a {
      position: relative;
      display: block;
      }
      .section {
      min-height: 100vh;
      }
      .one {
      background-color: #FFFFFF;
      }
      .two {
      background-color: #FFFFFF;
      }
      #sections .section {
      padding-top: 50px;
      }
      .hero {
      background: url("https://static.pexels.com/photos/38892/pexels-photo-38892.jpeg") center center no-repeat;
      background-attachment: fixed;
      background-size: cover;
      width: 100%;
      max-width: 100%;
      width: 100vw;
      height: 60%;
      }
      .shape {
      border-radius: 25px;
      background: #4D5061;
      content: url(http://i1126.photobucket.com/albums/l611/ldocherty1/IMG_0730_zpsiz4dqc47.jpg);
      color: white;
      height: 300px;
      margin: auto;
      padding: 3px;
      width: 300px;
      top: 15%;
      left: 50%;
      margin-left: -150px;
      z-index: 10;
      }
      .fa-angle-down {
      color: #0000;
      bottom: 0px;
      margin: 0 auto;
      }
      .fa-angle-up {
      color: #0000;
      bottom: 0px;
      margin: 0 auto;
      }
      .s1-text {
      text-align: center;
      color: black;
      z-index: 99;
      font-size: 18pt;
      }
      .s2-text {
      text-align: center;
      color: black;
      z-index: 99;
      font-size: 18pt;
      }
      .nav-text {
      font-size: 14pt;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
   </head>

   <body>
      <nav class="navbar navbar-default navbar-fixed-top">
         <div class="container-fluid">
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
               <img id="nav_img" class="img-responsive" src="http://i1126.photobucket.com/albums/l611/ldocherty1/logo1_zpsep8qps5m.png" alt="Logo design">
               <h5 class="nav-title text-center center-block hidden-sm hidden-md hidden-lg" id="nav-center">Liam Docherty's Digital Portfolio</h5>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-center">
              <li><h5 class="nav-title text-center center-block hidden-xs ">Liam Docherty's Digital Portfolio</h5></li>
              </ul>
               <ul class="nav navbar-nav navbar-right">

                  <li>Home
                  </li>
                  <li class="dropdown">
                     Units <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>Unit 6
                        </li>
                        <li>Unit 14
                        </li>
                        <li>Unit 7
                        </li>
                        <li>Unit 1
                        </li>
                     </ul>
                  </li>
                  <li class="dropdown">
                     About <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>About Me
                        </li>
                        <li>CV
                        </li>
                        <li>Education
                        </li>
                     </ul>
                  </li>
                  <li>Contact Me
                  </li>
               </ul>
            </div>
         </div>
      </nav>
      <div id="sections">
         <div class="section one">
            <div class="shape"></div>
            <div class="hero"></div>
            <h1 class="s1-text center-block">WELCOME TO MY</h1>
            <h1 class="s2-text center-block">PORTFOLIO</h1>
             <i class="fa fa-angle-down" style="font-size:100px;"></i>
         </div>
         <section id="contact-me" class="section two">
             <i class="fa fa-angle-up" style="font-size:100px;"></i>
      </div>
      <script>
         $(document).ready(function() {
           $('#sections').fullpage();
         });
      </script>
   </body>
</html></code>```

Hope this helps!

Body:
Q1

I was wondering if I wanted to centre text on the navigation bar using bootstrap what code I use. I have tried using center-block. However, this didn't work for me. This is the text  I'm trying to centre
Liam Docherty's Digital Portfolio
.

Site code

<!DOCTYPE html>

      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               Toggle navigation

               </button>

Liam Docherty's Digital Portfolio

Home

                     Units

Unit 6

Unit 14

Unit 7

Unit 1

                     About

About Me

CV

Education

Contact Me

WELCOME TO MY

PORTFOLIO

Body:
To achieve this you need to use some tricks. Firstly you need to give your logo a width and a height. Then I have two <h5 class="nav-title text-center center-block">Liam Docherty's Digital Portfolio</h5></div> one in the brand section and one within main nav-navbar ul. For nav-navbar ul I have used hidden-xs to hide it in small screens and for brand section I have used hidden-sm hidden-lg hidden-md so that it remains hidden for all devices having screen width more than 767px.

After this use the following css--

#nav_a {
  width:25%;

  }
   #nav_img {
  width:100%;
height: 30px;
  }
@media (min-width: 768px) {
.navbar-nav.navbar-center {
position: absolute;
left: 50%;
transform: translatex(-50%);
 }
 }

#nav_a {
      width:25%;

      }
       #nav_img {
      width:100%;
    height: 30px;
      }
 @media (min-width: 768px) {
   .navbar-nav.navbar-center {
    position: absolute;
    left: 50%;
    transform: translatex(-50%);
  }
}
      .body {
      font-family: 'Roboto', sans-serif;
      color: black;
      }
      .navbar.navbar-default {
      background-color: #FFFFFF;
      height: 10vh;
      z-index: 100;
      }
      .navbar.navbar-default ul {
      list-style-type: none;
      text-align: right;
      }
      .navbar.navbar-default ul li {
      display: inline-block;
      }
      .dropdown-menu li {
      text-align: center;
      }
      .dropdown .dropdown-menu {
      background-color: #FFFFFF;
      }
      .dropdown .dropdown-menu a {
      color: white;
      }
      .navbar.navbar-default ul li a {
      display: inline-block;
      padding: 3.5vh 8px 4px;
      color: black;
      text-decoration: none;
      font-size: 14pt;
      }
      .navbar.navbar-default ul li:after {
      content: '';
      position: absolute;
      right: 50%;
      bottom: 0;
      left: 50%;
      height: 3px;
      background-color: black;
      border-radius: 9px;
      transition: all .2s;
      }
      .nav.navbar-nav,
      .nav.navbar-nav>li {
      float: none;
      }
      .navbar.navbar-default ul li:hover:after {
      right: 0;
      left: 0;
      }
      .navbar.navbar-default ul.dropdown-menu li,
      .navbar.navbar-default ul.dropdown-menu li a {
      position: relative;
      display: block;
      }
      .section {
      min-height: 100vh;
      }
      .one {
      background-color: #FFFFFF;
      }
      .two {
      background-color: #FFFFFF;
      }
      #sections .section {
      padding-top: 50px;
      }
      .hero {
      background: url("https://static.pexels.com/photos/38892/pexels-photo-38892.jpeg") center center no-repeat;
      background-attachment: fixed;
      background-size: cover;
      width: 100%;
      max-width: 100%;
      width: 100vw;
      height: 60%;
      }
      .shape {
      border-radius: 25px;
      background: #4D5061;
      content: url(http://i1126.photobucket.com/albums/l611/ldocherty1/IMG_0730_zpsiz4dqc47.jpg);
      color: white;
      height: 300px;
      margin: auto;
      padding: 3px;
      width: 300px;
      top: 15%;
      left: 50%;
      margin-left: -150px;
      z-index: 10;
      }
      .fa-angle-down {
      color: #0000;
      bottom: 0px;
      margin: 0 auto;
      }
      .fa-angle-up {
      color: #0000;
      bottom: 0px;
      margin: 0 auto;
      }
      .s1-text {
      text-align: center;
      color: black;
      z-index: 99;
      font-size: 18pt;
      }
      .s2-text {
      text-align: center;
      color: black;
      z-index: 99;
      font-size: 18pt;
      }
      .nav-text {
      font-size: 14pt;
      }

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
   </head>

   <body>
      <nav class="navbar navbar-default navbar-fixed-top">
         <div class="container-fluid">
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
               <a id="nav_a" class="navbar-brand pull-left" href=""><img id="nav_img" class="img-responsive" src="http://i1126.photobucket.com/albums/l611/ldocherty1/logo1_zpsep8qps5m.png" alt="Logo design"></a>
               <h5 class="nav-title text-center center-block hidden-sm hidden-md hidden-lg" id="nav-center">Liam Docherty's Digital Portfolio</h5>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-center">
              <li><h5 class="nav-title text-center center-block hidden-xs ">Liam Docherty's Digital Portfolio</h5></li>
              </ul>
               <ul class="nav navbar-nav navbar-right">

                  <li><a href="#">Home</a>
                  </li>
                  <li class="dropdown">
                     <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Units <span class="caret"></span></a>
                     <ul class="dropdown-menu">
                        <li><a href="#">Unit 6</a>
                        </li>
                        <li><a href="#section3">Unit 14</a>
                        </li>
                        <li><a href="#">Unit 7</a>
                        </li>
                        <li><a href="#">Unit 1</a>
                        </li>
                     </ul>
                  </li>
                  <li class="dropdown">
                     <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">About <span class="caret"></span></a>
                     <ul class="dropdown-menu">
                        <li><a href="#">About Me</a>
                        </li>
                        <li><a href="#">CV</a>
                        </li>
                        <li><a href="#">Education</a>
                        </li>
                     </ul>
                  </li>
                  <li><a href="#contact-me">Contact Me</a>
                  </li>
               </ul>
            </div>
         </div>
      </nav>
      <div id="sections">
         <div class="section one">
            <div class="shape"></div>
            <div class="hero"></div>
            <h1 class="s1-text center-block">WELCOME TO MY</h1>
            <h1 class="s2-text center-block">PORTFOLIO</h1>
            <a href="#section two"> <i class="fa fa-angle-down" style="font-size:100px;"></i></a>
         </div>
         <section id="contact-me" class="section two">
            <a href="#section one"> <i class="fa fa-angle-up" style="font-size:100px;"></i></a>
      </div>
      <script>
         $(document).ready(function() {
           $('#sections').fullpage();
         });
      </script>
   </body>
</html>

Hope this helps!


问:
How to perform a bitwise operation on floating point numbers
I tried this:

```<code>float a = 1.4123;
a = a & (1 << 3);
</code>```

I get a compiler error saying that the operand of & cannot be of type float.

When I do:

```<code>float a = 1.4123;
a = (int)a & (1 << 3);
</code>```

I get the program running. The only thing is that the bitwise operation is done on the integer representation of the number obtained after rounding off.

The following is also not allowed.

```<code>float a = 1.4123;
a = (void*)a & (1 << 3);
</code>```

I don't understand why int can be cast to void* but not float.

I am doing this to solve the problem described in Stack Overflow question How to solve linear equations using a genetic algorithm?.

答:
FWIW, there is a real use case for bit-wise operations on floating point (I just ran into it recently) - shaders written for OpenGL implementations that only support older versions of GLSL (1.2 and earlier did not have support for bit-wise operators), and where there would be loss of precision if the floats were converted to ints.

The bit-wise operations can be implemented on floating point numbers using remainders (modulo) and inequality checks.  For example:

```<code>float A = 0.625; //value to check; ie, 160/256
float mask = 0.25; //bit to check; ie, 1/4
bool result = (mod(A, 2.0 * mask) >= mask); //non-zero if bit 0.25 is on in A
</code>```

The above assumes that A is between [0..1) and that there is only one "bit" in mask to check, but it could be generalized for more complex cases.

This idea is based on some of the info found in is-it-possible-to-implement-bitwise-operators-using-integer-arithmetic

If there is not even a built-in mod function, then that can also be implemented fairly easily.  For example:

```<code>float mod(float num, float den)
{
    return num - den * floor(num / den);
}
</code>```

Body:
I tried this:

float a = 1.4123;
a = a & (1 << 3);

I get a compiler error saying that the operand of & cannot be of type float.

When I do:

float a = 1.4123;
a = (int)a & (1 << 3);

I get the program running. The only thing is that the bitwise operation is done on the integer representation of the number obtained after rounding off.

The following is also not allowed.

float a = 1.4123;
a = (void*)a & (1 << 3);

I don't understand why int can be cast to void* but not float.

I am doing this to solve the problem described in Stack Overflow question How to solve linear equations using a genetic algorithm?.

Body:
FWIW, there is a real use case for bit-wise operations on floating point (I just ran into it recently) - shaders written for OpenGL implementations that only support older versions of GLSL (1.2 and earlier did not have support for bit-wise operators), and where there would be loss of precision if the floats were converted to ints.

The bit-wise operations can be implemented on floating point numbers using remainders (modulo) and inequality checks.  For example:

float A = 0.625; //value to check; ie, 160/256
float mask = 0.25; //bit to check; ie, 1/4
bool result = (mod(A, 2.0 * mask) >= mask); //non-zero if bit 0.25 is on in A

The above assumes that A is between [0..1) and that there is only one "bit" in mask to check, but it could be generalized for more complex cases.

This idea is based on some of the info found in is-it-possible-to-implement-bitwise-operators-using-integer-arithmetic

If there is not even a built-in mod function, then that can also be implemented fairly easily.  For example:

float mod(float num, float den)
{
    return num - den * floor(num / den);
}

ContentLicense: CC BY-SA 4.0


问:
Using a loop to get all tables within a database

Please understand that I am fairly new to PhP and I might have come by the answer to my question without knowing it. If this is the case, please direct me to the correct answer.

I have a database which has multiple tables in it. Each table does have the exact same structure, as each table corresponds with a different unit within a franchise of restaurants. I am trying to create a "master" page for the franchise owner to be able to pull up all (or one) of the tables onto one page in order to view the data associated with each unit. I have tried every permeation that I could think of to get the code to work right but I keep getting errors thrown at me. The most recent error message that I am getting is "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1"

In past questions people have tried telling me that my code needs to be one way because I only include a portion of my code. This time I will include all of the code within the page that is throwing the errors.

```<code><?php
require_once('../dbconnection.php');

$tables = array($_POST["spenard"], $_POST["benson"], $_POST["eagle"],
$_POST["wasilla"], $_POST["boniface"], $_POST["dimond"], $_POST["tudor"],
$_POST["huffman"], $_POST["dtown"], $_POST["airport"], $_POST["college"],
$_POST["npole"], $_POST["kenai"], $_POST["suldotna"]);
$length = count($tables);

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Food Safety Checklist Master List</title>

<script>

</script>
</head>

<body>

<!--<table>
    ?php
        for ($i = 0; $i < $length; $i++) {?>
        <tr>
            <th>?php echo $tables[$i]; ?></th>
        </tr>
        ?php }
    ?>
    <tr>

    </tr>
</table>-->

<table>
    <tr>
        <th>Food Safety Checklist</th>
    </tr>
    <?php for ($i = 0; $i < $length; $i++) {
        mysqli_select_db($conn, $dbname);
        $query_lists = "SELECT * FROM $tables[$i]";
        $lists = mysqli_query($conn, $query_lists) or
die(mysqli_error($conn));
        $row_lists = mysqli_fetch_assoc($lists);
        $totalRows_lists = mysqli_num_rows($lists);?>
    <tr>
        <th><?php echo $row_lists[' ']; ?></th>
    </tr>
    <?php } ?>
</table>

</body>
</html>
</code>```

The code for the initiating page is:

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Food Safety Checklist Master Selection</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
</head>

<body>

<header>
    <h1>Pizza Hut Food Safety</h1>
</header>

<section>
    <div>
        <form action="mastershow.php" method="post" name="masterselect" id="masterselect">
            <table>
                <tr>
                    <th colspan="2"><h2>Stores</h2></th>
                </tr>
                <tr>
                    <th colspan="2"><input type="submit" value="Run" id="submit" name="submit"></th>
                </tr>
                <tr>
                    <td><label for="spenard">Spenard 010576</label></td>
                    <td><input name="spenard" id="spenard" type="checkbox" value="`010576`"><br/></td>
                </tr>
                <tr>
                    <td><label for="benson">Benson 011169</label></td>
                    <td><input name="benson" id="benson" type="checkbox" value="`011169`"><br/></td>
                </tr>
                <tr>
                    <td><label for="eagle">Eagle River 008181</label></td>
                    <td><input name="eagle" id="eagle" type="checkbox" value="`008181`"><br/></td>
                </tr>
                <tr>
                    <td><label for="wasilla">Wasilla 010324</label></td>
                    <td><input name="wasilla" id="wasilla" type="checkbox" value="`010324`"><br/></td>
                </tr>
                <tr>
                    <td><label for="boniface">Boniface 008615</label></td>
                    <td><input name="boniface" id="boniface" type="checkbox" value="`008615`"><br/></td>
                </tr>
                <tr>
                    <td><label for="dimond">W. Dimond 009150</label></td>
                    <td><input name="dimond" id="dimond" type="checkbox" value="`009150`"><br/></td>
                </tr>
                <tr>
                    <td><label for="tudor">Tudor 014640</label></td>
                    <td><input name="tudor" id="tudor" type="checkbox" value="`014640`"><br/></td>
                </tr>
                <tr>
                    <td><label for="huffman">Huffman 0101684</label></td>
                    <td><input name="huffman" id="huffma" type="checkbox" value="`010684`"><br/></td>
                </tr>
                <tr>
                    <td><label for="dtown">6TH AVE 011168</label></td>
                    <td><input name="dtown" id="dtwon" type="checkbox" value="`011168`"><br/></td>
                </tr>
                <tr>
                    <td><label for="airport">Airport Rd. 014215</label></td>
                    <td><input name="airport" id="airport" type="checkbox" value="`014215`"><br/></td>
                </tr>
                <tr>
                    <td><label for="college">College Rd. 008179</label></td>
                    <td><input name="college" id="college" type="checkbox" value="`008179`"><br/></td>
                </tr>
                <tr>
                    <td><label for="npole">North Pole 008339</label></td>
                    <td><input name="npole" id="npole" type="checkbox" value="`008339`"><br/></td>
                </tr>
                <tr>
                    <td><label for="kenai">Kenai 008668</label></td>
                    <td><input name="kenai" id="kenai" type="checkbox" value="`008668`"><br/></td>
                </tr>
                <tr>
                    <td><label for="suldotna">Suldotna 031574</label></td>
                    <td><input name="suldotna" id="suldotna" type="checkbox" value="`031574`"><br/></td>
                </tr>
            </table>
        </form>
    </div>
</section>

<footer>
    Designed by Greg Weiland ©2017
</footer>

</body>
</html>
</code>```

Again, I am trying to have it to where the franchise owner can "check" which stores to run the report on, and then be able to get all rows from the corresponding tables (again, each table has a name which corresponds to one of the unit numbers) that he has selected. Each table has identical structure. Thank you for any and all help

答:
it tells you that your query is wrong and it is you have a variable inside without telling it that it is a variable fix it like this

```<code>$query_lists = "SELECT * FROM '$tables[$i]'";
</code>```

edit change this because of the type array

```<code>  //see my last comment on why i do it this way
  <?php foreach ($tables as $qtables) {
            mysqli_select_db($conn, $dbname);
            $query_lists = "SELECT * FROM '$qtables'";
</code>```

Body:
Please understand that I am fairly new to PhP and I might have come by the answer to my question without knowing it. If this is the case, please direct me to the correct answer.

I have a database which has multiple tables in it. Each table does have the exact same structure, as each table corresponds with a different unit within a franchise of restaurants. I am trying to create a "master" page for the franchise owner to be able to pull up all (or one) of the tables onto one page in order to view the data associated with each unit. I have tried every permeation that I could think of to get the code to work right but I keep getting errors thrown at me. The most recent error message that I am getting is "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1"

In past questions people have tried telling me that my code needs to be one way because I only include a portion of my code. This time I will include all of the code within the page that is throwing the errors.

<?php
require_once('../dbconnection.php');

$tables = array($_POST["spenard"], $_POST["benson"], $_POST["eagle"],
$_POST["wasilla"], $_POST["boniface"], $_POST["dimond"], $_POST["tudor"],
$_POST["huffman"], $_POST["dtown"], $_POST["airport"], $_POST["college"],
$_POST["npole"], $_POST["kenai"], $_POST["suldotna"]);
$length = count($tables);

?>
<!doctype html>

<meta charset="utf-8">
<title>Food Safety Checklist Master List</title>

        Food Safety Checklist

    <?php for ($i = 0; $i < $length; $i++) {
        mysqli_select_db($conn, $dbname);
        $query_lists = "SELECT * FROM $tables[$i]";
        $lists = mysqli_query($conn, $query_lists) or
die(mysqli_error($conn));
        $row_lists = mysqli_fetch_assoc($lists);
        $totalRows_lists = mysqli_num_rows($lists);?>

        <?php echo $row_lists[' ']; ?>

    <?php } ?>

The code for the initiating page is:

<!doctype html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Food Safety Checklist Master Selection</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Pizza Hut Food Safety

        <form action="mastershow.php" method="post" name="masterselect" id="masterselect">

Stores

                    <input type="submit" value="Run" id="submit" name="submit">

                    Spenard 010576
                    <input name="spenard" id="spenard" type="checkbox" value="`010576`">

                    Benson 011169
                    <input name="benson" id="benson" type="checkbox" value="`011169`">

                    Eagle River 008181
                    <input name="eagle" id="eagle" type="checkbox" value="`008181`">

                    Wasilla 010324
                    <input name="wasilla" id="wasilla" type="checkbox" value="`010324`">

                    Boniface 008615
                    <input name="boniface" id="boniface" type="checkbox" value="`008615`">

                    W. Dimond 009150
                    <input name="dimond" id="dimond" type="checkbox" value="`009150`">

                    Tudor 014640
                    <input name="tudor" id="tudor" type="checkbox" value="`014640`">

                    Huffman 0101684
                    <input name="huffman" id="huffma" type="checkbox" value="`010684`">

                    6TH AVE 011168
                    <input name="dtown" id="dtwon" type="checkbox" value="`011168`">

                    Airport Rd. 014215
                    <input name="airport" id="airport" type="checkbox" value="`014215`">

                    College Rd. 008179
                    <input name="college" id="college" type="checkbox" value="`008179`">

                    North Pole 008339
                    <input name="npole" id="npole" type="checkbox" value="`008339`">

                    Kenai 008668
                    <input name="kenai" id="kenai" type="checkbox" value="`008668`">

                    Suldotna 031574
                    <input name="suldotna" id="suldotna" type="checkbox" value="`031574`">

        </form>

    Designed by Greg Weiland ©2017

Again, I am trying to have it to where the franchise owner can "check" which stores to run the report on, and then be able to get all rows from the corresponding tables (again, each table has a name which corresponds to one of the unit numbers) that he has selected. Each table has identical structure. Thank you for any and all help

Body:
it tells you that your query is wrong and it is you have a variable inside without telling it that it is a variable fix it like this

$query_lists = "SELECT * FROM '$tables[$i]'";

edit change this because of the type array

  //see my last comment on why i do it this way
  <?php foreach ($tables as $qtables) {
            mysqli_select_db($conn, $dbname);
            $query_lists = "SELECT * FROM '$qtables'";


问:
MatPlotLib's ion() and draw() not working
I am trying to plot figures in real time using a for loop. I have the following simple code:

```<code>import matplotlib.pyplot as plt

plt.ion()
plt.figure()
for i in range(100):
    plt.plot([i], [i], 'o')
    plt.draw()
    plt.pause(0.0001)
</code>```

This code does not show the figure until it has finished computing, which I don't want. I want it to draw the figure after every loop. If I replace plt.draw() with plt.show, multiple figures are output in real time, but I want them all to appear in the same figure. Any ideas?

EDIT:

I downloaded PyCharm with Anaconda and everything works fine. I guess it's a problem with Spyder since I tried a few different versions of it without success. If anyone has any clue what is causing this problem in Spyder, let me know!

答:
Hey I was having the same problem, I checked other questions and my issue was solved when I plugged a pause into my solution. Here's some example code that worked for me.

```<code>import matplotlib.pyplot as plt
import numpy as np
plt.ion()
x = np.arange(0, 4*np.pi, 0.1)
y = [np.sin(i) for i in x]
plt.plot(x, y, 'g-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
plt.plot(x, [i**2 for i in y], 'g-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
plt.plot(x, [i**2*i+0.25 for i in y], 'r-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
</code>```

The solution was posted here:
Matplotlib ion() and subprocesses

Body:
I am trying to plot figures in real time using a for loop. I have the following simple code:

import matplotlib.pyplot as plt

plt.ion()
plt.figure()
for i in range(100):
    plt.plot([i], [i], 'o')
    plt.draw()
    plt.pause(0.0001)

This code does not show the figure until it has finished computing, which I don't want. I want it to draw the figure after every loop. If I replace plt.draw() with plt.show, multiple figures are output in real time, but I want them all to appear in the same figure. Any ideas?

EDIT:

I downloaded PyCharm with Anaconda and everything works fine. I guess it's a problem with Spyder since I tried a few different versions of it without success. If anyone has any clue what is causing this problem in Spyder, let me know!

Body:
Hey I was having the same problem, I checked other questions and my issue was solved when I plugged a pause into my solution. Here's some example code that worked for me.

import matplotlib.pyplot as plt
import numpy as np
plt.ion()
x = np.arange(0, 4*np.pi, 0.1)
y = [np.sin(i) for i in x]
plt.plot(x, y, 'g-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
plt.plot(x, [i**2 for i in y], 'g-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
plt.plot(x, [i**2*i+0.25 for i in y], 'r-', linewidth=1.5, markersize=4)
plt.pause(0.0001)

The solution was posted here:
Matplotlib ion() and subprocesses


问:
How do I connect to MemSQL from Elixir
MemSQL is binary compatible with Mysql and uses the same drivers. However this nice-in-theory does not seem to apply when you connect from Elixir with mariaex or mysqlex.

With mariaex, I can connect fine:

but I cannot query because of the enable_binary_protocol issue:

Enabling binary protocol in memsql.cnf for the aggregator kind of works for some short queries, but not for longer ones. First, after editing memsql.cnf to include the line "enable_binary_protocol=true" and restarting the cluster using "memsql-ops memsql-restart" I checked that the parameter was indeed set:

And now some stuff works, but not others:

BTW that query works fine in the memSQL command line interface:

The mysqlex driver, meantime, does not even connect:

So I'm basically stumped. Is anybody successfully using Elixir with memSQL? If so, what's the secret ingredient?

One option might be to use an Erlang library. This one (also available on Hex) might be good but I have no idea how to call the Erlang functions from Elixir. The closest I got was successfully compiling it in iex after adding the dependency {:mysql, "~> 1.0"} to my mix.exs.

答:
I don't have any experience with MemSQL but it does look like mysql-otp prepares query statements on the client side. You can try using it like this:

```<code># Connect
{:ok, pid} = :mysql.start_link(host: 'localhost', user: 'foo', password: 'hello', database: 'test')

# Select
{:ok, columns, rows} = :mysql.query(pid, "SELECT * FROM mytable WHERE id = ?", [1])

# Transactions
result = :mysql.transaction(pid, fn ->
  :ok = :mysql.query("INSERT INTO mytable (foo) VALUES (1)")
  raise "foo"
  :ok = :mysql.query("INSERT INTO mytable (foo) VALUES (1)")
end)
</code>```

See the official Erlang/Elixir crash course for more details.

Title: How do I connect to MemSQL from Elixir

Body:
I don't have any experience with MemSQL but it does look like mysql-otp prepares query statements on the client side. You can try using it like this:

# Connect
{:ok, pid} = :mysql.start_link(host: 'localhost', user: 'foo', password: 'hello', database: 'test')

# Select
{:ok, columns, rows} = :mysql.query(pid, "SELECT * FROM mytable WHERE id = ?", [1])

# Transactions
result = :mysql.transaction(pid, fn ->
  :ok = :mysql.query("INSERT INTO mytable (foo) VALUES (1)")
  raise "foo"
  :ok = :mysql.query("INSERT INTO mytable (foo) VALUES (1)")
end)

See the official Erlang/Elixir crash course for more details.


问:
Append conditionally without filtering
I've seen many questions on this site asking how one can append an element to a selection depending on the data it would be bound to. (Here's one, for example.) All of them seem to advocate filtering the data first to remove the items for which elements shouldn't be bound.

I can't do this because filtering out items in the data would change the indices of all elements afterward, and my code depends on the indices. I realized that I could create a tuple for each item, containing a datum and its original position, and then safely filter, but I'm wondering if there's a better way.

How can I append an element depending on the data to which it would be bound without filtering the data first?

My situation specifically: I have a 2D array. Each child array is bound to a <g>, and for each element within each child array, a <path> is calculated and drawn. The <path>'s transform depends on the element's index in the child array.

For some elements within any given child array, I want no <path> to be drawn. I realize I could accomplish this without not appending a <path> (for example, by making the <path> entirely translucent), but I'm trying to cut down on the number of elements in the hierarchy.

Currently, I bind all the data to a <path>, then filter and remove certain <path>s depending on their data. This doesn't seem particularly efficient, though...

答:
As I said in my comment, one possible solution is keeping two arrays, one for appending the elements (the filtered one) and one for referencing their indices (the original one). Is that approach intensive (regarding processor resources)? It depends on your actual code and case. Sometimes, a code that seems less performant can surprisingly perform better than one that is supposed to be faster (for instance, appending elements and removing them later... browsers are normally faster manipulating arrays and objects than manipulating actual DOM elements).

Anyway, here is another approach: create your new filtered data referencing the index of each element in the original data.

For instance, in the following snippet, I have this data set:

```<code>var originalData = [16, 18, 4, 17, 12, 2, 15, 13, 8, 19, 17, 3, 8];
</code>```

We're gonna make a filtered array keeping only the values that are smaller than 10. But, before filtering, we'll create an object that holds the value and the original index:

```<code>var filteredData = originalData.map((d, i) => ({
    value: d,
    index: i
})).filter(e => e.value < 10);
</code>```

Then, you just need to access index to know the original index.

Here is the demo, click the circles:

var svg = d3.select("svg");

var originalData = [16, 18, 4, 17, 12, 2, 15, 13, 8, 19, 17, 3, 8];

var filteredData = originalData.map((d, i) => ({
  value: d,
  index: i
})).filter(e => e.value < 10);

var circles = svg.selectAll("foo")
  .data(filteredData)
  .enter()
  .append("circle")
  .attr("r", 20)
  .attr("cy", 40)
  .attr("cx", (d, i) => 40 + 60 * i)
  .attr("fill", "teal")
  .attr("cursor", "pointer")
  .on("click", function(d) {
    console.log("My original index is " + d.index)
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 20% !important;}</code>```

<svg></svg>```

Title: Append conditionally without filtering

Body:
As I said in my comment, one possible solution is keeping two arrays, one for appending the elements (the filtered one) and one for referencing their indices (the original one). Is that approach intensive (regarding processor resources)? It depends on your actual code and case. Sometimes, a code that seems less performant can surprisingly perform better than one that is supposed to be faster (for instance, appending elements and removing them later... browsers are normally faster manipulating arrays and objects than manipulating actual DOM elements).

Anyway, here is another approach: create your new filtered data referencing the index of each element in the original data.

For instance, in the following snippet, I have this data set:

var originalData = [16, 18, 4, 17, 12, 2, 15, 13, 8, 19, 17, 3, 8];

We're gonna make a filtered array keeping only the values that are smaller than 10. But, before filtering, we'll create an object that holds the value and the original index:

var filteredData = originalData.map((d, i) => ({
    value: d,
    index: i
})).filter(e => e.value < 10);

Then, you just need to access index to know the original index.

Here is the demo, click the circles:

var svg = d3.select("svg");

var originalData = [16, 18, 4, 17, 12, 2, 15, 13, 8, 19, 17, 3, 8];

var filteredData = originalData.map((d, i) => ({
  value: d,
  index: i
})).filter(e => e.value < 10);

var circles = svg.selectAll("foo")
  .data(filteredData)
  .enter()
  .append("circle")
  .attr("r", 20)
  .attr("cy", 40)
  .attr("cx", (d, i) => 40 + 60 * i)
  .attr("fill", "teal")
  .attr("cursor", "pointer")
  .on("click", function(d) {
    console.log("My original index is " + d.index)
  })

.as-console-wrapper { max-height: 20% !important;}

<script src="https://d3js.org/d3.v4.js"></script>
<svg></svg>


问:
Circle div without resizing
I've created a circle div with this line of code:

```<code>style="width: 25%; height: auto; padding-top: 25%; margin-left: 37.5%; border-radius: 50%; background-color: #00e5c9; overflow: hidden; bottom: 0;">
</code>```

However, when I add an image inside of it, it expands and thus becomes an oval. Is there a way to keep the circle as it is with no uneven expansion? I would like to add that determining the width and height with pixels is out of the picture since I'm trying to create a responsive page.

Thank you!

答:
You can use position:absolute on the img.

Example

```<code> img{
  position:absolute;
  width:200px;
  height:200px;;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%)

}
</code>```

Snippet below

#d {
  position: relative;
  width: 25%;
  height: auto;
  padding-top: 25%;
  margin-left: 37.5%;
  border-radius: 50%;
  background-color: #00e5c9;
  overflow: hidden;
  bottom: 0;
}

#d img {
  position: absolute;
  width: 100px;
  height: 100px;
  ;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="d">
  <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSzQljZiYwAlULvViQAWNnBaIz4r_61X09p2lcgZCTVrEBN4Rot"></div></code>```

Title: Circle div without resizing

Body:
I've created a circle div with this line of code:

style="width: 25%; height: auto; padding-top: 25%; margin-left: 37.5%; border-radius: 50%; background-color: #00e5c9; overflow: hidden; bottom: 0;">

However, when I add an image inside of it, it expands and thus becomes an oval. Is there a way to keep the circle as it is with no uneven expansion? I would like to add that determining the width and height with pixels is out of the picture since I'm trying to create a responsive page.

Thank you!

Body:
You can use position:absolute on the img.

Example

 img{
  position:absolute;
  width:200px;
  height:200px;;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%)

}

Snippet below

#d {
  position: relative;
  width: 25%;
  height: auto;
  padding-top: 25%;
  margin-left: 37.5%;
  border-radius: 50%;
  background-color: #00e5c9;
  overflow: hidden;
  bottom: 0;
}

#d img {
  position: absolute;
  width: 100px;
  height: 100px;
  ;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%)
}

<div id="d">
  <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSzQljZiYwAlULvViQAWNnBaIz4r_61X09p2lcgZCTVrEBN4Rot"></div>


问:
How to change size of title's text on Action Bar?
There is an ActionBar on each Android 4.0 application, and it got a title. I need to make this size less. But I don't understand how I can do it, because ActionBar doesn't provide public methods for it. Remark: I don't want to use custom views.

答:
I have followed this method to skip the creation of custom style:

Create a custom layout with required text size and

apply that to your action bar.

1) Create a layout file (titlebar.xml):

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/action_bar_title"
        android:text="@string/app_name"
        android:textColor="@color/colorPrimary"
        android:textSize="24sp" />
</LinearLayout>
</code>```

Here set your required textSize.

2) MainActivity.java

```<code>    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //bellow setSupportActionBar(toolbar);
    getSupportActionBar().setCustomView(R.layout.titlebar);
</code>```

hope this helps.

Body:
I have followed this method to skip the creation of custom style:

Create a custom layout with required text size and

apply that to your action bar.

1) Create a layout file (titlebar.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/action_bar_title"
        android:text="@string/app_name"
        android:textColor="@color/colorPrimary"
        android:textSize="24sp" />
</LinearLayout>

Here set your required textSize.

2) MainActivity.java

    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //bellow setSupportActionBar(toolbar);
    getSupportActionBar().setCustomView(R.layout.titlebar);

hope this helps.


问:
How to access items in a model with ReferenceProperty?
This is a follow up on my previous question.

I set up the models with ReferenceProperty:

```<code>class User(db.Model):
    userEmail = db.StringProperty()

class Comment(db.Model):
    user = db.ReferenceProperty(User, collection_name="comments")
    comment = db.StringProperty(multiline=True)

class Venue(db.Model):
    user = db.ReferenceProperty(User, collection_name="venues")
    venue = db.StringProperty()
</code>```

In datastore I have this entry under User:

```<code>Entity Kind: User
Entity Key: ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBUM
ID: 21
userEmail: az@example.com
</code>```

And under Venue:

```<code>Entity Kind: Venue
Entity Key: ag1oZWxsby0xLXdvcmxkcgsLEgVWZW51ZRhVDA
ID: 85
venue (string): 5 star venue
user (Key): ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBUM
User: id=21
</code>```

I am trying to display the item in hw.py like this

```<code>query = User.all()
    results = query.fetch(10)
    self.response.out.write("<html><body><ol>")
    for result in results:
        self.response.out.write("<li>")
        self.response.out.write(result.userEmail)
        self.response.out.write(result.venues)
        self.response.out.write("</li>")
    self.response.out.write("</ol></body></html>")
</code>```

This line works:

```<code>        self.response.out.write(result.userEmail)
</code>```

But this line does not work:

```<code>        self.response.out.write(result.venues)
</code>```

But as per vonPetrushev's answer result.venues should grab the venue associated with this userEmail.

Sorry if this is confusing: I am just trying to access the tables linked to the userEmail with ReferenceProperty. The linked tables are Venue and Comment. How do I access an item in Venue or in Comment? Thanks.

答:
venues is actually a query object.  So you'll need to fetch or iterate over it.

Try replacing the self.response.out.write(result.venues) line with a loop:

```<code>query = User.all()
users = query.fetch(10)
self.response.out.write("<html><body><ol>")
for user in users:
    self.response.out.write("<li>")
    self.response.out.write(user.userEmail)
    self.response.out.write("<ul>")
    # Iterate over the venues
    for venue in user.venues:
        self.response.out.write("<li>%s</li>" % venue.venue)
    self.response.out.write("</ul></li>")
self.response.out.write("</ol></body></html>")
</code>```

However, this will not scale very well.  If there are 10 users, it will run 11 queries!  Make sure you are using Appstats to look for performance issues like these.  Try to minimize the number of RPC calls you make.

A better solution might be to denormalize and store the user's email on the Venue kind.  That way you will only need one query to print the venue information and users email.

ContentLicense: CC BY-SA 2.5

Body:
This is a follow up on my previous question.

I set up the models with ReferenceProperty:

class User(db.Model):
    userEmail = db.StringProperty()

class Comment(db.Model):
    user = db.ReferenceProperty(User, collection_name="comments")
    comment = db.StringProperty(multiline=True)

class Venue(db.Model):
    user = db.ReferenceProperty(User, collection_name="venues")
    venue = db.StringProperty()

In datastore I have this entry under User:

Entity Kind: User
Entity Key: ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBUM
ID: 21
userEmail: az@example.com

And under Venue:

Entity Kind: Venue
Entity Key: ag1oZWxsby0xLXdvcmxkcgsLEgVWZW51ZRhVDA
ID: 85
venue (string): 5 star venue
user (Key): ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBUM
User: id=21

I am trying to display the item in hw.py like this

query = User.all()
    results = query.fetch(10)
    self.response.out.write("
")
    for result in results:
        self.response.out.write("
")
        self.response.out.write(result.userEmail)
        self.response.out.write(result.venues)
        self.response.out.write("
")
    self.response.out.write("
")

This line works:

        self.response.out.write(result.userEmail)

But this line does not work:

        self.response.out.write(result.venues)

But as per vonPetrushev's answer result.venues should grab the venue associated with this userEmail.

Sorry if this is confusing: I am just trying to access the tables linked to the userEmail with ReferenceProperty. The linked tables are Venue and Comment. How do I access an item in Venue or in Comment? Thanks.

Body:
venues is actually a query object.  So you'll need to fetch or iterate over it.

Try replacing the self.response.out.write(result.venues) line with a loop:

query = User.all()
users = query.fetch(10)
self.response.out.write("<html><body><ol>")
for user in users:
    self.response.out.write("<li>")
    self.response.out.write(user.userEmail)
    self.response.out.write("<ul>")
    # Iterate over the venues
    for venue in user.venues:
        self.response.out.write("<li>%s</li>" % venue.venue)
    self.response.out.write("</ul></li>")
self.response.out.write("</ol></body></html>")

However, this will not scale very well.  If there are 10 users, it will run 11 queries!  Make sure you are using Appstats to look for performance issues like these.  Try to minimize the number of RPC calls you make.

A better solution might be to denormalize and store the user's email on the Venue kind.  That way you will only need one query to print the venue information and users email.


问:
Amazon Mechanical Turk: Random Questions in One Qualification Type
I am using CreateQualificationType operation to create a new qualification type in MTurk, so that I can require this qualification test in my HITs.

Now I have a set of questions for this qualification test, but I only want MTurk workers who request this qualification test to answer just a small part of those questions, and different works answer different questions randomly. I didn't find any useful answers in AWS Document about Qualifications. Is there a method to achieve that?

答:
a piece of cake, actually.  what you need to do is create the question xml file inside a loop and then create the hit from that question xml. In the example below I hand crafted a question xml and verified that it worked on the sandbox.  then I split the question xml file into parts a,b,c corresponding to the parts that did not change, then in my loop I write the xml code to a text file.

parta

part of the question that changes, in this case the image

partb
part of the question that changes, in this case the multiple choice

partc

at the conclusion of the progress I have a valid xml file that I open and use in the create hit.  Now I know this question is about a qualification, but the idea is exactly the same.

for hit_number in range(how_many):
    print(hit_number)
    my_emotions = sample(emotion_names,5)
    my_emoji = sample(emoji_numbers,1)
    HIT_image = url on S3 is convenient>

    f_out = open('data/dynamic_question.xml', 'w')
    f_out.write(parta)
    f_out.close()

    f_out = open('data/dynamic_question.xml', 'a')
    f_out.write('    <DataURL>' + HIT_image + '</DataURL>' + '\n')
    f_out.write(partb)

    for emotion in my_emotions:
        f_out.write('          <Selection>' + '\n')
        f_out.write('            <SelectionIdentifier>' + emotion + '</SelectionIdentifier>' + '\n')
        f_out.write('            <Text>' + emotion.capitalize() + '</Text>' + '\n')
        f_out.write('          </Selection>' + '\n')

    f_out.write(partc)
    f_out.close()

    with open("data/dynamic_question.xml") as f:
        question = f.read()

    # Create the HIT
    response = client.create_hit(
```

Body:
a piece of cake, actually.  what you need to do is create the question xml file inside a loop and then create the hit from that question xml. In the example below I hand crafted a question xml and verified that it worked on the sandbox.  then I split the question xml file into parts a,b,c corresponding to the parts that did not change, then in my loop I write the xml code to a text file.

parta

part of the question that changes, in this case the image

partb
part of the question that changes, in this case the multiple choice

partc

at the conclusion of the progress I have a valid xml file that I open and use in the create hit.  Now I know this question is about a qualification, but the idea is exactly the same.

for hit_number in range(how_many):
    print(hit_number)
    my_emotions = sample(emotion_names,5)
    my_emoji = sample(emoji_numbers,1)
    HIT_image = <a url on S3 is convenient>

    f_out = open('data/dynamic_question.xml', 'w')
    f_out.write(parta)
    f_out.close()

    f_out = open('data/dynamic_question.xml', 'a')
    f_out.write('    <DataURL>' + HIT_image + '</DataURL>' + '\n')
    f_out.write(partb)

    for emotion in my_emotions:
        f_out.write('          <Selection>' + '\n')
        f_out.write('            <SelectionIdentifier>' + emotion + '</SelectionIdentifier>' + '\n')
        f_out.write('            <Text>' + emotion.capitalize() + '</Text>' + '\n')
        f_out.write('          </Selection>' + '\n')

    f_out.write(partc)
    f_out.close()

    with open("data/dynamic_question.xml") as f:
        question = f.read()

    # Create the HIT
    response = client.create_hit(


问:
How can I have null column value for a composite key column in CQL3
This may sound silly as there are no null values in SQL's composite primary key. But just want to confirm if we can have the same in CQL3?

So, we have a table like this to store wide rows:

```<code>CREATE TABLE keyspace12.colFamily1
(
  id text,
  colname text,
  colvalue blob,
  PRIMARY KEY (id,colname, colvalue)
) WITH COMPACT STORAGE
</code>```

And we have some cases where colname is null. Can I do that? If yes, then how? If NO, then what are the ways to store wide columns rows where we can have some null in first part of composite column of cassandra(As per Thrift's convention)?

The related questions are:
CQL3 and millions of columns composite key use case and Cassandra -How to create composite column name (not key) using cqlsh

答:
I needed to do the same in order to model parent/child relationships in a single table. So when I want to insert a parent then 'id' is populated and your 'colname' would be set to nil.

To do this the solution was really simple literally insert the 'colname' as empty string. I can see my select return null returned.

Body:
This may sound silly as there are no null values in SQL's composite primary key. But just want to confirm if we can have the same in CQL3?

So, we have a table like this to store wide rows:

CREATE TABLE keyspace12.colFamily1
(
  id text,
  colname text,
  colvalue blob,
  PRIMARY KEY (id,colname, colvalue)
) WITH COMPACT STORAGE

And we have some cases where colname is null. Can I do that? If yes, then how? If NO, then what are the ways to store wide columns rows where we can have some null in first part of composite column of cassandra(As per Thrift's convention)?

The related questions are:
CQL3 and millions of columns composite key use case and Cassandra -How to create composite column name (not key) using cqlsh


问:
Separating a String from a CSV file
Currently I'm letting users import a CSV-file created from Excel or Numbers. The sheet has multiple fields and I can import these without problem.

However, one of the fields looks like this:

```<code>"[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"
</code>```

How should I separate this field into a dictionary looking like this:

```<code>//[String: [[Int: String]]]

[
    "Title1": [[100: "S11"], [100: "S12"], [100:   "10"], [100:   "2"], [100:   "3"]],
    "Title2": [[300:  "50"], [300:  "90"], [300: "100a"], [300:   "D"], [300:   "E"]],
    "Title3": [[500:   "2"], [500: "112"], [500:    "6"], [500: "110"], [500: "113"]]
]
</code>```

This field is created by the user itself and this already seems to be a bit too complicated and prone to error's. Perhaps a better question would be how to format this better instead of splitting this field into the dictionary I want?

Perhaps a simplified version:

```<code>//[String: [Int: [String]]]

[
    "Title1": [100: ["S11", "S12",   "10",   "2",   "3"]],
    "Title2": [300:  ["50",  "90", "100a",   "D",   "E"]],
    "Title3": [500:   ["2", "112",    "6", "110", "113"]]
]
</code>```

Some explanation about this field:

Title: can be anything, it's the title of the nested dictionary

The key in the nested dictionary can be 100, 200, 300, 400, 500 or 600

The value in the nested dictionary is a String which forms a unique key together with they key in this nested dictionary.

This means:

```<code>100: "S11" and 200: "S11" // valid
100: "S11" and 100: "S11" // not valid
</code>```

```<code>extension String {

    // Separate alphanumeric characters
    func split(_ number: Int = 1) -> [String] {
        let number = max(number, 1)

        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { $0.characters.count > number - 1 }
    }
}

let string = "Appetizer: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3) * Main: (300: 50), (300: 90), (300: 100a), (300: D), (300: E) * Dessert: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)"

let values = string.components(separatedBy: "*").map { $0.split() }

var result: [String: [Int: [String]]] = [:]

values.forEach {
    guard let key = $0.first else { return }

    result[key] = result[key] ?? [:]

    let values = $0.dropFirst()

    let name = values.enumerated().filter { $0.0 % 2 == 0 }.map { $0.1 }
    let code = values.enumerated().filter { $0.0 % 2 != 0 }.map { $0.1 }

    zip(name, code).forEach {
        guard let category = Int($0.0) else { return }

        result[key]?[category] = (result[key]?[category] ?? []) + [$0.1]
    }
}
</code>```

This code produces the result I wanted, but it seems very ugly and it's too much dependant on the location of the values (instead of checking the values).

Any suggestion on how to do this using a much simpler and more elegant way?

答:
The following code should parse the data you've provide into a dictionary as you wanted:

```<code>    let data = "[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"

    let arr1 = data.components(separatedBy:"],")
    var dic = [String:[[String:Any]]]()
    for row1 in arr1 {
        let arr2 = row1.components(separatedBy:",")
        var key = ""
        for row2 in arr2 {
            var txt = row2.replacingOccurrences(of:" ", with:"")
            if txt.hasPrefix("[Title") {
                // First row
                txt = txt.replacingOccurrences(of:"[", with:"")
                let arr3 = txt.components(separatedBy:":")
                key = arr3[0]
                let key1 = arr3[1].replacingOccurrences(of:"(", with:"")
                let val1 = arr3[2].replacingOccurrences(of:")", with:"").replacingOccurrences(of:" ", with:"")
                dic[key] = [[key1:val1]]
            } else {
                let arr3 = row2.components(separatedBy:":")
                let key1 = arr3[0].replacingOccurrences(of:"(", with:"").replacingOccurrences(of:" ", with:"")
                let val1 = arr3[1].replacingOccurrences(of:")", with:"").replacingOccurrences(of:"]", with:"").replacingOccurrences(of:" ", with:"")
                dic[key]?.append([key1:val1])
            }
        }
    }
    print(dic)
</code>```

The above answers your first question, how do you parse the data you provided into a dictionary as you specified. The second question is a bit more complicated since I don't know enough about the data to provide a useful answer. But perhaps that is unnecessary now since the data can be split into a dictionary as required? :)

Title: Separating a String from a CSV file

Body:
Currently I'm letting users import a CSV-file created from Excel or Numbers. The sheet has multiple fields and I can import these without problem.

However, one of the fields looks like this:

"[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"

How should I separate this field into a dictionary looking like this:

//[String: [[Int: String]]]

[
    "Title1": [[100: "S11"], [100: "S12"], [100:   "10"], [100:   "2"], [100:   "3"]],
    "Title2": [[300:  "50"], [300:  "90"], [300: "100a"], [300:   "D"], [300:   "E"]],
    "Title3": [[500:   "2"], [500: "112"], [500:    "6"], [500: "110"], [500: "113"]]
]

This field is created by the user itself and this already seems to be a bit too complicated and prone to error's. Perhaps a better question would be how to format this better instead of splitting this field into the dictionary I want?

Perhaps a simplified version:

//[String: [Int: [String]]]

[
    "Title1": [100: ["S11", "S12",   "10",   "2",   "3"]],
    "Title2": [300:  ["50",  "90", "100a",   "D",   "E"]],
    "Title3": [500:   ["2", "112",    "6", "110", "113"]]
]

Some explanation about this field:

Title: can be anything, it's the title of the nested dictionary

The key in the nested dictionary can be 100, 200, 300, 400, 500 or 600

The value in the nested dictionary is a String which forms a unique key together with they key in this nested dictionary.

This means:

100: "S11" and 200: "S11" // valid
100: "S11" and 100: "S11" // not valid

extension String {

    // Separate alphanumeric characters
    func split(_ number: Int = 1) -> [String] {
        let number = max(number, 1)

        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { $0.characters.count > number - 1 }
    }
}

let string = "Appetizer: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3) * Main: (300: 50), (300: 90), (300: 100a), (300: D), (300: E) * Dessert: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)"

let values = string.components(separatedBy: "*").map { $0.split() }

var result: [String: [Int: [String]]] = [:]

values.forEach {
    guard let key = $0.first else { return }

    result[key] = result[key] ?? [:]

    let values = $0.dropFirst()

    let name = values.enumerated().filter { $0.0 % 2 == 0 }.map { $0.1 }
    let code = values.enumerated().filter { $0.0 % 2 != 0 }.map { $0.1 }

    zip(name, code).forEach {
        guard let category = Int($0.0) else { return }

        result[key]?[category] = (result[key]?[category] ?? []) + [$0.1]
    }
}

This code produces the result I wanted, but it seems very ugly and it's too much dependant on the location of the values (instead of checking the values).

Any suggestion on how to do this using a much simpler and more elegant way?

Body:
The following code should parse the data you've provide into a dictionary as you wanted:

    let data = "[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"

    let arr1 = data.components(separatedBy:"],")
    var dic = [String:[[String:Any]]]()
    for row1 in arr1 {
        let arr2 = row1.components(separatedBy:",")
        var key = ""
        for row2 in arr2 {
            var txt = row2.replacingOccurrences(of:" ", with:"")
            if txt.hasPrefix("[Title") {
                // First row
                txt = txt.replacingOccurrences(of:"[", with:"")
                let arr3 = txt.components(separatedBy:":")
                key = arr3[0]
                let key1 = arr3[1].replacingOccurrences(of:"(", with:"")
                let val1 = arr3[2].replacingOccurrences(of:")", with:"").replacingOccurrences(of:" ", with:"")
                dic[key] = [[key1:val1]]
            } else {
                let arr3 = row2.components(separatedBy:":")
                let key1 = arr3[0].replacingOccurrences(of:"(", with:"").replacingOccurrences(of:" ", with:"")
                let val1 = arr3[1].replacingOccurrences(of:")", with:"").replacingOccurrences(of:"]", with:"").replacingOccurrences(of:" ", with:"")
                dic[key]?.append([key1:val1])
            }
        }
    }
    print(dic)

The above answers your first question, how do you parse the data you provided into a dictionary as you specified. The second question is a bit more complicated since I don't know enough about the data to provide a useful answer. But perhaps that is unnecessary now since the data can be split into a dictionary as required? :)


问:
if an a link contain something in the href change the href to this
i want to check if the href contains 'coming-soon' if it does change the href to go to my products page:

```<code>$('a[href$="coming-soon"]').attr('href', '/products.aspx');
</code>```

cant work this out.

答:
Your selector is currently any anchor tag whose href ends with coming-soon. The contains selector is *=:

```<code>$('a[href*="coming-soon"]').attr('href', '/products.aspx');
</code>```

See http://api.jquery.com/attribute-contains-selector/

If this isn't the problem, ensure the code is ran when the DOM is loaded; by wrapping the code in the $(document).ready()

```<code>$(document).ready(function () {
    $('a[href*="coming-soon"]').attr('href', '/products.aspx');
});
</code>```

Body:
i want to check if the href contains 'coming-soon' if it does change the href to go to my products page:

$('a[href$="coming-soon"]').attr('href', '/products.aspx');

cant work this out.

Body:
Your selector is currently any anchor tag whose href ends with coming-soon. The contains selector is *=:

$('a[href*="coming-soon"]').attr('href', '/products.aspx');

See http://api.jquery.com/attribute-contains-selector/

If this isn't the problem, ensure the code is ran when the DOM is loaded; by wrapping the code in the $(document).ready()

$(document).ready(function () {
    $('a[href*="coming-soon"]').attr('href', '/products.aspx');
});


问:
Why is my boolean returning an integer?
I'm fairly new to the programming world and I had a school assignment to create a simple program containing an if loop.
Basically, I want my code to return true if a is greater than 18, and false if a is less than 18. I also want a to increase by one each time canTakeRoadtest returns false. When I run my code all I get is

"I am 0 years old.

I can take my road test. 0"

I'm wondering why bool canTakeRoadtest is returning an integer, and why a isn't incrementing. Any help would be appreciated and I apologize for the simple question but we all start somewhere!

My coding environment is Eclipse Neon if it makes any difference.

```<code>#include <iostream>

using namespace std;

int main() {
//Local Variables
    int a = 0;
    bool canTakeRoadtest = false;
//If Loop
    if (a >= 18) {
        canTakeRoadtest = true;
        cout << "I'm ready!\n";
    } else {
        canTakeRoadtest = false;
        cout << "I am " << a << " years old.\n";
        cout << "I can take my road test. " << canTakeRoadtest << endl;
        a++;

    }

    //return 0;

}
</code>```

答:
Use boolalpha. By default bool values are integers, boolaplpha sets the bool flag to output its textual representation

http://www.cplusplus.com/reference/ios/boolalpha/

Or you can just change your cout statement.

```<code>if (a >= 18) {
    canTakeRoadtest = true;
    cout << "I'm ready!\n";
} else {
    canTakeRoadtest = false;
    cout << "I am " << a << " years old.\n";
    cout << "I can take my road test. false" << endl;
    a++;
}
</code>```

Title: Why is my boolean returning an integer?

Body:
I'm fairly new to the programming world and I had a school assignment to create a simple program containing an if loop.
Basically, I want my code to return true if a is greater than 18, and false if a is less than 18. I also want a to increase by one each time canTakeRoadtest returns false. When I run my code all I get is

"I am 0 years old.

I can take my road test. 0"

I'm wondering why bool canTakeRoadtest is returning an integer, and why a isn't incrementing. Any help would be appreciated and I apologize for the simple question but we all start somewhere!

My coding environment is Eclipse Neon if it makes any difference.

#include <iostream>

using namespace std;

int main() {
//Local Variables
    int a = 0;
    bool canTakeRoadtest = false;
//If Loop
    if (a >= 18) {
        canTakeRoadtest = true;
        cout << "I'm ready!\n";
    } else {
        canTakeRoadtest = false;
        cout << "I am " << a << " years old.\n";
        cout << "I can take my road test. " << canTakeRoadtest << endl;
        a++;

    }

    //return 0;

}

Body:
Use boolalpha. By default bool values are integers, boolaplpha sets the bool flag to output its textual representation

http://www.cplusplus.com/reference/ios/boolalpha/

Or you can just change your cout statement.

if (a >= 18) {
    canTakeRoadtest = true;
    cout << "I'm ready!\n";
} else {
    canTakeRoadtest = false;
    cout << "I am " << a << " years old.\n";
    cout << "I can take my road test. false" << endl;
    a++;
}


问:
Spark to read a big file as inputstream
I know spark built in method can have partition and read huge chunk of file and distributed as rdd using textfile.
However, i am reading this in a customized encrytped filessytem which spark does not support by nature. One way i can think of is to read an inputstream instead and loads multiple lines and distributed to executor. Keep reading until all file is loaded. So no executor will blow up due to out of memory error. Is that possible to do this in spark?</p>

答:
you can try lines.take(n) for different n to find the limit of your cluster.

or

```<code>spark.readStream.option("sep", ";").csv("filepath.csv")
</code>```

Title: Spark to read a big file as inputstream

Body:
you can try lines.take(n) for different n to find the limit of your cluster.

or

spark.readStream.option("sep", ";").csv("filepath.csv")


问:
C: char* is not modifiable
I am writing a really basic trim function in my code:

```<code>void trim(char a[]){
    if (a[0] == 'a')
    {
        a += 4;
    }else{
        a += 5;
    }
}

int main(){
    char a[] = "add abc";
    char* b = "find abc";
    trim(a);
    trim(b);
    printf("a=%s, b=%s\n", a,b);
}
</code>```

For the trim function, it is supposed to return just "abc" for both a and b. And I checked in gdb, trim(a) worked perfectly inside the trim function. At end of the trim function, a is pointing to "abc". However, when it get returned back to the main function, a became "add abc" again.

Need some help from the community. Really appreciate!!!

答:
```<code>char* trim(char* a){
    if (a[0] == 'a')
    {
        a += 4;
    }else{
        a += 5;
    }
    return a;
}

int main(){
    char a[] = "add abc";
    char* b = "find abc";
    char* c = trim(a);
    char* d = trim(b);
    printf("a=%s, b=%s\n", c,d);
}
</code>```

This will work after I change the return type of trim and catch the retuen value in main function using two new pointer.

Title: C: char* is not modifiable

Body:
I am writing a really basic trim function in my code:

void trim(char a[]){
    if (a[0] == 'a')
    {
        a += 4;
    }else{
        a += 5;
    }
}

int main(){
    char a[] = "add abc";
    char* b = "find abc";
    trim(a);
    trim(b);
    printf("a=%s, b=%s\n", a,b);
}

For the trim function, it is supposed to return just "abc" for both a and b. And I checked in gdb, trim(a) worked perfectly inside the trim function. At end of the trim function, a is pointing to "abc". However, when it get returned back to the main function, a became "add abc" again.

Need some help from the community. Really appreciate!!!

Body:
char* trim(char* a){
    if (a[0] == 'a')
    {
        a += 4;
    }else{
        a += 5;
    }
    return a;
}

int main(){
    char a[] = "add abc";
    char* b = "find abc";
    char* c = trim(a);
    char* d = trim(b);
    printf("a=%s, b=%s\n", c,d);
}

This will work after I change the return type of trim and catch the retuen value in main function using two new pointer.


问:
When using play FakeRequest is it better practice specifying the uri?
Using FakeRequest to test my controller, in what case should I specify uri?

this is my current fake request:

```<code>val request = FakeRequest(POST, "/").withHeaders("Content-type" -> "application/json").withBody(someBody)
</code>```

答:
You can use the Play reverse router, so if you change your route or put an http.context in the application.conf you won't have problems.

This also has the advantage that you can specify query parameters or path parameters when calling the controller.

https://www.playframework.com/documentation/2.5.x/ScalaRouting#reverse-routing

```<code>routes.Application.hello("Bob")
</code>```

Body:
Using FakeRequest to test my controller, in what case should I specify uri?

this is my current fake request:

val request = FakeRequest(POST, "/").withHeaders("Content-type" -> "application/json").withBody(someBody)

Body:
You can use the Play reverse router, so if you change your route or put an http.context in the application.conf you won't have problems.

This also has the advantage that you can specify query parameters or path parameters when calling the controller.

https://www.playframework.com/documentation/2.5.x/ScalaRouting#reverse-routing

routes.Application.hello("Bob")


问:
Random number generation with random operators
I am new to android development and currently working on a simple app which, among other things, needs to generate random numbers with random operators (+, -, *, /) every time. I have a "generate" button which is supposed to give different questions every time it is pressed. I know how to generate random numbers, but I don't know how to generate the random operators so that the question is different every time. I tried using a switch statement but not successful so far (or I'm missing code in it). Can anyone help? Thanks in advance.

Here is the code i have thus far:

private void goGenerate() {

```<code>    num1 = (int)(Math.random()*10) + 1;
    num2 = (int)(Math.random()*10) + 1;
    generate();
}

private void generate() {
    StringBuilder equation = new StringBuilder();
    goGenerate();

    operator = (int)(Math.random() *4 ) + 1;

    equation.append(num1);
    if(operator == 1) {
        equation.append("+");
        result = num1 + num2;
    }
    else if(operator == 2) {
        equation.append("-");
        result = num1-num2;
    }
    else if(operator == 3) {
        equation.append("*");
        result = num1 * num2;
    }
    else if(operator == 4) {
        equation.append("/");
        while((num1 % num2 != 0) && (num1 < num2)) {
            generate();
        }
        result = num1 / num2;
    }

    textViewOperation.setText(operator);
</code>```

答:
Make two random routines, one for your number and one, restricted to 0-3, where you associate each of the possible numbers (0 to 3) to an operator. Then it's done. Good luck.

EDIT (this works):

```<code>int operator, num1, num2, result;
StringBuilder equation;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView tv1 = (TextView) findViewById(R.id.tv1);
    tv1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            generate();
            tv1.setText(String.valueOf(result));
        }
    });

}

private Integer generate() {

    equation = new StringBuilder();
    num1 = (int)(Math.random()*10) + 1;
    num2 = (int)(Math.random()*10) + 1;

    operator = new Random().nextInt(4);

    equation.append(num1);
    if (operator == 1) {
        equation.append("+");
        result = num1 + num2;
    } else if (operator == 2) {
        equation.append("-");
        result = num1 - num2;
    } else if (operator == 3) {
        equation.append("*");
        result = num1 * num2;
    } else if (operator == 4) {
        equation.append("/");
        while ((num1 % num2 != 0) && (num1 < num2)) {
            generate();
        }
        result = num1 / num2;
    }
    return result;
}}
</code>```

Body:
I am new to android development and currently working on a simple app which, among other things, needs to generate random numbers with random operators (+, -, *, /) every time. I have a "generate" button which is supposed to give different questions every time it is pressed. I know how to generate random numbers, but I don't know how to generate the random operators so that the question is different every time. I tried using a switch statement but not successful so far (or I'm missing code in it). Can anyone help? Thanks in advance.

Here is the code i have thus far:

private void goGenerate() {

    num1 = (int)(Math.random()*10) + 1;
    num2 = (int)(Math.random()*10) + 1;
    generate();
}

private void generate() {
    StringBuilder equation = new StringBuilder();
    goGenerate();

    operator = (int)(Math.random() *4 ) + 1;

    equation.append(num1);
    if(operator == 1) {
        equation.append("+");
        result = num1 + num2;
    }
    else if(operator == 2) {
        equation.append("-");
        result = num1-num2;
    }
    else if(operator == 3) {
        equation.append("*");
        result = num1 * num2;
    }
    else if(operator == 4) {
        equation.append("/");
        while((num1 % num2 != 0) && (num1 < num2)) {
            generate();
        }
        result = num1 / num2;
    }

    textViewOperation.setText(operator);

Body:
Make two random routines, one for your number and one, restricted to 0-3, where you associate each of the possible numbers (0 to 3) to an operator. Then it's done. Good luck.

EDIT (this works):

int operator, num1, num2, result;
StringBuilder equation;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView tv1 = (TextView) findViewById(R.id.tv1);
    tv1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            generate();
            tv1.setText(String.valueOf(result));
        }
    });

}

private Integer generate() {

    equation = new StringBuilder();
    num1 = (int)(Math.random()*10) + 1;
    num2 = (int)(Math.random()*10) + 1;

    operator = new Random().nextInt(4);

    equation.append(num1);
    if (operator == 1) {
        equation.append("+");
        result = num1 + num2;
    } else if (operator == 2) {
        equation.append("-");
        result = num1 - num2;
    } else if (operator == 3) {
        equation.append("*");
        result = num1 * num2;
    } else if (operator == 4) {
        equation.append("/");
        while ((num1 % num2 != 0) && (num1 < num2)) {
            generate();
        }
        result = num1 / num2;
    }
    return result;
}}


问:
JSON object shows as Null. Why?
This is the class Database:

```<code>namespace vVvBot.Model
{
    public class Database
    {
        public List<CustomCommand> CustomCommands { get; set; }
        public List<CustomEvent> CustomEvents { get; set; }
    }
}
</code>```

This is the class for CustomEvent:

```<code>namespace vVvBot.Model
{
    public class CustomEvent
    {
        public string Name { get; set; }
        public bool Enabled { get; set; }
        public List<CustomCommand> Commands { get; set; }
    }
}
</code>```

This is the class CustomCommand:

```<code>namespace vVvBot.Model
{
    public class CustomCommand
    {
        public string Keyword { get; set; }
        public CommandType Type { get; set; }
        public string Message { get; set; }
        public bool Enabled { get; set; }
    }
}
</code>```

This is the class where I deserialize and serialize the Database object

```<code>namespace vVvBot.Data
{
    public class FileJsonContext
    {
        public Database ReadToObject(string fileName)
        {
            dynamic jsonData = File.ReadAllText(fileName);

            return JsonConvert.DeserializeObject<Database>(jsonData) ?? new Database();
        }

        public void ObjectToFile(string fileName, Database database)
        {
            dynamic jsonData = JsonConvert.SerializeObject(database, Formatting.Indented);

            File.WriteAllText(fileName, jsonData);
        }
    }
}
</code>```

In the file with the issue, this is where I instantiate Database:

```<code>private Database _database;
public Database Database => _database ?? (_database = JsonContext.ReadToObject("Commands.txt"));
</code>```

The line with the issue is:

```<code>var messageindex = Database.CustomEvents[index].Commands.FindLastIndex(x => x.Type == CommandType.Welcome);
</code>```

It tries to complete the line but immediately returns because its comes back with null. There is a List in the custom events that should call the customcommand list so I can access the object. Not sure why it comes back to NULL.

The Json File includes:

```<code>{
  "CustomCommands": [
    {
      "Keyword": "Hello",
      "Type": 0,
      "Message": "World",
      "Enabled": true
    },
    {
      "Keyword": "Test",
      "Type": 0,
      "Message": "test",
      "Enabled": true
    },
    {
      "Keyword": "greeting",
      "Type": 3,
      "Message": "this isnt a test ",
      "Enabled": true
    },
    {
      "Keyword": "leaving",
      "Type": 4,
      "Message": "Sorry to see you go ",
      "Enabled": true
    },
    {
      "Keyword": "faq",
      "Type": 1,
      "Message": "This is a FAQ TEST ",
      "Enabled": true
    },
    {
      "Keyword": "Hi",
      "Type": 0,
      "Message": "Hilo ",
      "Enabled": false
    },
    {
      "Keyword": "Hi",
      "Type": 0,
      "Message": "Hilo ",
      "Enabled": false
    }
  ],
  "CustomEvents": [
    {
      "Name": "greeting",
      "Enabled": true
    },
    {
      "Name": "leaving",
      "Enabled": true
    }
  ]
}
</code>```

答:
i had this problem a long time ago and i thought the problem was from Unicode.
so i wrote a function for this . you can use it :

```<code>    List<T> ToJson<T>(byte[] byteArray) where T : new()
    {

    MemoryStream stream = new MemoryStream(byteArray);

    JsonSerializer se = new JsonSerializer();

    StreamReader re = new StreamReader(stream);
    JsonTextReader reader = new JsonTextReader(re);
        return se.Deserialize<List<T>>(reader);
     }
</code>```

and i use this function Like this:
    ToJson(data.ToArray());

data is a MemoryStream.

Title: JSON object shows as Null. Why?

Body:
This is the class Database:

namespace vVvBot.Model
{
    public class Database
    {
        public List<CustomCommand> CustomCommands { get; set; }
        public List<CustomEvent> CustomEvents { get; set; }
    }
}

This is the class for CustomEvent:

namespace vVvBot.Model
{
    public class CustomEvent
    {
        public string Name { get; set; }
        public bool Enabled { get; set; }
        public List<CustomCommand> Commands { get; set; }
    }
}

This is the class CustomCommand:

namespace vVvBot.Model
{
    public class CustomCommand
    {
        public string Keyword { get; set; }
        public CommandType Type { get; set; }
        public string Message { get; set; }
        public bool Enabled { get; set; }
    }
}

This is the class where I deserialize and serialize the Database object

namespace vVvBot.Data
{
    public class FileJsonContext
    {
        public Database ReadToObject(string fileName)
        {
            dynamic jsonData = File.ReadAllText(fileName);

            return JsonConvert.DeserializeObject<Database>(jsonData) ?? new Database();
        }

        public void ObjectToFile(string fileName, Database database)
        {
            dynamic jsonData = JsonConvert.SerializeObject(database, Formatting.Indented);

            File.WriteAllText(fileName, jsonData);
        }
    }
}

In the file with the issue, this is where I instantiate Database:

private Database _database;
public Database Database => _database ?? (_database = JsonContext.ReadToObject("Commands.txt"));

The line with the issue is:

var messageindex = Database.CustomEvents[index].Commands.FindLastIndex(x => x.Type == CommandType.Welcome);

It tries to complete the line but immediately returns because its comes back with null. There is a List in the custom events that should call the customcommand list so I can access the object. Not sure why it comes back to NULL.

The Json File includes:

{
  "CustomCommands": [
    {
      "Keyword": "Hello",
      "Type": 0,
      "Message": "World",
      "Enabled": true
    },
    {
      "Keyword": "Test",
      "Type": 0,
      "Message": "test",
      "Enabled": true
    },
    {
      "Keyword": "greeting",
      "Type": 3,
      "Message": "this isnt a test ",
      "Enabled": true
    },
    {
      "Keyword": "leaving",
      "Type": 4,
      "Message": "Sorry to see you go ",
      "Enabled": true
    },
    {
      "Keyword": "faq",
      "Type": 1,
      "Message": "This is a FAQ TEST ",
      "Enabled": true
    },
    {
      "Keyword": "Hi",
      "Type": 0,
      "Message": "Hilo ",
      "Enabled": false
    },
    {
      "Keyword": "Hi",
      "Type": 0,
      "Message": "Hilo ",
      "Enabled": false
    }
  ],
  "CustomEvents": [
    {
      "Name": "greeting",
      "Enabled": true
    },
    {
      "Name": "leaving",
      "Enabled": true
    }
  ]
}

Body:
i had this problem a long time ago and i thought the problem was from Unicode.
so i wrote a function for this . you can use it :

    List<T> ToJson<T>(byte[] byteArray) where T : new()
    {

    MemoryStream stream = new MemoryStream(byteArray);

    JsonSerializer se = new JsonSerializer();

    StreamReader re = new StreamReader(stream);
    JsonTextReader reader = new JsonTextReader(re);
        return se.Deserialize<List<T>>(reader);
     }

and i use this function Like this:
    ToJson(data.ToArray());

data is a MemoryStream.