问:
Disabled input works wrong in Firefox
I have an input which sets to disabled when some condtition implements.
For example i have input with default value 20.

<input type='number' id='main' value='20'>

And i have added to oninput event folowing code:

```<code>var input=document.getElementById('main');
input.oninput=function(){
  if(input.value>20){
  input.disabled=true;
  }
}
</code>```

Totally when you mousedown on increase button,the value will increment before you mouseup.

In Chrome the value stops at 21 as expected.

Try here:https://jsfiddle.net/u0obL5h2/3/

答:
Pretty strange behaviour from firefox i guess.
The input.disabled is fired before the input resets the mouseup event.
So my solution which works in chrome and firefox is this:

```<code>var input=document.getElementById('main');
input.onmouseup = function() {
  if(input.value>20){
    input.disabled=true;
  }
}
</code>```

Try it here:
https://codepen.io/anon/pen/MdqOjM

Title: Disabled input works wrong in Firefox

Body:
I have an input which sets to disabled when some condtition implements.
For example i have input with default value 20.

<input type='number' id='main' value='20'>

And i have added to oninput event folowing code:

var input=document.getElementById('main');
input.oninput=function(){
  if(input.value>20){
  input.disabled=true;
  }
}

Totally when you mousedown on increase button,the value will increment before you mouseup.

In Chrome the value stops at 21 as expected.

Try here:https://jsfiddle.net/u0obL5h2/3/

Body:
Pretty strange behaviour from firefox i guess.
The input.disabled is fired before the input resets the mouseup event.
So my solution which works in chrome and firefox is this:

var input=document.getElementById('main');
input.onmouseup = function() {
  if(input.value>20){
    input.disabled=true;
  }
}

Try it here:
https://codepen.io/anon/pen/MdqOjM


来源: stackexchange

问:
How to remove first chracter from the string and store the same into new column in Pandas?
I have a column name called Student name and each row has four or five student names -- like this John mills, Tim Harry, Alex win, Kate marry... I want to take the first two student names and store into a new column called Student 1 and Student 2. Names have been separated from comma.

I created a function and i can able to extract first student name . result storing into my dataframe called student_0

```<code>def find_student(df2):
for i in range(2):
df2[f"student name_{i}"] = [x.split(',')[i] for x in df2["student name"]]
return df2
</code>```

```<code>new_df = find_student(df2)
</code>```

df2 is my dataframe name

I AM NOT GETTING SECOND STUDENT NAME. PLEASE ADVISE

答:
Use pandas functionality(str and split), you don't need to write a function.

df = [["John mills, Tim Harry, Alex win, Kate marry"],
      ["Brando XI, James Caan, Richard S. Castellano"],
      ["Heath Ledger,Aaron Eckhart, Michael Caine"]]

df2 = pd.DataFrame(df)
df2.columns = ['Student_Name']

df2['student name_1'] = df2.Student_Name.str.split(",").str[0]
df2['student name_2'] = df2.Student_Name.str.split(",").str[1]
```

ContentLicense: CC BY-SA 4.0

Body:
I have a column name called Student name and each row has four or five student names -- like this John mills, Tim Harry, Alex win, Kate marry... I want to take the first two student names and store into a new column called Student 1 and Student 2. Names have been separated from comma.

I created a function and i can able to extract first student name . result storing into my dataframe called student_0

def find_student(df2):
for i in range(2):
df2[f"student name_{i}"] = [x.split(',')[i] for x in df2["student name"]]
return df2

new_df = find_student(df2)

df2 is my dataframe name

I AM NOT GETTING SECOND STUDENT NAME. PLEASE ADVISE


问:
Why are .innerHTML problems not an issue when using JQuery().html()?
I worked out any single instance of document.getElementById("MyID").innerHTML = "A value" in this Javascript World Clock guide causes Wordpress Admin not to load completely and breaks various areas of the Wordpress admin interface.

I solved it by replacing each instance with jQuery("#MyID").html("A value")) which appears to work fine. What is causing .innerHTML to fail miserably but not JQuery().html()?

答:
This is likely the pertinent part of the jQuery source:

```<code>try {
    for ( var i = 0, l = this.length; i < l; i++ ) {
        // Remove element nodes and prevent memory leaks
        if ( this[i].nodeType === 1 ) {
            jQuery.cleanData( this[i].getElementsByTagName("*") );
            this[i].innerHTML = value;
        }
    }

    // If using innerHTML throws an exception, use the fallback method
} catch(e) {
    this.empty().append( value );
}
</code>```

Note that it handles exceptions thrown.

See it for yourself in 1.5.2.

ContentLicense: CC BY-SA 3.0

Body:
This is likely the pertinent part of the jQuery source:

try {
    for ( var i = 0, l = this.length; i < l; i++ ) {
        // Remove element nodes and prevent memory leaks
        if ( this[i].nodeType === 1 ) {
            jQuery.cleanData( this[i].getElementsByTagName("*") );
            this[i].innerHTML = value;
        }
    }

    // If using innerHTML throws an exception, use the fallback method
} catch(e) {
    this.empty().append( value );
}

Note that it handles exceptions thrown.

See it for yourself in 1.5.2.


问:
How can i fix the dropdown menu when i scroll down on phone it goes away
On Windows small screen it works but on phone it goes away, I tried so many things but I can't find something to fix, or way to go around.

https://meedia-testomgeving.nu/index.html

I have followed a guides. and some youtube video's but it didnt work. About navigation menu. I don't know what kind of code I used it some time ago.

HTML

```<code><!doctype html>
<html>
<header>
<nav id="cssmenu">
<div class="logo"><img src="Meedia Producten PC & Hardware/Background/Home Page&Favicon&Footer/Meedia LOGO.png"></div>
<div id="head-mobile"></div>
<div class="button-nav"></div>
<ul>
<li class="active"><a href="index.html">HOME</a></li>
<li><a href="Over ons.html">OVER ONS</a>
   <ul>
       <li><a href="Voor Ouders.html" target="">Voor Ouders</a></li>
         <ul>
         </ul>
      </li>
             <li><a href="Voor Hulpverleners.html" target="">Voor Hulpverleners</a></li>
         <ul>
         </ul>
       </li>
   </ul>
</li>
<li><a href="Meedoen met meedia.html">MEEDOEN MET MEEDIA</a>
   <ul>
       <li><a href="ICT & Multimedia.html" target="">ICT & Multimedia</a></li>
         <ul>
         </ul>
      </li>
           <li><a href="Fashion & Lifestyle.html" target="">Fashion & Lifestyle</a></li>
         <ul>
         </ul>
      </li>

             <li><a href="Onderwijs Ondersteuning.html" target="">Onderwijs Ondersteuning</a></li>
         <ul>
         </ul>
       </li>
   </ul>
</li>
<li><a href="Producten.html">PRODUCTEN</a>
   <ul>
      <li><a href="PC & Hardware.html" target="">PC & Hardware</a>
         <ul>
            <li><a href="Meedia Market PC.html" target="_blank">PC</a></li>
            <li><a href="Meedia Market Laptop.html" target="_blank">Laptop</a></li>
            <li><a href="Meedia Market Monitoren.html" target="_blank">Monitoren</a></li>
            <li><a href="Meedia Market Randapparatuur.html" target="_blank">Randapparatuur</a></li>
            <li><a href="Meedia Market Hardware.html" target="_blank">Hardware</a></li>
            <li><a href="Meedia Market Onderdelen.html" target="_blank">Onderdelen</a></li>
            <li><a href="Meedia Market Netwerk.html" target="_blank">Netwerk</a></li>
            <li><a href="Meedia Market Printers.html" target="_blank">Printers</a></li>
         </ul>
      </li>
      <li><a href="Market Fashion & Lifestyle.html">Fashion & LifeStyle</a>
         <ul>
            <li><a href="Meedia Market Kasten.html" target="_blank">Kasten</a></li>
            <li><a href="Meedia Market Lampen.html" target="_blank">Lampen</a></li>
            <li><a href="Meedia Market Manden.html" target="_blank">Manden</a></li>
            <li><a href="Meedia Market Stoelen.html" target="_blank">Stoelen</a></li>
            <li><a href="Meedia Market Iets aan de wand.html" target="_blank">iets aan de Wand</a></li>
            <li><a href="Meedia Market sign borden.html" target="_blank">Sign Borden</a></li>
            <li><a href="Meedia Market Boekjes.html" target="_blank">Boekjes</a></li>
            <li><a href="Meedia Market Kleding.html" target="_blank">Kleding</a></li>
         </ul>
       </li>
   </ul>
</li>
<li><a href="Nieuws.html" target="">NIEUWS</a></li>
<li><a href="Foto's.html" target="">FOTO'S</a></li>
<li><a href="Contact.html">CONTACT</a>

  <ul>
       <li><a href="Contactformulier.html" target="">Contactformulier</a></li>
         <ul>
         </ul>
      </li>
         <ul>
         </ul>
      </li>
</ul>
</nav>

</header>
</code>```

CSS

```<code>*{margin:0;padding:0;text-decoration:none}
body{background:url(Images/.jpg)}
header{position:relative;width:100%;background:#333;}
.logo{position:relative;z-index:123;padding:10px;font:18px verdana;color:#31a3dd;float:left;width:19%}
.logo a{color:#31a3dd;}
nav{position:relative;width:1010px;margin:0 auto;}
#cssmenu,#cssmenu ul,#cssmenu ul li,#cssmenu ul li a,#cssmenu #head-mobile{border:0;list-style:none;line-height:1;display:block;position:relative;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
#cssmenu:after,#cssmenu > ul:after{content:".";display:block;clear:both;visibility:hidden;line-height:0;height:0}
#cssmenu #head-mobile{display:none}
#cssmenu{font-family:sans-serif;background:#333}
#cssmenu > ul > li{float:left}
#cssmenu > ul > li > a{padding:17px;font-size:12px;letter-spacing:1px;text-decoration:none;color:#FFFFFF;font-weight:700;}
#cssmenu > ul > li:hover > a,#cssmenu ul li.active a{color:#fff}
#cssmenu > ul > li:hover,#cssmenu ul li.active:hover,#cssmenu ul li.active,#cssmenu ul li.has-sub.active:hover{background:#31a3dd!important;-webkit-transition:background .3s ease;-ms-transition:background .3s ease;transition:background .3s ease;}
#cssmenu > ul > li.has-sub > a{padding-right:30px}
#cssmenu > ul > li.has-sub > a:after{position:absolute;top:22px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu > ul > li.has-sub > a:before{position:absolute;top:19px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu > ul > li.has-sub:hover > a:before{top:23px;height:0}
#cssmenu ul ul{position:absolute;left:-9999px}
#cssmenu ul ul li{height:0;-webkit-transition:all .25s ease;-ms-transition:all .25s ease;background:#333;transition:all .25s ease}
#cssmenu ul ul li:hover{}
#cssmenu li:hover > ul{left:auto}
#cssmenu li:hover > ul > li{height:35px}
#cssmenu ul ul ul{margin-left:100%;top:0}
#cssmenu ul ul li a{border-bottom:1px solid rgba(150,150,150,0.15);padding:11px 15px;width:170px;font-size:12px;text-decoration:none;color:#FFFFFF;font-weight:400;}
#cssmenu ul ul li:last-child > a,#cssmenu ul ul li.last-item > a{border-bottom:0}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li a:hover{color:#fff}
#cssmenu ul ul li.has-sub > a:after{position:absolute;top:16px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu ul ul li.has-sub > a:before{position:absolute;top:13px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu ul ul > li.has-sub:hover > a:before{top:17px;height:0}
#cssmenu ul ul li.has-sub:hover,#cssmenu ul li.has-sub ul li.has-sub ul li:hover{background:#363636;}
#cssmenu ul ul ul li.active a{border-left:1px solid #333}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active> a{border-top:1px solid #333}

@media screen and (max-width:1000px){
.logo{position:absolute;top:0;left: 0;width:100%;height:46px;text-align:center;padding:10px 0 0 0 ;float:none}
.logo2{display:none}
nav{width:100%;}
#cssmenu{width:100%}
#cssmenu ul{width:100%;display:none}
#cssmenu ul li{width:100%;border-top:1px solid #444}
#cssmenu ul li:hover{background:#363636;}
#cssmenu ul ul li,#cssmenu li:hover > ul > li{height:auto}
#cssmenu ul li a,#cssmenu ul ul li a{width:100%;border-bottom:0}
#cssmenu > ul > li{float:none}
#cssmenu ul ul li a{padding-left:25px}
#cssmenu ul ul li{background:#333!important;}
#cssmenu ul ul li:hover{background:#363636!important}
#cssmenu ul ul ul li a{padding-left:35px}
#cssmenu ul ul li a{color:#FFFFFF;background:none}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li.active > a{color:#fff}
#cssmenu ul ul,#cssmenu ul ul ul{position:relative;left:0;width:100%;margin:0;text-align:left}
#cssmenu > ul > li.has-sub > a:after,#cssmenu > ul > li.has-sub > a:before,#cssmenu ul ul > li.has-sub > a:after,#cssmenu ul ul > li.has-sub > a:before{display:none}
#cssmenu #head-mobile{display:block;padding:23px;color:#FFFFFF;font-size:12px;font-weight:700}
.button-nav{width:55px;height:46px;position:absolute;right:0;top:0;cursor:pointer;z-index: 12399994;}
.button-nav:after{position:absolute;top:22px;right:20px;display:block;height:4px;width:20px;border-top:2px solid #FFFFFF;border-bottom:2px solid #FFFFFF;content:''}
.button-nav:before{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;position:absolute;top:16px;right:20px;display:block;height:2px;width:20px;background:#FFFFFF;content:''}
.button-nav.menu-opened:after{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;top:23px;border:0;height:2px;width:19px;background:#fff;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg)}
.button-nav.menu-opened:before{top:23px;background:#fff;width:19px;-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);-o-transform:rotate(-45deg);transform:rotate(-45deg)}
#cssmenu .submenu-button-nav{position:absolute;z-index:99;right:0;top:0;display:block;border-left:1px solid #444;height:46px;width:46px;cursor:pointer}
#cssmenu .submenu-button-nav.submenu-opened{background:#262626}
#cssmenu ul ul .submenu-button-nav{height:34px;width:34px}
#cssmenu .submenu-button-nav:after{position:absolute;top:22px;right:19px;width:8px;height:2px;display:block;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:after{top:15px;right:13px}
#cssmenu .submenu-button-nav.submenu-opened:after{background:#fff}
#cssmenu .submenu-button-nav:before{position:absolute;top:19px;right:22px;display:block;width:2px;height:8px;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:before{top:12px;right:16px}
#cssmenu .submenu-button-nav.submenu-opened:before{display:none}
#cssmenu ul ul ul li.active a{border-left:none}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active > a{border-top:none}
}

#cssmenu{
z-index: 1000;
position:relative;
}

#cssmnu {
  opacity: 1.1;
}
</code>```

JQuery

```<code>(function($) {
$.fn.menumaker = function(options) {
 var cssmenu = $(this), settings = $.extend({
   format: "dropdown",
   sticky: false
 }, options);
 return this.each(function() {
   $(this).find(".button-nav").on('click', function(){
     $(this).toggleClass('menu-opened');
     var mainmenu = $(this).next('ul');
     if (mainmenu.hasClass('open')) {
       mainmenu.slideToggle().removeClass('open');
     }
     else {
       mainmenu.slideToggle().addClass('open');
       if (settings.format === "dropdown") {
         mainmenu.find('ul').show();
       }
     }
   });
   cssmenu.find('li ul').parent().addClass('has-sub');
multiTg = function() {
     cssmenu.find(".has-sub").prepend('<span class="submenu-button-nav"></span>');
     cssmenu.find('.submenu-button-nav').on('click', function() {
       $(this).toggleClass('submenu-opened');
       if ($(this).siblings('ul').hasClass('open')) {
         $(this).siblings('ul').removeClass('open').slideToggle();
       }
       else {
         $(this).siblings('ul').addClass('open').slideToggle();
       }
     });
   };
   if (settings.format === 'multitoggle') multiTg();
   else cssmenu.addClass('dropdown');
   if (settings.sticky === true) cssmenu.css('position', 'fixed');
resizeFix = function() {
  var mediasize = 1000;
     if ($( window ).width() > mediasize) {
       cssmenu.find('ul').show();
     }
     if ($(window).width() <= mediasize) {
       cssmenu.find('ul').hide().removeClass('open');
     }
   };
   resizeFix();
   return $(window).on('resize', resizeFix);
 });
  };
})(jQuery);

(function($){
$(document).ready(function(){
$("#cssmenu").menumaker({
   format: "multitoggle"
});
});
})(jQuery);

</code>```

Thanks already

答:
$(".open button").click(function(){
  $("ul").slideToggle();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  margin:0;
  padding:0;
}
nav{
  width:100%;
    background:purple;
padding: 10px 0px;

}
.container{
  margin:0 100px ;
}
.flex{
    display:flex;
  flex-wrap:wrap;
}
nav ul {
  display:flex;
  flex-wrap:wrap;
  list-style-type:none;
}
nav ul li {
  margin: 0 20px;
  color:white;
  font-size:20px;
}
.open{
  margin-left:auto;
  display:none;
}
@media(max-width:768px){
  nav{
    position:fixed;
    top:0;
    left:0;
  }
  nav ul {
    width:100%;
    display:block;
    display:none;
    text-align:center;
  }
  nav ul li{
    margin:10px 0px;
  }
  .open{
  display:block;
}
}

.content{
  width:100%;
  height:2000px;
}</code>```

<button>show</button>

home

about

contanct

```

this is sticky nav bar for small screen!
adding fixed position for media query !

Body:
On Windows small screen it works but on phone it goes away, I tried so many things but I can't find something to fix, or way to go around.

https://meedia-testomgeving.nu/index.html

I have followed a guides. and some youtube video's but it didnt work. About navigation menu. I don't know what kind of code I used it some time ago.

HTML

<!doctype html>

HOME

OVER ONS

Voor Ouders

Voor Hulpverleners

MEEDOEN MET MEEDIA

ICT & Multimedia

Fashion & Lifestyle

Onderwijs Ondersteuning

PRODUCTEN

PC & Hardware

PC

Laptop

Monitoren

Randapparatuur

Hardware

Onderdelen

Netwerk

Printers

Fashion & LifeStyle

Kasten

Lampen

Manden

Stoelen

iets aan de Wand

Sign Borden

Boekjes

Kleding

NIEUWS

FOTO'S

CONTACT

Contactformulier

CSS

*{margin:0;padding:0;text-decoration:none}
body{background:url(Images/.jpg)}
header{position:relative;width:100%;background:#333;}
.logo{position:relative;z-index:123;padding:10px;font:18px verdana;color:#31a3dd;float:left;width:19%}
.logo a{color:#31a3dd;}
nav{position:relative;width:1010px;margin:0 auto;}
#cssmenu,#cssmenu ul,#cssmenu ul li,#cssmenu ul li a,#cssmenu #head-mobile{border:0;list-style:none;line-height:1;display:block;position:relative;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
#cssmenu:after,#cssmenu > ul:after{content:".";display:block;clear:both;visibility:hidden;line-height:0;height:0}
#cssmenu #head-mobile{display:none}
#cssmenu{font-family:sans-serif;background:#333}
#cssmenu > ul > li{float:left}
#cssmenu > ul > li > a{padding:17px;font-size:12px;letter-spacing:1px;text-decoration:none;color:#FFFFFF;font-weight:700;}
#cssmenu > ul > li:hover > a,#cssmenu ul li.active a{color:#fff}
#cssmenu > ul > li:hover,#cssmenu ul li.active:hover,#cssmenu ul li.active,#cssmenu ul li.has-sub.active:hover{background:#31a3dd!important;-webkit-transition:background .3s ease;-ms-transition:background .3s ease;transition:background .3s ease;}
#cssmenu > ul > li.has-sub > a{padding-right:30px}
#cssmenu > ul > li.has-sub > a:after{position:absolute;top:22px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu > ul > li.has-sub > a:before{position:absolute;top:19px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu > ul > li.has-sub:hover > a:before{top:23px;height:0}
#cssmenu ul ul{position:absolute;left:-9999px}
#cssmenu ul ul li{height:0;-webkit-transition:all .25s ease;-ms-transition:all .25s ease;background:#333;transition:all .25s ease}
#cssmenu ul ul li:hover{}
#cssmenu li:hover > ul{left:auto}
#cssmenu li:hover > ul > li{height:35px}
#cssmenu ul ul ul{margin-left:100%;top:0}
#cssmenu ul ul li a{border-bottom:1px solid rgba(150,150,150,0.15);padding:11px 15px;width:170px;font-size:12px;text-decoration:none;color:#FFFFFF;font-weight:400;}
#cssmenu ul ul li:last-child > a,#cssmenu ul ul li.last-item > a{border-bottom:0}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li a:hover{color:#fff}
#cssmenu ul ul li.has-sub > a:after{position:absolute;top:16px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu ul ul li.has-sub > a:before{position:absolute;top:13px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu ul ul > li.has-sub:hover > a:before{top:17px;height:0}
#cssmenu ul ul li.has-sub:hover,#cssmenu ul li.has-sub ul li.has-sub ul li:hover{background:#363636;}
#cssmenu ul ul ul li.active a{border-left:1px solid #333}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active> a{border-top:1px solid #333}

@media screen and (max-width:1000px){
.logo{position:absolute;top:0;left: 0;width:100%;height:46px;text-align:center;padding:10px 0 0 0 ;float:none}
.logo2{display:none}
nav{width:100%;}
#cssmenu{width:100%}
#cssmenu ul{width:100%;display:none}
#cssmenu ul li{width:100%;border-top:1px solid #444}
#cssmenu ul li:hover{background:#363636;}
#cssmenu ul ul li,#cssmenu li:hover > ul > li{height:auto}
#cssmenu ul li a,#cssmenu ul ul li a{width:100%;border-bottom:0}
#cssmenu > ul > li{float:none}
#cssmenu ul ul li a{padding-left:25px}
#cssmenu ul ul li{background:#333!important;}
#cssmenu ul ul li:hover{background:#363636!important}
#cssmenu ul ul ul li a{padding-left:35px}
#cssmenu ul ul li a{color:#FFFFFF;background:none}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li.active > a{color:#fff}
#cssmenu ul ul,#cssmenu ul ul ul{position:relative;left:0;width:100%;margin:0;text-align:left}
#cssmenu > ul > li.has-sub > a:after,#cssmenu > ul > li.has-sub > a:before,#cssmenu ul ul > li.has-sub > a:after,#cssmenu ul ul > li.has-sub > a:before{display:none}
#cssmenu #head-mobile{display:block;padding:23px;color:#FFFFFF;font-size:12px;font-weight:700}
.button-nav{width:55px;height:46px;position:absolute;right:0;top:0;cursor:pointer;z-index: 12399994;}
.button-nav:after{position:absolute;top:22px;right:20px;display:block;height:4px;width:20px;border-top:2px solid #FFFFFF;border-bottom:2px solid #FFFFFF;content:''}
.button-nav:before{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;position:absolute;top:16px;right:20px;display:block;height:2px;width:20px;background:#FFFFFF;content:''}
.button-nav.menu-opened:after{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;top:23px;border:0;height:2px;width:19px;background:#fff;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg)}
.button-nav.menu-opened:before{top:23px;background:#fff;width:19px;-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);-o-transform:rotate(-45deg);transform:rotate(-45deg)}
#cssmenu .submenu-button-nav{position:absolute;z-index:99;right:0;top:0;display:block;border-left:1px solid #444;height:46px;width:46px;cursor:pointer}
#cssmenu .submenu-button-nav.submenu-opened{background:#262626}
#cssmenu ul ul .submenu-button-nav{height:34px;width:34px}
#cssmenu .submenu-button-nav:after{position:absolute;top:22px;right:19px;width:8px;height:2px;display:block;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:after{top:15px;right:13px}
#cssmenu .submenu-button-nav.submenu-opened:after{background:#fff}
#cssmenu .submenu-button-nav:before{position:absolute;top:19px;right:22px;display:block;width:2px;height:8px;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:before{top:12px;right:16px}
#cssmenu .submenu-button-nav.submenu-opened:before{display:none}
#cssmenu ul ul ul li.active a{border-left:none}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active > a{border-top:none}
}

#cssmenu{
z-index: 1000;
position:relative;
}

#cssmnu {
  opacity: 1.1;
}

JQuery

(function($) {
$.fn.menumaker = function(options) {
 var cssmenu = $(this), settings = $.extend({
   format: "dropdown",
   sticky: false
 }, options);
 return this.each(function() {
   $(this).find(".button-nav").on('click', function(){
     $(this).toggleClass('menu-opened');
     var mainmenu = $(this).next('ul');
     if (mainmenu.hasClass('open')) {
       mainmenu.slideToggle().removeClass('open');
     }
     else {
       mainmenu.slideToggle().addClass('open');
       if (settings.format === "dropdown") {
         mainmenu.find('ul').show();
       }
     }
   });
   cssmenu.find('li ul').parent().addClass('has-sub');
multiTg = function() {
     cssmenu.find(".has-sub").prepend('');
     cssmenu.find('.submenu-button-nav').on('click', function() {
       $(this).toggleClass('submenu-opened');
       if ($(this).siblings('ul').hasClass('open')) {
         $(this).siblings('ul').removeClass('open').slideToggle();
       }
       else {
         $(this).siblings('ul').addClass('open').slideToggle();
       }
     });
   };
   if (settings.format === 'multitoggle') multiTg();
   else cssmenu.addClass('dropdown');
   if (settings.sticky === true) cssmenu.css('position', 'fixed');
resizeFix = function() {
  var mediasize = 1000;
     if ($( window ).width() > mediasize) {
       cssmenu.find('ul').show();
     }
     if ($(window).width() <= mediasize) {
       cssmenu.find('ul').hide().removeClass('open');
     }
   };
   resizeFix();
   return $(window).on('resize', resizeFix);
 });
  };
})(jQuery);

(function($){
$(document).ready(function(){
$("#cssmenu").menumaker({
   format: "multitoggle"
});
});
})(jQuery);

Thanks already

Body:
$(".open button").click(function(){
  $("ul").slideToggle();
})

*{
  margin:0;
  padding:0;
}
nav{
  width:100%;
    background:purple;
padding: 10px 0px;

}
.container{
  margin:0 100px ;
}
.flex{
    display:flex;
  flex-wrap:wrap;
}
nav ul {
  display:flex;
  flex-wrap:wrap;
  list-style-type:none;
}
nav ul li {
  margin: 0 20px;
  color:white;
  font-size:20px;
}
.open{
  margin-left:auto;
  display:none;
}
@media(max-width:768px){
  nav{
    position:fixed;
    top:0;
    left:0;
  }
  nav ul {
    width:100%;
    display:block;
    display:none;
    text-align:center;
  }
  nav ul li{
    margin:10px 0px;
  }
  .open{
  display:block;
}
}

.content{
  width:100%;
  height:2000px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div class="container flex">
      <div class="open"><button>show</button>
          </div>
  <ul>
    <li>home</li>
     <li>about</li>
     <li>contanct</li>
  </ul>
</div>

  </nav>
<div class="content"></div>

this is sticky nav bar for small screen!
adding fixed position for media query !


问:
Running a Python function for a specific duration
Total sleep time should be 60 secs and each check should be in 5 secs interval.
How should I use count variable to trace the count of the total execution

```<code>
def test(a):
    count=0
    while True:
        if a < 10:
            print("ok")
            return True
        count = count+1
        time.sleep(5)

        if(count == 12):
            return False

print(test(a=40))
</code>```

the while loop should stop executing after 60 secs and return false, the each check interval is 5 secs. I am confused that where should I increment the count, before time.sleep(5) or after time.sleep(5). what will be the solution to see that the time.sleep is been executed for 12 times and it has been 60 secs of waiting and return false

答:
```<code>import time
def test(a):
    count=0
    while True:
        if a < 10:
            print("ok")
            return True
        count = count+1
        time.sleep(5)

        if(count == 12):
            return False

print ("Start : %s" % time.ctime())
print(test(a=40))
print ("End : %s" % time.ctime())[enter image description here][1]
</code>```

Body:
Total sleep time should be 60 secs and each check should be in 5 secs interval.
How should I use count variable to trace the count of the total execution

def test(a):
    count=0
    while True:
        if a < 10:
            print("ok")
            return True
        count = count+1
        time.sleep(5)

        if(count == 12):
            return False

print(test(a=40))

the while loop should stop executing after 60 secs and return false, the each check interval is 5 secs. I am confused that where should I increment the count, before time.sleep(5) or after time.sleep(5). what will be the solution to see that the time.sleep is been executed for 12 times and it has been 60 secs of waiting and return false


问:
How to copy and paste data from SAP to excel?
I saved my script and connected it to VBA, then I want to copy my local SAP data into an external Excel file.

```<code> Sub FOS()
 If Not IsObject(App) Then
 Set SapGuiAuto = GetObject("SAPGUI")
 Set App = SapGuiAuto.GetScriptingEngine
 End If
 ...
 session.findById("wnd[0]").maximize
 session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87011964"
 ...
 session.findById("wnd[0]/tbar[1]/btn[19]").press
 session.findById("wnd[0]/usr/chkPA_XGBAF").Selected = True
 session.findById("wnd[0]/usr/chkPA_XGBAF").SetFocus
 session.findById("wnd[0]/tbar[1]/btn[8]").press

 End Sub()
</code>```

I want to automate an extraction and thus copy my data and transfer them to a very specific excel file thanks to a VBA macro.

答:
When an ALV Grid Control has been selected, you could try the following.

for example:

```<code>...
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/tbar[1]/btn[31]").press

'for the German SAP version
'SAP_Workbook = "Tabelle von ALV (1)"

'for the English SAP version (?)
SAP_Workbook = "Worksheet in ALVXXL01 (1)"

EXCEL_Path = "c:\tmp\"
myWorkbook = "Report.xlsx"

Set xclwbk = Application.Workbooks.Item(SAP_Workbook)

Application.Visible = True
Application.DisplayAlerts = False

xclwbk.SaveAs Filename:=EXCEL_Path & myWorkbook, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

Set xclwbk = Nothing
'Application.Wait (Now + TimeValue("0:00:02"))
session.findById("wnd[0]/tbar[0]/btn[3]").press
Application.DisplayAlerts = True
...
End Sub
</code>```

Regards, ScriptMan

Body:
I saved my script and connected it to VBA, then I want to copy my local SAP data into an external Excel file.

 Sub FOS()
 If Not IsObject(App) Then
 Set SapGuiAuto = GetObject("SAPGUI")
 Set App = SapGuiAuto.GetScriptingEngine
 End If
 ...
 session.findById("wnd[0]").maximize
 session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87011964"
 ...
 session.findById("wnd[0]/tbar[1]/btn[19]").press
 session.findById("wnd[0]/usr/chkPA_XGBAF").Selected = True
 session.findById("wnd[0]/usr/chkPA_XGBAF").SetFocus
 session.findById("wnd[0]/tbar[1]/btn[8]").press

 End Sub()

I want to automate an extraction and thus copy my data and transfer them to a very specific excel file thanks to a VBA macro.

Body:
When an ALV Grid Control has been selected, you could try the following.

for example:

...
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/tbar[1]/btn[31]").press

'for the German SAP version
'SAP_Workbook = "Tabelle von ALV (1)"

'for the English SAP version (?)
SAP_Workbook = "Worksheet in ALVXXL01 (1)"

EXCEL_Path = "c:\tmp\"
myWorkbook = "Report.xlsx"

Set xclwbk = Application.Workbooks.Item(SAP_Workbook)

Application.Visible = True
Application.DisplayAlerts = False

xclwbk.SaveAs Filename:=EXCEL_Path & myWorkbook, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

Set xclwbk = Nothing
'Application.Wait (Now + TimeValue("0:00:02"))
session.findById("wnd[0]/tbar[0]/btn[3]").press
Application.DisplayAlerts = True
...
End Sub

Regards, ScriptMan


问:
DevOps Stages To Deploy
I have a question about how we should perform the deployment of applications through automation (DevOps). I have seen examples where when doing a pull request to the master branch two environments QA and Production are deployed and I have also seen other examples where only deployed to Production and no longer the UAT environment. Is there any good practice that tells you what the ideal scenario is? Personally I see the procedure of double deployment unnecessary when doing the pull to master, because we assume that for this your application previously passed through a quality environment and was tested correctly otherwise it would not be going to master.

I include two images to try to graph more or less what I mean.

(source: microsoft.com)

答:
Is there any good practice that tells you what the ideal scenario is?

I am afraid that should be hard for us to tell you the good practice what the ideal scenario is.

Whether we deploy to different phases in parallel depends on the actual needs of our project.

As we know, each stage represents one deployment target, though that target could be a physical or virtual server, a groups of servers, or any other legitimate physical or virtual deployment target. For example, if we build a pipeline, and we have to deploy it two or more environment, like windows, MAC. In this case, we should create two or more stage in parallel.

On the other hand, if we need more testing for the build result before we deploy the pipeline to the Production or Development stage, in this case, we need deploy to the QA stage before the Production or Development stage.

You can check the Define your multi-stage continuous deployment (CD) pipeline for some details.

If I do not understand your problem correctly, please let me know for free.

Hope this helps.

Title: DevOps Stages To Deploy


问:
Counting the Number of Capital Letters in Each Row in [R]
I am working in R and I have a column with various upper case and lower case letters in each row. I am trying to count the number of uppercase letters in each row and create a column that shows that number. My column looks like this(just with a lot more rows in the whole data set):

gctaggggggatggttactactGtgctatggactac

gGaagggacggttactaCgTtatggactac

gcGaggggattggcttac

Is there an easy way to create a column that list the number of upper case letters in each row. Thank you.

答:
```<code>using str_count:

t <- c("gctaggggggatggttactactGtgctatggactac", "gGaagggacggttactaCgTtatggactac", "gcGaggggattggcttac")

str_count(t, "[A-Z]")
</code>```


问:
Decimal numbers get round up while formatting python
Here is what I have tried:

```<code>>>> pi = 3.14159265
>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.1f') #print 3.1
'3.1'
>>> format(pi, '.10f') #print 3.1415926500, more precision than the original
'3.1415926500'
>>> format(pi, '.5f') #print 3.14159, more precision than the original
'3.14159'
>>> format(pi, '.4f')
'3.1416'
</code>```

The concern part is this:

```<code>>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.4f')
'3.1416'
</code>```

Where I was expecting to have 3.1415, I am getting 3.1416. Please suggest me.

The SO is showing these 2 links:

http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate

http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary

But these are not the one I am looking for.

答:
I'm not sure what kind of suggestion you want, but here's a way to truncate a number to a given number of decimal places:</p>

```<code>pi = 3.14159265

def truncate(v, places):
    return int(v * 10**places) / 10**places

print(truncate(pi, 3))  # -> 3.141
print(truncate(pi, 4))  # -> 3.1415
</code>```

Body:
Here is what I have tried:

>>> pi = 3.14159265
>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.1f') #print 3.1
'3.1'
>>> format(pi, '.10f') #print 3.1415926500, more precision than the original
'3.1415926500'
>>> format(pi, '.5f') #print 3.14159, more precision than the original
'3.14159'
>>> format(pi, '.4f')
'3.1416'

The concern part is this:

>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.4f')
'3.1416'

Where I was expecting to have 3.1415, I am getting 3.1416. Please suggest me.

The SO is showing these 2 links:

http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate

http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary

But these are not the one I am looking for.

Body:
I'm not sure what kind of suggestion you want, but here's a way to truncate a number to a given number of decimal places:

pi = 3.14159265

def truncate(v, places):
    return int(v * 10**places) / 10**places

print(truncate(pi, 3))  # -> 3.141
print(truncate(pi, 4))  # -> 3.1415


问:
Regarding deleting array of dynamic objects
How to delete the array of dynamic objects created in this following snippet?

I tried to go through some previous answers in the forum, but none could point answer for me.

```<code>#include <iostream>
struct Card{int x;};
int main()
{
    std::vector<Card*> S;
    for (int i = 0; i < 3; i++)
    {
        Card* o = new Card;
        o->x = i;
        S.push_back(o);
    }

    for (auto a : S)
        std::cout << "Opening from the container " << a->x << '\n';

//delete o; --------> How to delete the array of objects???
return 0;
}
</code>```

答:
By looping through the vector and calling delete:

```<code>for(auto& elem : S)
{
  delete elem;
}
</code>```

Also, It's a good habit to range-loop over a container using (const) auto& instead of auto to prevent copies.

Also also, since you're using range-based for loops that means you have access to smart pointers so in reality you shouldn't be calling delete at all nor storing raw pointers.

Either store actual objects in the vector or store smart pointers like std::unique_ptr.

Body:
How to delete the array of dynamic objects created in this following snippet?

I tried to go through some previous answers in the forum, but none could point answer for me.

#include <iostream>
struct Card{int x;};
int main()
{
    std::vector<Card*> S;
    for (int i = 0; i < 3; i++)
    {
        Card* o = new Card;
        o->x = i;
        S.push_back(o);
    }

    for (auto a : S)
        std::cout << "Opening from the container " <x << '\n';

//delete o; --------> How to delete the array of objects???
return 0;
}

Body:
By looping through the vector and calling delete:

for(auto& elem : S)
{
  delete elem;
}

Also, It's a good habit to range-loop over a container using (const) auto& instead of auto to prevent copies.

Also also, since you're using range-based for loops that means you have access to smart pointers so in reality you shouldn't be calling delete at all nor storing raw pointers.

Either store actual objects in the vector or store smart pointers like std::unique_ptr.


答:
Use "onchange" in place of "oninput".
Hope it will help.</p>

```<code>var input=document.getElementById('main');
input.onchange=function(){
  if(input.value>20){
  input.disabled=true;
  }
}
</code>```

Title: Disabled input works wrong in Firefox

Body:
Use "onchange" in place of "oninput".
Hope it will help.

var input=document.getElementById('main');
input.onchange=function(){
  if(input.value>20){
  input.disabled=true;
  }
}


问:
Can we use angularJS string interpolation ( {{}}) in jquery html function
I want to use angularJs string interpolation inside Jquery html function

```<code>$('#existingScoresForWeek').html("<p>{{1 + 1}}</p>");
</code>```

The above line of code is not printing Result as 2

```<code><div data-ng-app="myApp"  ng-controller="myCtrl">
<p id="existingScoresForWeek"></p>
<button ng-click="myFunc()">sub</button>

</div>

<script>

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
$scope.myFunc= function(){
    ScoreScreenersSave();
};
function ScoreScreenersSave() {
    $('#existingScoresForWeek').html("<p>{{1 + 1}}</p>");
}

});
</script>
</code>```

Actual Result: {{1 + 1}}
Expected Result : 2

答:
Use $compile to compile your html string.
See below:

```<code>var app = angular.module("myApp",[]);
app.controller("myCtrl", function($scope, $compile) {
  $scope.myFunc= function(){
     ScoreScreenersSave();
  };
  function ScoreScreenersSave() {
     $('#existingScoresForWeek').html($compile("<p>{{1 + 1}}</p>")($scope));
  }
});
</code>```

Hope it helps!

Body:
I want to use angularJs string interpolation inside Jquery html function

$('#existingScoresForWeek').html("
{{1 + 1}}
");

The above line of code is not printing Result as 2

<button ng-click="myFunc()">sub</button>

Actual Result: {{1 + 1}}
Expected Result : 2

Body:
Use $compile to compile your html string.
See below:

var app = angular.module("myApp",[]);
app.controller("myCtrl", function($scope, $compile) {
  $scope.myFunc= function(){
     ScoreScreenersSave();
  };
  function ScoreScreenersSave() {
     $('#existingScoresForWeek').html($compile("<p>{{1 + 1}}</p>")($scope));
  }
});

Hope it helps!


问:
Laravel: An unsupported attribute was designated on the PDO object. MSSQL on Ubuntu
My Ubuntu vagrant Laravel Homestead set up has been configured to connect to MSSQL. Randomly it's starting throwing the following error on every query going to the MSSQL database (on a Windows server).

Any ideas? I can't find much info re:this available on Google.

I restarted PHP and confirmed SQLSRV modules are loaded.

```<code>SQLSTATE[IMSSP]: An unsupported attribute was designated on the PDO object. (SQL: select top 10 * from [orders] where [ordertype] = SO order by [orderdate] desc)
</code>```

答: Check this issue report PDO::ATTR_PERSISTENT is not supported. Also they are reporting problems with PDO::ATTR_ERRMODE so check your connection for these two parameters.

Body:
My Ubuntu vagrant Laravel Homestead set up has been configured to connect to MSSQL. Randomly it's starting throwing the following error on every query going to the MSSQL database (on a Windows server).

Any ideas? I can't find much info re:this available on Google.

I restarted PHP and confirmed SQLSRV modules are loaded.

SQLSTATE[IMSSP]: An unsupported attribute was designated on the PDO object. (SQL: select top 10 * from [orders] where [ordertype] = SO order by [orderdate] desc)


问:
Elasticsearch starts and stops immediately
I'm trying to start Elasticsearch process from Services. It starts, then stops immediately.

Laptop with Windows 10.
I've tried different versions, I've tried .msi and installing from zip.
Now I'm stuck with elasticsearch-6.8.0.
System variable JAVA_HOME added. ("C:\Program Files (x86)\Java\jre1.8.0_211").

I don't see anything in logs:

```<code>Java HotSpot(TM) Client VM (25.211-b12) for windows-x86 JRE (1.8.0_211-b12), built on Apr  1 2019 20:53:53 by "java_re" with MS VC++ 10.0 (VS2010)
Memory: 4k page, physical 6590616k(3782852k free), swap 7639192k(4460440k free)
CommandLine flags: -XX:+AlwaysPreTouch -XX:CMSInitiatingOccupancyFraction=75 -XX:ErrorFile=logs/hs_err_pid%p.log -XX:GCLogFileSize=67108864 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=data -XX:InitialHeapSize=2147483648 -XX:MaxHeapSize=2147483648 -XX:MaxNewSize=268435456 -XX:MaxTenuringThreshold=6 -XX:NewSize=268435456 -XX:NumberOfGCLogFiles=32 -XX:OldPLABSize=16 -XX:OldSize=536870912 -XX:-OmitStackTraceInFastThrow -XX:+PrintGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:ThreadStackSize=1024 -XX:+UseCMSInitiatingOccupancyOnly -XX:+UseConcMarkSweepGC -XX:+UseGCLogFileRotation -XX:-UseLargePagesIndividualAllocation -XX:+UseParNewGC
</code>```

答:
It could be java heap issue. Can you try reducing max and min heap value in elasticsearch\config\jvm.options

Reduce below value
-Xms2g
-Xmx2g

to
-Xms1g
-Xmx1g

or lower

Body:
I'm trying to start Elasticsearch process from Services. It starts, then stops immediately.

Laptop with Windows 10.
I've tried different versions, I've tried .msi and installing from zip.
Now I'm stuck with elasticsearch-6.8.0.
System variable JAVA_HOME added. ("C:\Program Files (x86)\Java\jre1.8.0_211").

I don't see anything in logs:

Java HotSpot(TM) Client VM (25.211-b12) for windows-x86 JRE (1.8.0_211-b12), built on Apr  1 2019 20:53:53 by "java_re" with MS VC++ 10.0 (VS2010)
Memory: 4k page, physical 6590616k(3782852k free), swap 7639192k(4460440k free)
CommandLine flags: -XX:+AlwaysPreTouch -XX:CMSInitiatingOccupancyFraction=75 -XX:ErrorFile=logs/hs_err_pid%p.log -XX:GCLogFileSize=67108864 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=data -XX:InitialHeapSize=2147483648 -XX:MaxHeapSize=2147483648 -XX:MaxNewSize=268435456 -XX:MaxTenuringThreshold=6 -XX:NewSize=268435456 -XX:NumberOfGCLogFiles=32 -XX:OldPLABSize=16 -XX:OldSize=536870912 -XX:-OmitStackTraceInFastThrow -XX:+PrintGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:ThreadStackSize=1024 -XX:+UseCMSInitiatingOccupancyOnly -XX:+UseConcMarkSweepGC -XX:+UseGCLogFileRotation -XX:-UseLargePagesIndividualAllocation -XX:+UseParNewGC


问:
Can i use a 32 Bit ODBC Driver for my 64 Bit app
I have a Win32 application that makes ODBC-Connections. We connect using SQLDriverConnect()
which displays a dialog to select the data source. In the x64-Version the Dialog shows and offers 2 different 32 Bit MS ACCESS Drivers. When i select one of these, in the 32 Bit version i would see a open file dialog to select a .mdb file. In the 64 Bit version the call to SQLDriverConnect() at this point returns with -1.

SQLError() returns: "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"

Is it in general possible to use a 32 Bit ODBC Driver from a 64-Bit executable? Why are these driver shown? As far as i can find there is no 64 Bit MS Access OBDC driver so far. What can i do?

答:
In order to "bridge" from a 64bit application to a 32bit ODBC driver you would need to employ an ODBC to ODBC Bridge such as -

http://uda.openlinksw.com/odbc-odbc-mt/

This has a 64bit ODBC client component which connects vis sockets to 32bit server components. The server components bridge to a pre-configured 32bit Access ODBC DSN.

Client component can be either on the local machine or a server machine...


问:
External links in Facbook don't work in WKWebView. Any idea how to resolve this?
Facebook has external links to all sorts of sites. These can be opened successfully in Safari on iOS and even using UISafariViewController.
However in a WKWebView these links are not clickable, as if there is no link, just the text.

Anybody experienced something similar or knows how to resolve this?

Other web-sites opening external links are not a problem. It seems to be a Facebook specific issue. Almost as if Facebook is actively preventing this.
I found a difference in the User Agent of Safari and of WKWebView, maybe Facebook is making use of this?!

答:
I faced similar problem , with one of the pages in WkWebview

Basically when the link on this page is clicked , it opens a new page and it works very well with Mobile safari and SFSafariViewController but not with the WkWebview

WKWebView does not open any links which have target="_blank" i.e 'Open in new Window'

Here is what I did

Implement WKNavigationDelegate on current view controller

```<code>@interface ViewController () <WKNavigationDelegate>
{

}
</code>```

Assign navigation delegate to current view controller

```<code>WKWebView.navigationDelegate = self;
</code>```

and implement the navigation delegate like below ( This lets target _blank links to be opened on current window )

```<code>- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    BOOL shouldLoad = [self shouldStartLoadWithRequest:navigationAction.request];

    if (shouldLoad && navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    decisionHandler(shouldLoad ? WKNavigationActionPolicyAllow : WKNavigationActionPolicyCancel);
}
</code>```

Hope this helps

Body:
I faced similar problem , with one of the pages in WkWebview

Basically when the link on this page is clicked , it opens a new page and it works very well with Mobile safari and SFSafariViewController but not with the WkWebview

WKWebView does not open any links which have target="_blank" i.e 'Open in new Window'

Here is what I did

Implement WKNavigationDelegate on current view controller

@interface ViewController () <WKNavigationDelegate>
{

}

Assign navigation delegate to current view controller

WKWebView.navigationDelegate = self;

and implement the navigation delegate like below ( This lets target _blank links to be opened on current window )

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    BOOL shouldLoad = [self shouldStartLoadWithRequest:navigationAction.request];

    if (shouldLoad && navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    decisionHandler(shouldLoad ? WKNavigationActionPolicyAllow : WKNavigationActionPolicyCancel);
}

Hope this helps


问:
How to add a unit to the Xaxis tooltip with highcharts
I have this chart :

I want to add a unit to the value "4" (value of my xAxis). How can I do that?

Thank you

答:
```<code> tooltip: {
        valueDecimals: 2,
        valuePrefix: '$',
        valueSuffix: ' USD'
    }
</code>```

please check the below link

https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/tooltip/valuedecimals/

Body:
 tooltip: {
        valueDecimals: 2,
        valuePrefix: '$',
        valueSuffix: ' USD'
    }

please check the below link

https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/tooltip/valuedecimals/


问:
Windows form UI freezing and unable to execute user action when too much data is coming in
Created a simple window form to receive and process data from serial port
also logging the data in textfile and displaying in the rich-text box.

For some reason, it is going into unresponsive state and not able to execute user action and freeze.

According to my understanding, earlier code was using two threads one UI and another one for data received event. Is this correct

But now as i am using background worker, it should create anther thread to process and append in the log and richtext box. Is this correct?

This is my first project in c# so pardon me if it is already answered somewhere else as i am unable to correlate this situation with the given answers and not able to implement them.

Is it a good idea to background worker if not then how can i solve this problem.

Thanks in advance.

Earlier the entire application was running on UI thread. Now i have tried to use background to create a new thread to store data receiving from serial port and processing inside that thread

```<code>//earlier code
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];
        Port.Read(buffer, 0, bytes);
        receivedBytes.AddRange(buffer);
        ProcessRecievedBytes(null);
    }
}

//latest code with background worker
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];

        Port.Read(buffer, 0, bytes);
        receivingBytes.AddRange(buffer);

        if (!essentialBgWorker.IsBusy)
        {
            receivedBytes.AddRange(receivingBytes);
            receivingBytes.Clear();
            essentialBgWorker.RunWorkerAsync();
        }
    }
 }

private void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (byte hexByte in receivedBytes)
    {
        //color = Color.Gray;
        if ((Config.Data.Serial_DisplayLevel == GLOBAL.HEX_LEVEL_NONE))
        {
            if ((hexByte == '\n') || ((hexByte >= 0x20) && (hexByte <= 0x7E)))
            {
                String tmpString = new String((char)hexByte, 1);
                //essentialBgWorker.ReportProgress(0, tmpString);
                //in here i am putting in the log file and appending in the richtext box
                PreprocessAppend(tmpString, Color.Black, false);
            }
        }
    }

    process.ProcessData(receivedBytes);//in here i am processing the data
    receivedBytes.Clear();
}

private void essentialBgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string str = e.UserState.ToString();
    logWriter.Write(str);
    logWriter.Flush();

    if (e.ProgressPercentage == 0)
    {
        AppendSerial(str, Color.Black, false);
    }
    else if (e.ProgressPercentage == 1)
    {
        AppendSerial(str, Color.Black, false);
    }
}

SerialTab.SerialPort.AppendSerial += delegate (string data, Color txtColor, bool newLineCheck)
{
    this.BeginInvoke((MethodInvoker)(delegate ()
    {
        if (newLineCheck && (serialTextBox.Text != "") && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\r') && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\n'))
        {
            data = "\n" + data;
        }

        AppendTextbox(serialTextBox, data, txtColor);
    }));
};

void AppendTextbox(RichTextBox tb, string data, Color txtColor)
{
    if (data == null)
    {
        return;
    }

    int start = tb.TextLength;
    tb.AppendText(data);
    int end = tb.TextLength;

    // Textbox may transform chars, so (end-start) != text.Length
    tb.Select(start, end - start);
    tb.SelectionColor = txtColor;

    //reset color to defaults
    tb.SelectionLength = 0;
    tb.SelectionColor = serialTextBox.ForeColor;

    //move caret to bottom of page
    ScrollToBottom(tb);

    //ensure text buffer stays below 15000 characters
    checkTextBoxLength(tb);
}

void checkTextBoxLength(RichTextBox box)
{
    //ensure text buffer in text box gets too large
    if (box.Text.Length > 15000)
    {
        box.ReadOnly = false;
        box.SelectionStart = 0;
        box.SelectionLength = box.TextLength - 10000;
        box.SelectedText = "";
        box.ReadOnly = true;
    }
}
</code>```

答:
I recommend you junk all of your existing code, and proceed with using something like this, derived from the example from MSDN

```<code>namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {

        SerialPort mySerialPort = new SerialPort("COM1");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None;
            mySerialPort.RtsEnable = true;

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            mySerialPort.Open();

        }

        private void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();

            textBox1.InvokeIfRequired(ctrl => ctrl.AppendText(indata));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            mySerialPort.Close();
        }

    }

    public static class ControlHelpers
    {
        public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : ISynchronizeInvoke
        {
            if (control.InvokeRequired)
            {
                control.Invoke(new Action(() => action(control)), null);
            }
            else
            {
                action(control);
            }
        }
    }
}
</code>```

Your DataReceived handler is quite complex. The MSDN example uses a far simpler interface where it takes care internally of the reading and buffering etc with ReadExisting. You might want to attach to it and just keep appending the data you received into some kind of buffer (stringbuilder?), and regularly inspect the buffer to see if it contains a full message that you want to process

Body:
Created a simple window form to receive and process data from serial port
also logging the data in textfile and displaying in the rich-text box.

For some reason, it is going into unresponsive state and not able to execute user action and freeze.

According to my understanding, earlier code was using two threads one UI and another one for data received event. Is this correct

But now as i am using background worker, it should create anther thread to process and append in the log and richtext box. Is this correct?

This is my first project in c# so pardon me if it is already answered somewhere else as i am unable to correlate this situation with the given answers and not able to implement them.

Is it a good idea to background worker if not then how can i solve this problem.

Thanks in advance.

Earlier the entire application was running on UI thread. Now i have tried to use background to create a new thread to store data receiving from serial port and processing inside that thread

//earlier code
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];
        Port.Read(buffer, 0, bytes);
        receivedBytes.AddRange(buffer);
        ProcessRecievedBytes(null);
    }
}

//latest code with background worker
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];

        Port.Read(buffer, 0, bytes);
        receivingBytes.AddRange(buffer);

        if (!essentialBgWorker.IsBusy)
        {
            receivedBytes.AddRange(receivingBytes);
            receivingBytes.Clear();
            essentialBgWorker.RunWorkerAsync();
        }
    }
 }

private void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (byte hexByte in receivedBytes)
    {
        //color = Color.Gray;
        if ((Config.Data.Serial_DisplayLevel == GLOBAL.HEX_LEVEL_NONE))
        {
            if ((hexByte == '\n') || ((hexByte >= 0x20) && (hexByte <= 0x7E)))
            {
                String tmpString = new String((char)hexByte, 1);
                //essentialBgWorker.ReportProgress(0, tmpString);
                //in here i am putting in the log file and appending in the richtext box
                PreprocessAppend(tmpString, Color.Black, false);
            }
        }
    }

    process.ProcessData(receivedBytes);//in here i am processing the data
    receivedBytes.Clear();
}

private void essentialBgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string str = e.UserState.ToString();
    logWriter.Write(str);
    logWriter.Flush();

    if (e.ProgressPercentage == 0)
    {
        AppendSerial(str, Color.Black, false);
    }
    else if (e.ProgressPercentage == 1)
    {
        AppendSerial(str, Color.Black, false);
    }
}

SerialTab.SerialPort.AppendSerial += delegate (string data, Color txtColor, bool newLineCheck)
{
    this.BeginInvoke((MethodInvoker)(delegate ()
    {
        if (newLineCheck && (serialTextBox.Text != "") && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\r') && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\n'))
        {
            data = "\n" + data;
        }

        AppendTextbox(serialTextBox, data, txtColor);
    }));
};

void AppendTextbox(RichTextBox tb, string data, Color txtColor)
{
    if (data == null)
    {
        return;
    }

    int start = tb.TextLength;
    tb.AppendText(data);
    int end = tb.TextLength;

    // Textbox may transform chars, so (end-start) != text.Length
    tb.Select(start, end - start);
    tb.SelectionColor = txtColor;

    //reset color to defaults
    tb.SelectionLength = 0;
    tb.SelectionColor = serialTextBox.ForeColor;

    //move caret to bottom of page
    ScrollToBottom(tb);

    //ensure text buffer stays below 15000 characters
    checkTextBoxLength(tb);
}

void checkTextBoxLength(RichTextBox box)
{
    //ensure text buffer in text box gets too large
    if (box.Text.Length > 15000)
    {
        box.ReadOnly = false;
        box.SelectionStart = 0;
        box.SelectionLength = box.TextLength - 10000;
        box.SelectedText = "";
        box.ReadOnly = true;
    }
}

Body:
I recommend you junk all of your existing code, and proceed with using something like this, derived from the example from MSDN

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {

        SerialPort mySerialPort = new SerialPort("COM1");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None;
            mySerialPort.RtsEnable = true;

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            mySerialPort.Open();

        }

        private void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();

            textBox1.InvokeIfRequired(ctrl => ctrl.AppendText(indata));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            mySerialPort.Close();
        }

    }

    public static class ControlHelpers
    {
        public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : ISynchronizeInvoke
        {
            if (control.InvokeRequired)
            {
                control.Invoke(new Action(() => action(control)), null);
            }
            else
            {
                action(control);
            }
        }
    }
}

Your DataReceived handler is quite complex. The MSDN example uses a far simpler interface where it takes care internally of the reading and buffering etc with ReadExisting. You might want to attach to it and just keep appending the data you received into some kind of buffer (stringbuilder?), and regularly inspect the buffer to see if it contains a full message that you want to process


答:
You may try this. May be exactly list the answer @U9-Forward, a little compact.

```<code>>>> str(pi)[:6]
'3.1415'
</code>```

Hope this will help.

Title: Decimal numbers get round up while formatting python

Body:
You may try this. May be exactly list the answer @U9-Forward, a little compact.

>>> str(pi)[:6]
'3.1415'

Hope this will help.


问:
How to get setuptools and easy_install?
I downloaded the ez_setup code from here: http://peak.telecommunity.com/dist/ez_setup.py
and ran it, but i don't think setuptools was properly installed. When i try to open an egg using easy_install i am getting a NameError. Any thoughts?

Here is the specific error:

```<code>Traceback (most recent call last):
  File "C:...setup.py", line 223, in <module>
    easy_install eggsetup.py
NameError: name 'easy_install' is not defined
</code>```

答:
If you are installing from distro packages, then this probably doesn't apply to your scenario...

recompile python

I have multiple versions of Python built from source installed, and I found I didn't have setuptools for version 3.5. It seems like I was missing the zlib libraries when I compiled 3.5, which subsequently made the setuptools install fail quietly (to me at least). Recompiling with the zlib libs installed fixed this for me.

install from GitHub

If you are for some reason missing setuptools and have Python compiled with all the necessary libs, you should be able to install it from the GitHub repo like this:

```<code>git clone https://github.com/pypa/setuptools.git
cd ./setuptools
python3.5 bootstrap.py
sudo python3.5 setup.py install
</code>```

Title: How to get setuptools and easy_install?

Body:
I downloaded the ez_setup code from here: http://peak.telecommunity.com/dist/ez_setup.py
and ran it, but i don't think setuptools was properly installed. When i try to open an egg using easy_install i am getting a NameError. Any thoughts?

Here is the specific error:

Traceback (most recent call last):
  File "C:...setup.py", line 223, in <module>
    easy_install eggsetup.py
NameError: name 'easy_install' is not defined

Body:
If you are installing from distro packages, then this probably doesn't apply to your scenario...

recompile python

I have multiple versions of Python built from source installed, and I found I didn't have setuptools for version 3.5. It seems like I was missing the zlib libraries when I compiled 3.5, which subsequently made the setuptools install fail quietly (to me at least). Recompiling with the zlib libs installed fixed this for me.

install from GitHub

If you are for some reason missing setuptools and have Python compiled with all the necessary libs, you should be able to install it from the GitHub repo like this:

git clone https://github.com/pypa/setuptools.git
cd ./setuptools
python3.5 bootstrap.py
sudo python3.5 setup.py install


问:
Watson Assistant Log Error "Rate limit exceeded"
I need your help in getting Watson Assistant Logs. I am getting an error “Rate limit exceeded”. According to API docs, we can specify cursor in param. When cursor is specified we can make 120 requests / min. If cursor is not specified then we can make 40 requests / 30min only. I have passed cursor attribute in “param” object as empty string when it first initiates and then I have updated the cursor value to next_cursor value which was returned by Watson (pagination attribute as a token). However, still its making 40 requests and connection gets closed for 30 min. Could you please tell me what I am doing wrong? I am able to retrieve 40 logs in text file. I am using Node JS. I am looking forward to hearing from you.

Below is the small sample function which I have created:

```<code>const getLogs = () => {
           const params = {
             workspace_id: '50f6598a-a369-45df-9cfb-20bdfe617066',
             cursor: ""
           }
           service.listLogs(params)
           .then(res => {
             if(res.pagination.next_cursor) {
               fs.writeFile("temp.txt", JSON.stringify(res, null, 2), err => {
                 if (err) console.log(err);
                 console.log("Successfully Written to File.");
               });
               params.cursor = res.pagination.next_cursor;
               getLogs()
             } else {
               console.log('no more logs')
             }
           })
           .catch(err => console.log(JSON.stringify(err, null, 2)));
         }
         getLogs();

</code>```

```<code>{
  "name": "Too Many Requests",
  "code": 429,
  "message": "Rate limit exceeded",
  "body": "{\"error\":\"Rate limit exceeded\",\"code\":429}",
  "headers": {
    "x-backside-transport": "FAIL FAIL",
    "content-type": "application/json; charset=utf-8",
    "access-control-allow-origin": "*",
    "access-control-allow-methods": "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS",
    "access-control-allow-headers": "Content-Type, Content-Length, Authorization, X-Watson-Authorization-Token, X-WDC-PL-OPT-OUT, X-Watson-UserInfo, X-Watson-Learning-Opt-Out, X-Watson-Metadata",
    "access-control-max-age": "3600",
    "content-security-policy": "default-src 'none'",
    "x-dns-prefetch-control": "off",
    "x-frame-options": "SAMEORIGIN",
    "strict-transport-security": "max-age=31536000;",
    "x-download-options": "noopen",
    "x-content-type-options": "nosniff",
    "x-xss-protection": "1; mode=block",
    "x-ratelimit-limit": "40",
    "x-ratelimit-reset": "1559060571",
    "x-ratelimit-remaining": "0",
    "retry-after": "1143.36",
    "x-global-transaction-id": "7ecac92c5ced5be3440b2991",
    "x-dp-watson-tran-id": "gateway01-1141582225",
    "x-dp-transit-id": "gateway01-1141582225",
    "content-length": "42",
    "x-edgeconnect-midmile-rtt": "256",
    "x-edgeconnect-origin-mex-latency": "210",
    "date": "Tue, 28 May 2019 16:03:47 GMT",
    "connection": "close"
  }
}
</code>```

答:
I think this may be recursion related and that params.cursor is set to "" at the start of each recursion. What you need to do is to combine recursion with closure. So your code will look something like:</p>

```<code> const getLogs = () => {
   const params = {
        workspace_id: '50f6598a-a369-45df-9cfb-20bdfe617066',
        cursor: ""
    }
   function doGetLogs() {
     service.listLogs(params)
     .then(res => {
        if(res.pagination.next_cursor) {
                ...
                params.cursor = res.pagination.next_cursor;
                doGetLogs()
              }
              ...
            })
           ...
   }
   return doGetLogs();
 }

 getLogs();
</code>```

Body:
I need your help in getting Watson Assistant Logs. I am getting an error “Rate limit exceeded”. According to API docs, we can specify cursor in param. When cursor is specified we can make 120 requests / min. If cursor is not specified then we can make 40 requests / 30min only. I have passed cursor attribute in “param” object as empty string when it first initiates and then I have updated the cursor value to next_cursor value which was returned by Watson (pagination attribute as a token). However, still its making 40 requests and connection gets closed for 30 min. Could you please tell me what I am doing wrong? I am able to retrieve 40 logs in text file. I am using Node JS. I am looking forward to hearing from you.

Below is the small sample function which I have created:

const getLogs = () => {
           const params = {
             workspace_id: '50f6598a-a369-45df-9cfb-20bdfe617066',
             cursor: ""
           }
           service.listLogs(params)
           .then(res => {
             if(res.pagination.next_cursor) {
               fs.writeFile("temp.txt", JSON.stringify(res, null, 2), err => {
                 if (err) console.log(err);
                 console.log("Successfully Written to File.");
               });
               params.cursor = res.pagination.next_cursor;
               getLogs()
             } else {
               console.log('no more logs')
             }
           })
           .catch(err => console.log(JSON.stringify(err, null, 2)));
         }
         getLogs();

{
  "name": "Too Many Requests",
  "code": 429,
  "message": "Rate limit exceeded",
  "body": "{\"error\":\"Rate limit exceeded\",\"code\":429}",
  "headers": {
    "x-backside-transport": "FAIL FAIL",
    "content-type": "application/json; charset=utf-8",
    "access-control-allow-origin": "*",
    "access-control-allow-methods": "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS",
    "access-control-allow-headers": "Content-Type, Content-Length, Authorization, X-Watson-Authorization-Token, X-WDC-PL-OPT-OUT, X-Watson-UserInfo, X-Watson-Learning-Opt-Out, X-Watson-Metadata",
    "access-control-max-age": "3600",
    "content-security-policy": "default-src 'none'",
    "x-dns-prefetch-control": "off",
    "x-frame-options": "SAMEORIGIN",
    "strict-transport-security": "max-age=31536000;",
    "x-download-options": "noopen",
    "x-content-type-options": "nosniff",
    "x-xss-protection": "1; mode=block",
    "x-ratelimit-limit": "40",
    "x-ratelimit-reset": "1559060571",
    "x-ratelimit-remaining": "0",
    "retry-after": "1143.36",
    "x-global-transaction-id": "7ecac92c5ced5be3440b2991",
    "x-dp-watson-tran-id": "gateway01-1141582225",
    "x-dp-transit-id": "gateway01-1141582225",
    "content-length": "42",
    "x-edgeconnect-midmile-rtt": "256",
    "x-edgeconnect-origin-mex-latency": "210",
    "date": "Tue, 28 May 2019 16:03:47 GMT",
    "connection": "close"
  }
}

Body:
I think this may be recursion related and that params.cursor is set to "" at the start of each recursion. What you need to do is to combine recursion with closure. So your code will look something like:

 const getLogs = () => {
   const params = {
        workspace_id: '50f6598a-a369-45df-9cfb-20bdfe617066',
        cursor: ""
    }
   function doGetLogs() {
     service.listLogs(params)
     .then(res => {
        if(res.pagination.next_cursor) {
                ...
                params.cursor = res.pagination.next_cursor;
                doGetLogs()
              }
              ...
            })
           ...
   }
   return doGetLogs();
 }

 getLogs();


问:
Visual Studio Database Project - Unresolved Reference to temp table
I have imported my sql server 2005 database into a VS2010 database project.  One of my stored procedures contains a statement similar to

INSERT INTO #myTemp...

and Visual Studio gives me a warning such as

SQL04151: Procedure: [dbo].[mySproc] has an unresolved reference to object [#myTemp].

Is there a way of resolving this reference? I'd like to clear as many of the project warnings as possible.

答:
Did you try three part naming as in here
(VS 2010 build database project receive SQL04151)

Also you might need to change the db ref to tempdb instead of master. See this article (http://blogs.msdn.com/b/gertd/archive/2009/06/10/system-objects-in-tempdb.aspx). It describes sys objects but temporary tables are stored in tempdb so would exhibit the same behavior.

ContentLicense: CC BY-SA 2.5


问:
Npgsql: nested sql commands on one connection
I'm porting an app from firebird to postgres and there is a bunch of nested sql commands. The first command is necessary for the second one to run, there are some functions that have 5 or 6 nested commands and they are all using the same connection. I just wanted to know if there is a way to do all this on one connection without having to rewrite the whole thing.

```<code>    static void NestedCommandsOnOneConnection()
    {
        using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString))
        {
            using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM tableA", connection))
            {
                using (NpgsqlDataReader reader = command.ExecuteReader())
                {
                    using (NpgsqlCommand command2 = new NpgsqlCommand("SELECT * FROM tableB where column1 = @column1", connection))
                    {
                        command2.Parameters.AddWithValue("@column1", reader["column1"]);

                        using (NpgsqlDataReader reader2 = command2.ExecuteReader())
                        {
                            while (reader2.Read())
                            {
                                //Do things
                            }
                        }
                    }
                }
            }
        }
    }
</code>```

//Edit: Would it be better if i do something like this?

```<code>    static void NestedCommandsOnOneConnection()
    {
        using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString))
        {
            var column1 = "";
            using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM tableA LIMIT 1", connection))
            {
                using (NpgsqlDataReader reader = command.ExecuteReader())
                {
                    while(reader.Read())
                    {
                       column1 = reader["column1"].ToString();
                    }

                }
            }
            using (NpgsqlCommand command2 = new NpgsqlCommand("SELECT * FROM tableB where column1 = @column1", connection))
            {
                command2.Parameters.AddWithValue("@column1", column1);

                using (NpgsqlDataReader reader2 = command2.ExecuteReader())
                {
                    while (reader2.Read())
                    {
                        //Do things
                    }
                }
            }
        }
    }
</code>```

When the second command gets executed I get the error msg "a command is already in progress: SELECT * FROM tableA" So is there any way to do this without having to make a connection for each command?

答: To add to @paulo-correia's response above, opening a second connection may be fine, depending on your usecase. Assuming you're using pooling and you're not in shortage of connections (i.e. a massively concurrent scenario), there's nothing wrong with doing that and it would save on the client-side memory needed to buffer the first query's results. However, note that if the two queries need to be in a transaction this is not possible.</p>

Body:
I'm porting an app from firebird to postgres and there is a bunch of nested sql commands. The first command is necessary for the second one to run, there are some functions that have 5 or 6 nested commands and they are all using the same connection. I just wanted to know if there is a way to do all this on one connection without having to rewrite the whole thing.

    static void NestedCommandsOnOneConnection()
    {
        using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString))
        {
            using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM tableA", connection))
            {
                using (NpgsqlDataReader reader = command.ExecuteReader())
                {
                    using (NpgsqlCommand command2 = new NpgsqlCommand("SELECT * FROM tableB where column1 = @column1", connection))
                    {
                        command2.Parameters.AddWithValue("@column1", reader["column1"]);

                        using (NpgsqlDataReader reader2 = command2.ExecuteReader())
                        {
                            while (reader2.Read())
                            {
                                //Do things
                            }
                        }
                    }
                }
            }
        }
    }

//Edit: Would it be better if i do something like this?

    static void NestedCommandsOnOneConnection()
    {
        using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString))
        {
            var column1 = "";
            using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM tableA LIMIT 1", connection))
            {
                using (NpgsqlDataReader reader = command.ExecuteReader())
                {
                    while(reader.Read())
                    {
                       column1 = reader["column1"].ToString();
                    }

                }
            }
            using (NpgsqlCommand command2 = new NpgsqlCommand("SELECT * FROM tableB where column1 = @column1", connection))
            {
                command2.Parameters.AddWithValue("@column1", column1);

                using (NpgsqlDataReader reader2 = command2.ExecuteReader())
                {
                    while (reader2.Read())
                    {
                        //Do things
                    }
                }
            }
        }
    }

When the second command gets executed I get the error msg "a command is already in progress: SELECT * FROM tableA" So is there any way to do this without having to make a connection for each command?


问:
Compare a two column with the same table to remove duplicate
A sample table with two column and I need to compare the column 1 and column 2 to the same table records and need to remove the column 1 + column 2 = column 2+column 1.

I tried to do self join and case condition. But its not working

答:
The SQL below will get the reversed col1 and col2 rows:

```<code>select
    distinct t2.col1,t1.col2
from
    table t1
join
    table t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1
</code>```

And when we get these reversed rows, we can except them with the left join clause, the complete SQL is:

```<code>select
    t.col1,t.col2
from
    table t
left join
    (
      select
        distinct t2.col1,t1.col2
      from
        table t1
      join
        table t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1
    ) tmp on t.col1 = tmp.col1 and t.col2 = tmp.col2
where
    tmp.col1 is null
</code>```

Is it clear?

Body:
The SQL below will get the reversed col1 and col2 rows:

select
    distinct t2.col1,t1.col2
from
    table t1
join
    table t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1

And when we get these reversed rows, we can except them with the left join clause, the complete SQL is:

select
    t.col1,t.col2
from
    table t
left join
    (
      select
        distinct t2.col1,t1.col2
      from
        table t1
      join
        table t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1
    ) tmp on t.col1 = tmp.col1 and t.col2 = tmp.col2
where
    tmp.col1 is null

Is it clear?


问:
InvalidDefinitionException: Cannot construct instance of `com.vehicle.datatransferobject.VehicleDTO`
In the REST endpoint I'm building in Spring Boot, I'm trying to pass my vehicleDTO to my controller. But before it reaches my controller, there is an error.

InvalidDefinitionException: Cannot construct instance of
  com.vehicle.datatransferobject.VehicleDTO (no Creators, like default
  construct, exist): cannot deserialize from Object value (no delegate-
  or property-based Creator)

vehicleDTO

```<code>import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.myvehicle.EngineType;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class VehicleDTO {

    @JsonIgnore
    private Long id;

    @NotNull(message = "vehiclenumber can not be null!")
    private String vehiclenumber;

    @Min(2)
    @NotNull(message = "Seat count can not be less than 2!")
    private Integer vehicleseatcount;

    @NotNull(message = "Engine Type can not be null!")
    private EngineType enginetype;

    @Max(5)
    private Integer vehiclerating;

    private VehicleDTO(Long id, String vehiclenumber, Integer vehicleseatcount, EngineType enginetype,Integer vehiclerating){
        this.vehiclenumber=vehiclenumber;
        this.vehicleseatcount=vehicleseatcount;
        this.enginetype=enginetype;
        this.vehiclerating=vehiclerating;
        this.id=id;
    }

    public static VehicleDTOBuilder newBuilder()
    {
        return new VehicleDTOBuilder();
    }

    @JsonProperty
    public Long getId() {
        return id;
    }

    public String getvehiclenumber() {
        return vehiclenumber;
    }

    public Integer getvehicleseatcount() {
        return vehicleseatcount;
    }

    public EngineType getEnginetype() {
        return enginetype;
    }

    public Integer getvehiclerating() {
        return vehiclerating;
    }

    public static class VehicleDTOBuilder{

        private Long id;
        private String vehiclenumber;
        private Integer vehicleseatcount;
        private EngineType enginetype;
        private Integer vehiclerating;

        public VehicleDTOBuilder setId(Long id) {
            this.id = id;
            return this;
        }
        public VehicleDTOBuilder setvehiclenumber(String vehiclenumber) {
            this.vehiclenumber = vehiclenumber;
            return this;
        }
        public VehicleDTOBuilder setvehicleseatcount(Integer vehicleseatcount) {
            this.vehicleseatcount = vehicleseatcount;
            return this;
        }
        public VehicleDTOBuilder setEnginetype(EngineType enginetype) {
            this.enginetype = enginetype;
            return this;
        }
        public VehicleDTOBuilder setvehiclerating(Integer vehiclerating) {
            this.vehiclerating = vehiclerating;
            return this;
        }

        public VehicleDTO createVehicleDTO()
        {
            return new VehicleDTO(id, vehiclenumber, vehicleseatcount, enginetype,vehiclerating);
        }

    }

}
</code>```

My DTO has an Enum type called EngineType

```<code>public enum EngineType {
    ELECTRIC, DIESEL
}
</code>```

My controller looks like this

```<code>@PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public VehicleDTO addvehicle(@Valid @RequestBody VehicleDTO vehicleDTO)
    {
        VehicleDO vehicleDO = Mapper.VehicleDO(vehicleDTO);
        return Mapper.makeVehicleDTO(Service.addvehicle(vehicleDO));
    }
</code>```

答:
I faced this error when I used Lombok's @Builder and @Data annotations together on a POJO class that is used for connecting to an API (either for consuming or for providing response)

I removed the @Builder annotation and then it is working fine

Body:
In the REST endpoint I'm building in Spring Boot, I'm trying to pass my vehicleDTO to my controller. But before it reaches my controller, there is an error.

InvalidDefinitionException: Cannot construct instance of
  com.vehicle.datatransferobject.VehicleDTO (no Creators, like default
  construct, exist): cannot deserialize from Object value (no delegate-
  or property-based Creator)

vehicleDTO

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.myvehicle.EngineType;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class VehicleDTO {

    @JsonIgnore
    private Long id;

    @NotNull(message = "vehiclenumber can not be null!")
    private String vehiclenumber;

    @Min(2)
    @NotNull(message = "Seat count can not be less than 2!")
    private Integer vehicleseatcount;

    @NotNull(message = "Engine Type can not be null!")
    private EngineType enginetype;

    @Max(5)
    private Integer vehiclerating;

    private VehicleDTO(Long id, String vehiclenumber, Integer vehicleseatcount, EngineType enginetype,Integer vehiclerating){
        this.vehiclenumber=vehiclenumber;
        this.vehicleseatcount=vehicleseatcount;
        this.enginetype=enginetype;
        this.vehiclerating=vehiclerating;
        this.id=id;
    }

    public static VehicleDTOBuilder newBuilder()
    {
        return new VehicleDTOBuilder();
    }

    @JsonProperty
    public Long getId() {
        return id;
    }

    public String getvehiclenumber() {
        return vehiclenumber;
    }

    public Integer getvehicleseatcount() {
        return vehicleseatcount;
    }

    public EngineType getEnginetype() {
        return enginetype;
    }

    public Integer getvehiclerating() {
        return vehiclerating;
    }

    public static class VehicleDTOBuilder{

        private Long id;
        private String vehiclenumber;
        private Integer vehicleseatcount;
        private EngineType enginetype;
        private Integer vehiclerating;

        public VehicleDTOBuilder setId(Long id) {
            this.id = id;
            return this;
        }
        public VehicleDTOBuilder setvehiclenumber(String vehiclenumber) {
            this.vehiclenumber = vehiclenumber;
            return this;
        }
        public VehicleDTOBuilder setvehicleseatcount(Integer vehicleseatcount) {
            this.vehicleseatcount = vehicleseatcount;
            return this;
        }
        public VehicleDTOBuilder setEnginetype(EngineType enginetype) {
            this.enginetype = enginetype;
            return this;
        }
        public VehicleDTOBuilder setvehiclerating(Integer vehiclerating) {
            this.vehiclerating = vehiclerating;
            return this;
        }

        public VehicleDTO createVehicleDTO()
        {
            return new VehicleDTO(id, vehiclenumber, vehicleseatcount, enginetype,vehiclerating);
        }

    }

}

My DTO has an Enum type called EngineType

public enum EngineType {
    ELECTRIC, DIESEL
}

My controller looks like this

@PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public VehicleDTO addvehicle(@Valid @RequestBody VehicleDTO vehicleDTO)
    {
        VehicleDO vehicleDO = Mapper.VehicleDO(vehicleDTO);
        return Mapper.makeVehicleDTO(Service.addvehicle(vehicleDO));
    }


问:
How to find a key in multidimensional array?
I have a  multidimensional array and i need make a searchCategory($categories, $id) function, which have to return a value of 'title' properties.

it try this code, it work but only for one layer of multidimensional array.

Multidimensional array:

```<code>$categories = array(    array(
    "id" => 1,
    "title" =>  "Обувь",
    'children' => array(
        array(
            'id' => 2,
            'title' => 'Ботинки',
            'children' => array(
                array('id' => 3, 'title' => 'Кожа'),
                array('id' => 4, 'title' => 'Текстиль'),
            ),
        ),
        array('id' => 5, 'title' => 'Кроссовки',),
    )),     array(
    "id" => 6,
    "title" =>  "Спорт",
    'children' => array(
        array(
            'id' => 7,
            'title' => 'Мячи'
        )
    )   ), );
</code>```

Code which i try solve problem:

```<code>function searchCategory($categories, $id) {

    foreach($categories as $category) {

        if($category['id'] == $id) {

            echo $category['title'] . '<br>';

        }
    }
};
</code>```

I need my function to look up the id value in all arrays and return the title in the case of the array found

答:
Here is recursive iterator case for you, please go through inline doc for explanation

```<code>function searchCategory($categories, $id)
{
    $arrayiter = new RecursiveArrayIterator($categories);
    $iteriter  = new RecursiveIteratorIterator($arrayiter);
    foreach ($iteriter as $key => $value) {
        // checking if iterator comes to point where key is id and value matched
        if ($key == 'id' && $value == $id) {
            // returning matched value with current iterator instance
            return $iteriter->getInnerIterator()['title'];
        }
    }
    return '';
}
echo searchCategory($categories, 2).'<br/>';
echo searchCategory($categories, 7);
</code>```

Working demo.

RecursiveArrayIterator - This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.

RecursiveIteratorIterator - Can be used to iterate through recursive iterators.

RecursiveIteratorIterator::getInnerIterator: Get inner iterator

Body:
I have a  multidimensional array and i need make a searchCategory($categories, $id) function, which have to return a value of 'title' properties.

it try this code, it work but only for one layer of multidimensional array.

Multidimensional array:

$categories = array(    array(
    "id" => 1,
    "title" =>  "Обувь",
    'children' => array(
        array(
            'id' => 2,
            'title' => 'Ботинки',
            'children' => array(
                array('id' => 3, 'title' => 'Кожа'),
                array('id' => 4, 'title' => 'Текстиль'),
            ),
        ),
        array('id' => 5, 'title' => 'Кроссовки',),
    )),     array(
    "id" => 6,
    "title" =>  "Спорт",
    'children' => array(
        array(
            'id' => 7,
            'title' => 'Мячи'
        )
    )   ), );

Code which i try solve problem:

function searchCategory($categories, $id) {

    foreach($categories as $category) {

        if($category['id'] == $id) {

            echo $category['title'] . '
';

        }
    }
};

I need my function to look up the id value in all arrays and return the title in the case of the array found

Body:
Here is recursive iterator case for you, please go through inline doc for explanation

function searchCategory($categories, $id)
{
    $arrayiter = new RecursiveArrayIterator($categories);
    $iteriter  = new RecursiveIteratorIterator($arrayiter);
    foreach ($iteriter as $key => $value) {
        // checking if iterator comes to point where key is id and value matched
        if ($key == 'id' && $value == $id) {
            // returning matched value with current iterator instance
            return $iteriter->getInnerIterator()['title'];
        }
    }
    return '';
}
echo searchCategory($categories, 2).'<br/>';
echo searchCategory($categories, 7);

Working demo.

RecursiveArrayIterator - This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.

RecursiveIteratorIterator - Can be used to iterate through recursive iterators.

RecursiveIteratorIterator::getInnerIterator: Get inner iterator