问:
Floating Burger Menu to the left to align with div id
I am sure this is something very simple but I want to align my burger Nav with the text I have defined. It is currently sitting underneath.

I have tried including the href link within the defined text but this then causes the burger nav to be shown at all times, and not just mobile sizes. Ideally this will only be shown at smaller screen widths.

Here is my code.

body {
  font: 100%/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: white;
}

/* Style the list 'container'  */

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

/* Float the list items left - this is the 'magic' that turns a vertical list into a horizontal row */

ul.topnav li {
  float: left;
}

/* style the links  */

ul.topnav li a {
  display: inline-block;
  color: white;
  text-align: center;
  text-decoration: none;
  transition: 0.3s;
  font-size: 17px;
}

/* hover */

ul.topnav li a:hover {
  color: gold;
}

/* Hide the icon initially  */

ul.topnav li.icon {
  display: none;
}

/* Global */

.container {
  width: 60%;
  margin: auto;
  overflow: hidden;
}

a {
  text-decoration: none;
  color: black;
}

ul {
  margin: 0;
  padding: 0;
}

.subscribe {
  height: 38px;
  background: gold;
  border: 0;
  padding-left: 20px;
  padding-right: 20px;
  color: black;
}

.dark {
  padding: 25px;
  background: #35424a;
  color: white;
  margin-top: 10px;
  margin-bottom: 10px;
}

/* Header **/

header {
  background: #35424a;
  color: white;
  padding-top: 30px;
  min-height: 70px;
  border-bottom: gold 5px solid;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 100%;
}

header li {
  float: left;
  display: inline;
  padding: 0 20px 0 20px;
}

header #branding {
  float: left;
}

header #branding h1 {
  margin: 0;
}

header nav {
  float: right;
  margin-top: 10px;
}

header .highlight {
  color: gold;
}

header a:hover {
  color: gold;
}

h3 .bronze {
  color: #cc6633;
}

h3 .silver {
  color: silver;
}

h3 .gold {
  color: gold;
}

/* Showcase */

#showcase {
  min-height: 400px;
  color: black;
}

#showcase h1 {
  margin-top: 50px;
  font-size: 300%;
  margin-bottom: 10px;
}

#showcase p {
  font-size: 120%;
}

/* Newsletter */

#newsletter {
  padding: 15px;
  color: #ffffff;
  background: #35424a
}

#newsletter h1 {
  float: left;
}

#newsletter form {
  float: right;
  margin-top: 15px;
}

#newsletter input[type="email"] {
  padding: 4px;
  height: 26px;
  width: 250px;
}

/* Sidebar */

aside#sidebar {
  float: right;
  margin-top: 10px;
}

aside#sidebar .quote input,
aside#sidebar .quote textarea {
  top-margin: 10px;
  width: 80%;
  padding: 10px;
}

/* Main-col */

article#main-col {
  float: left;
  width: 65%;
}

/* Imagery */

#social {
  margin-top: 10%;
  text-align: center;
  font-size: 150%;
  color: black;
}

#imagery {
  margin-top: 5%;
  margin-bottom: 5%;
}

#imagery .box {
  float: right;
  text-align: center;
  width: 30%;
  padding: 10px;
}

#imagery .box i {
  font-size: 700%;
}

/* Create four equal columns that floats next to each other */

.column {
  float: left;
  width: 20%;
  padding: 10px;
}

.column img {
  margin-top: 12px;
  width: 100%;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Services */

ul#services li {
  list-style: none;
  padding: 20px;
  border: #cccccc solid 1px;
  margin-bottom: 5px;
  background: #35424a;
  color: white;
}

footer {
  padding: 20px;
  margin-top: 20px;
  color: black;
  background-color: gold;
  text-align: center;
}

/* Media Queries */

@media(max-width: 768px) {
  header #branding,
  header nav,
  header nav li,
  #newsletter h1,
  #newsletter form,
  #boxes .box,
  article#main-col,
  aside#sidebar {
    float: none;
    text-align: center;
    width: 100%;
  }
  header {
    padding-bottom: 20px;
  }
  #imagery {
    font-size: 50%;
    float: none;
  }
  #showcase h1 {
    margin-top: 40px;
  }
  #newsletter button,
  .quote button {
    display: block;
    width: 100%;
  }
  #newsletter form input[type="email"],
  .quote input,
  .quote textarea {
    width: 100%;
    margin-bottom: 5px;
  }
  /* nav */
  ul.topnav li {
    display: none;
  }
  ul.topnav li.icon {
    display: inline-block;
  }
  ul.topnav.responsive {
    position: relative;
  }
  ul.topnav.responsive li.icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  ul.topnav.responsive li {
    float: none;
    /*  'un' float the list items so they return to displaying vertically */
    display: inline;
  }
  ul.topnav.responsive li a {
    display: block;
    text-align: left;
  }
}

/*css reset
* {

  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}

body {
  line-height: 1;
  background-image: url("bg.jpg");
  background-size: cover;  /*this seems better*/

/*background-size: contain;

}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* end reset */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>DB Plumbing | Home</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script src="https://use.fontawesome.com/3a2264e344.js"></script>
  <script src="html8shiv.js"></script>
  <link rel="shortcut icon" type="image/png" href="wrench.png" />
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
  <meta name="desciption" content="Darran Brady Plumbing">
  <meta name="keywords" content="Plumbing, Boilers, Showers, Central Heating, Kitchens, Bathrooms, Installations, Landlord Services, Horsham, West Sussex, Sussex,Barns Green, Billingshurst,Broadbridge Heath,Christ's Hospital, Clemsfold, Copsale,Colgate,Cowfold, Faygate, Handcross, Horsham, Itchingfield, Kingsfold,Lambs Farm,Lower Beeding,Mannings Heath, Maplehurst, Monks Gate, Nuthurst, Partridge Green, Pease Pottage, Roffey, Rowhook, Rusper, Rudgwick, Southwater, Slinfold, Warnham ">
  <meta name="author" content="DB, Darran, Brady, Darran Brady">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script>
    function myFunction() {
      var x = document.getElementById("myTopnav");
      if (x.className === "topnav") {
        x.className += " responsive";
      } else {
        x.className = "topnav";
      }
    }
  </script>
</head>

<body>
  <header>
    <div class="container">
      <div id="branding">
        <h1><span class="highlight">DB</span> Plumbing</h1>
      </div>
      <nav>
        <ul class="topnav" id="myTopnav">
          <li class="active">Home</li>
          <li>About</li>
          <li>Services</li>
          <li>Coverage</li>
          <li>Contact</li>
          <li class="icon">
            ☰
        </ul>
      </nav>
    </div>
  </header>

  <section id="showcase">
    <div class="container">
      <h1>Local Award Winning Trader</h1>
      <h2>Call Darren | <i class="fa fa-phone" aria-hidden="true"></i> 07756848657</h2>
      <p>DB Plumbing provides a full range of general plumbing and repair services, from installing your new bathroom suite to fixing that leaking tap or joint that has been annoying you for ages. </p>

      <p>Our customer's individual requirements are important to us at DB Plumbing. We always provide quality service and products and combined with honesty has made us the first choice of many homes in the Horsham area</p>
    </div>
  </section>

  <section id="newsletter">
    <div class="container">
      <h1>Subscribe To Our Weekly Blog</h1>
      <form>
        <input type="email" placeholder="Subscribe today...">
        <button type="submit" class="subscribe">Subscribe</button>
      </form>
    </div>
  </section>

  <section id="imagery">
    <div class="container">
      <div class="box">
        <i class="fa fa-star" aria-hidden="true"></i>
        <h1>Accredited</h1>
        <p>Gas Safe Accreditted </p>
      </div>
      <div class="box">
        <i class="fa fa-thumbs-up" aria-hidden="true"></i>
        <h1>Reputable</h1>
        <p>"25 years service experience "</p>
      </div>
      <div class="box">
        <i class="fa fa-map-marker" aria-hidden="true"></i>
        <h1>Local</h1>
        <p>Sussex and Surrey Countywide</p>
      </div>
    </div>
  </section>

  <footer>
    <div>
      <p>Darren Brady Plumbing Copyright © 2017</p>
    </div>
  </footer>
</body>

</html></code>```

Wanting to float the burger nav to align with text

答:
I've taken only the part we are interested into on code so it's a little more readable and here's my sugegstion. Using the display: flex property will help put the elements on the same line:

body {
  font: 100%/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
}

.container {
  width: 60%;
  margin: auto;
  overflow: hidden;
  /*Below is the simple fix*/
  display: flex;
  align-items: baseline;
}

#branding {
  display: inline-block;
  background: red; /*Only for readability purpose*/
}

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;

}

a {
  display: inline-block;
  color: white;
  text-align: center;
  text-decoration: none;
  transition: 0.3s;
  font-size: 17px;
  text-decoration: none;
  font-size: 130%;
  background: teal; /*Only for readability purpose*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div id="branding">
    <h1><span class="highlight">DB</span> Plumbing</h1>
  </div>
  <nav>
    <ul class="topnav">
      <li class="icon">
        ☰
      </li>
    </ul>
  </nav>
</div></code>```

See A complete guide to flexbox on CSS Tricks for more insights.

Hope I got it right :)

Body:
I am sure this is something very simple but I want to align my burger Nav with the text I have defined. It is currently sitting underneath.

I have tried including the href link within the defined text but this then causes the burger nav to be shown at all times, and not just mobile sizes. Ideally this will only be shown at smaller screen widths.

Here is my code.

body {
  font: 100%/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: white;
}

/* Style the list 'container'  */

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

/* Float the list items left - this is the 'magic' that turns a vertical list into a horizontal row */

ul.topnav li {
  float: left;
}

/* style the links  */

ul.topnav li a {
  display: inline-block;
  color: white;
  text-align: center;
  text-decoration: none;
  transition: 0.3s;
  font-size: 17px;
}

/* hover */

ul.topnav li a:hover {
  color: gold;
}

/* Hide the icon initially  */

ul.topnav li.icon {
  display: none;
}

/* Global */

.container {
  width: 60%;
  margin: auto;
  overflow: hidden;
}

a {
  text-decoration: none;
  color: black;
}

ul {
  margin: 0;
  padding: 0;
}

.subscribe {
  height: 38px;
  background: gold;
  border: 0;
  padding-left: 20px;
  padding-right: 20px;
  color: black;
}

.dark {
  padding: 25px;
  background: #35424a;
  color: white;
  margin-top: 10px;
  margin-bottom: 10px;
}

/* Header **/

header {
  background: #35424a;
  color: white;
  padding-top: 30px;
  min-height: 70px;
  border-bottom: gold 5px solid;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 100%;
}

header li {
  float: left;
  display: inline;
  padding: 0 20px 0 20px;
}

header #branding {
  float: left;
}

header #branding h1 {
  margin: 0;
}

header nav {
  float: right;
  margin-top: 10px;
}

header .highlight {
  color: gold;
}

header a:hover {
  color: gold;
}

h3 .bronze {
  color: #cc6633;
}

h3 .silver {
  color: silver;
}

h3 .gold {
  color: gold;
}

/* Showcase */

#showcase {
  min-height: 400px;
  color: black;
}

#showcase h1 {
  margin-top: 50px;
  font-size: 300%;
  margin-bottom: 10px;
}

#showcase p {
  font-size: 120%;
}

/* Newsletter */

#newsletter {
  padding: 15px;
  color: #ffffff;
  background: #35424a
}

#newsletter h1 {
  float: left;
}

#newsletter form {
  float: right;
  margin-top: 15px;
}

#newsletter input[type="email"] {
  padding: 4px;
  height: 26px;
  width: 250px;
}

/* Sidebar */

aside#sidebar {
  float: right;
  margin-top: 10px;
}

aside#sidebar .quote input,
aside#sidebar .quote textarea {
  top-margin: 10px;
  width: 80%;
  padding: 10px;
}

/* Main-col */

article#main-col {
  float: left;
  width: 65%;
}

/* Imagery */

#social {
  margin-top: 10%;
  text-align: center;
  font-size: 150%;
  color: black;
}

#imagery {
  margin-top: 5%;
  margin-bottom: 5%;
}

#imagery .box {
  float: right;
  text-align: center;
  width: 30%;
  padding: 10px;
}

#imagery .box i {
  font-size: 700%;
}

/* Create four equal columns that floats next to each other */

.column {
  float: left;
  width: 20%;
  padding: 10px;
}

.column img {
  margin-top: 12px;
  width: 100%;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Services */

ul#services li {
  list-style: none;
  padding: 20px;
  border: #cccccc solid 1px;
  margin-bottom: 5px;
  background: #35424a;
  color: white;
}

footer {
  padding: 20px;
  margin-top: 20px;
  color: black;
  background-color: gold;
  text-align: center;
}

/* Media Queries */

@media(max-width: 768px) {
  header #branding,
  header nav,
  header nav li,
  #newsletter h1,
  #newsletter form,
  #boxes .box,
  article#main-col,
  aside#sidebar {
    float: none;
    text-align: center;
    width: 100%;
  }
  header {
    padding-bottom: 20px;
  }
  #imagery {
    font-size: 50%;
    float: none;
  }
  #showcase h1 {
    margin-top: 40px;
  }
  #newsletter button,
  .quote button {
    display: block;
    width: 100%;
  }
  #newsletter form input[type="email"],
  .quote input,
  .quote textarea {
    width: 100%;
    margin-bottom: 5px;
  }
  /* nav */
  ul.topnav li {
    display: none;
  }
  ul.topnav li.icon {
    display: inline-block;
  }
  ul.topnav.responsive {
    position: relative;
  }
  ul.topnav.responsive li.icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  ul.topnav.responsive li {
    float: none;
    /*  'un' float the list items so they return to displaying vertically */
    display: inline;
  }
  ul.topnav.responsive li a {
    display: block;
    text-align: left;
  }
}

/*css reset
* {

  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}

body {
  line-height: 1;
  background-image: url("bg.jpg");
  background-size: cover;  /*this seems better*/

/*background-size: contain;

}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* end reset */

<!DOCTYPE html>

  <title>DB Plumbing | Home</title>
  <link rel="stylesheet" type="text/css" href="style.css">

  <link rel="shortcut icon" type="image/png" href="wrench.png" />
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
  <meta name="desciption" content="Darran Brady Plumbing">
  <meta name="keywords" content="Plumbing, Boilers, Showers, Central Heating, Kitchens, Bathrooms, Installations, Landlord Services, Horsham, West Sussex, Sussex,Barns Green, Billingshurst,Broadbridge Heath,Christ's Hospital, Clemsfold, Copsale,Colgate,Cowfold, Faygate, Handcross, Horsham, Itchingfield, Kingsfold,Lambs Farm,Lower Beeding,Mannings Heath, Maplehurst, Monks Gate, Nuthurst, Partridge Green, Pease Pottage, Roffey, Rowhook, Rusper, Rudgwick, Southwater, Slinfold, Warnham ">
  <meta name="author" content="DB, Darran, Brady, Darran Brady">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

DB Plumbing

Home

About

Services

Coverage

Contact

            ☰

Local Award Winning Trader

Call Darren |  07756848657

DB Plumbing provides a full range of general plumbing and repair services, from installing your new bathroom suite to fixing that leaking tap or joint that has been annoying you for ages.

Our customer's individual requirements are important to us at DB Plumbing. We always provide quality service and products and combined with honesty has made us the first choice of many homes in the Horsham area

Subscribe To Our Weekly Blog

      <form>
        <input type="email" placeholder="Subscribe today...">
        <button type="submit" class="subscribe">Subscribe</button>
      </form>

Accredited

Gas Safe Accreditted

Reputable

"25 years service experience "

Local

Sussex and Surrey Countywide

Darren Brady Plumbing Copyright © 2017

Wanting to float the burger nav to align with text

Body:
I've taken only the part we are interested into on code so it's a little more readable and here's my sugegstion. Using the display: flex property will help put the elements on the same line:

body {
  font: 100%/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
}

.container {
  width: 60%;
  margin: auto;
  overflow: hidden;
  /*Below is the simple fix*/
  display: flex;
  align-items: baseline;
}

#branding {
  display: inline-block;
  background: red; /*Only for readability purpose*/
}

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;

}

a {
  display: inline-block;
  color: white;
  text-align: center;
  text-decoration: none;
  transition: 0.3s;
  font-size: 17px;
  text-decoration: none;
  font-size: 130%;
  background: teal; /*Only for readability purpose*/
}

<div class="container">
  <div id="branding">
    <h1><span class="highlight">DB</span> Plumbing</h1>
  </div>
  <nav>
    <ul class="topnav">
      <li class="icon">
        <a href="javascript:void(0);" onclick="myFunction()">☰</a>
      </li>
    </ul>
  </nav>
</div>

See A complete guide to flexbox on CSS Tricks for more insights.

Hope I got it right :)


来源: stackexchange

问:
convert a string to a list of object using Java 8
I have a string

```<code>"Red apple, blue banana, orange".
</code>```

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

```<code>   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());
</code>```

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

答:
To split the string you can do:

```<code>string[] output = fruitString.split(",");
</code>```

You would then have to go through the string letter by letter to find spaces and replace them with strings:`

```<code>for(int i = 0; i < output.length; i++){
   for(int j = 0; j < output[i].length(); j++){
       char c = output[i].charAt(j);
       //check for space and replace with _
   }
}
</code>```

then using the .toUpperCase() to conver the first char to a upper letter

Hope this helps you.

ContentLicense: CC BY-SA 3.0

Body:
I have a string

"Red apple, blue banana, orange".

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

Body:
To split the string you can do:

string[] output = fruitString.split(",");

You would then have to go through the string letter by letter to find spaces and replace them with strings:`

for(int i = 0; i < output.length; i++){
   for(int j = 0; j < output[i].length(); j++){
       char c = output[i].charAt(j);
       //check for space and replace with _
   }
}

then using the .toUpperCase() to conver the first char to a upper letter

Hope this helps you.


问:
How to use last item in combo box vb.net
Trying to create a program that takes user input and multiplies it by a value in a combo box, 1 to 9. The combo box must automatically increment by 1. Results are displayed in a List box. I got all of this to work, my problem is that when the combo box reaches the last value, it throws an error. How do I fix it so that when it reaches the last value it does not throw an error?
combo box is populated on form load</p>

```<code>Dim intUserInput As Integer
Dim outPut As Integer
intUserInput = TextBox1.Text
Try

    If intUserInput >= 1 Then
        outPut = intUserInput * ComboBox1.SelectedItem
        ListBox1.Items.Add(outPut)
        TextBox1.Clear()
        ComboBox1.SelectedIndex = ComboBox1.SelectedIndex + 1
    End If

Catch ex As Exception
    MessageBox.Show(ex.Message)
    MessageBox.Show("Error")
End Try
</code>```

答:
It's throwing an error at you because you are trying to add past the index of the last item of the combo box. So you need to ensure that you don't add past that value. The following code should sort this problem, but I think you need more, particularly checking textbox is numeric (Look at Integer.Tryparse):</p>

```<code>Dim intUserInput As Integer
Dim outPut As Integer
intUserInput = CInt(TextBox1.Text)
Try
    If intUserInput >= 1 Then
        outPut = intUserInput * CInt(ComboBox1.SelectedItem)
        ListBox1.Items.Add(outPut)
        TextBox1.Clear()
        If ComboBox1.SelectedIndex < ComboBox1.Items.Count - 1 Then
            ComboBox1.SelectedIndex += 1
        End If
    End If
Catch ex As Exception
    MessageBox.Show(ex.Message)
    MessageBox.Show("Error")
End Try
</code>```

Body:
Trying to create a program that takes user input and multiplies it by a value in a combo box, 1 to 9. The combo box must automatically increment by 1. Results are displayed in a List box. I got all of this to work, my problem is that when the combo box reaches the last value, it throws an error. How do I fix it so that when it reaches the last value it does not throw an error?
combo box is populated on form load

Dim intUserInput As Integer
Dim outPut As Integer
intUserInput = TextBox1.Text
Try

    If intUserInput >= 1 Then
        outPut = intUserInput * ComboBox1.SelectedItem
        ListBox1.Items.Add(outPut)
        TextBox1.Clear()
        ComboBox1.SelectedIndex = ComboBox1.SelectedIndex + 1
    End If

Catch ex As Exception
    MessageBox.Show(ex.Message)
    MessageBox.Show("Error")
End Try

Body:
It's throwing an error at you because you are trying to add past the index of the last item of the combo box. So you need to ensure that you don't add past that value. The following code should sort this problem, but I think you need more, particularly checking textbox is numeric (Look at Integer.Tryparse):

Dim intUserInput As Integer
Dim outPut As Integer
intUserInput = CInt(TextBox1.Text)
Try
    If intUserInput >= 1 Then
        outPut = intUserInput * CInt(ComboBox1.SelectedItem)
        ListBox1.Items.Add(outPut)
        TextBox1.Clear()
        If ComboBox1.SelectedIndex < ComboBox1.Items.Count - 1 Then
            ComboBox1.SelectedIndex += 1
        End If
    End If
Catch ex As Exception
    MessageBox.Show(ex.Message)
    MessageBox.Show("Error")
End Try


问:
How to write to an existing excel file without overwriting data (using pandas)?
I use pandas to write to excel file in the following fashion:

```<code>import pandas

writer = pandas.ExcelWriter('Masterfile.xlsx')

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()
</code>```

Masterfile.xlsx already consists of number of different tabs. However, it does not yet contain "Main".

Pandas correctly writes to "Main" sheet, unfortunately it also deletes all other tabs.

答:
```<code>writer = pd.ExcelWriter('prueba1.xlsx'engine='openpyxl',keep_date_col=True)
</code>```

The "keep_date_col" hope help you

ContentLicense: CC BY-SA 4.0

Body:
I use pandas to write to excel file in the following fashion:

import pandas

writer = pandas.ExcelWriter('Masterfile.xlsx')

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

Masterfile.xlsx already consists of number of different tabs. However, it does not yet contain "Main".

Pandas correctly writes to "Main" sheet, unfortunately it also deletes all other tabs.

Body:
writer = pd.ExcelWriter('prueba1.xlsx'engine='openpyxl',keep_date_col=True)

The "keep_date_col" hope help you


问:
How to have colors in the output of (emacs) shell-command?
When executing the command shell-command, the output shown in the associated buffer is not colorized.

This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs.

How can I configure, or extend, emacs in order to have shell-command allowing colorized output in the shell and preserving the colors while representing that output?

Thanks!

ps. I'm using the Bash shell, on a UN*X system.

答:
This is probably what you want :</p>

```<code>(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is probably what you want :

(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)


问:
Symfony add a service that depends on TemplateEngine in twig.globals
I want to inject a service in each view, but this service depends on EngineInterface so I cannot add it to twig.globals as it throws an error of circular reference.

Here is an example:

The service:

namespace AppBundle\Utils;

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

```<code>class Test
{
    /** @var EngineInterface */
    private $template;

    /**
     * Test constructor.
     * @param $template
     */
    public function __construct(EngineInterface $template)
    {
        $this->template = $template;
    }

    public function render(){
        return $this->template->render('AppBundle::test.html.twig');
    }
}
</code>```

And in config.yml:

```<code># Twig Configuration
twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    globals:
        test: "@AppBundle\\Utils\\Test"
</code>```

And the error shown:

So, how can I inject this service in all views. Of course I could inject the container and get the templating service from the container, but I would like to avoid the container injection.

Thank you.

答:
Your service basically just includes the test.html.twig template into another template.

Twig already provides a built-in function for that. Instead of

```<code>{{ test.render() }}
</code>```

You could just do this for the same effect, but without the need for a custom service:

```<code>{{ include('AppBundle::test.html.twig') }}
</code>```

If you don't want to provide the template every time you can create a macro in a "util.twig" template file:

```<code>{% macro render() %}
    {{ include('AppBundle::test.html.twig') }}
{% endmacro %}
</code>```

and use it in your template:

```<code>{% import "util.twig" as util %}

...

{{ util.render() }}
</code>```

Body:
I want to inject a service in each view, but this service depends on EngineInterface so I cannot add it to twig.globals as it throws an error of circular reference.

Here is an example:

The service:

namespace AppBundle\Utils;

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class Test
{
    /** @var EngineInterface */
    private $template;

    /**
     * Test constructor.
     * @param $template
     */
    public function __construct(EngineInterface $template)
    {
        $this->template = $template;
    }

    public function render(){
        return $this->template->render('AppBundle::test.html.twig');
    }
}

And in config.yml:

# Twig Configuration
twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    globals:
        test: "@AppBundle\\Utils\\Test"

And the error shown:

So, how can I inject this service in all views. Of course I could inject the container and get the templating service from the container, but I would like to avoid the container injection.

Thank you.

Body:
Your service basically just includes the test.html.twig template into another template.

Twig already provides a built-in function for that. Instead of

{{ test.render() }}

You could just do this for the same effect, but without the need for a custom service:

{{ include('AppBundle::test.html.twig') }}

If you don't want to provide the template every time you can create a macro in a "util.twig" template file:

{% macro render() %}
    {{ include('AppBundle::test.html.twig') }}
{% endmacro %}

and use it in your template:

{% import "util.twig" as util %}

...

{{ util.render() }}


问:
Microsoft Query displaying data correctly but won't return data to Excel- Error SQ20448
Good morning,

I have a semi-functioning SQL query to pull data from the IBM AS/400 into Microsoft Excel. The data displays correctly inside Microsoft Query, but when I click on "Return Data" to return the data to Excel, I receive the following error message:

```<code>[IBM][System i Access ODBC Driver][DB2 for i5/OS]SQ20448 - Expression not
valid using format string specified for TIMESTAMP_FORMAT.
</code>```

Essentially, my code is joining a few files to provide me with item information and uses dates to remove duplicates so that I can get the most recent transactions.

I use practically an identical code for other files that functions correctly, so I suspect there may be an incorrectly formatted date in my original data, which would cause an error when converting the IBM date to the Microsoft-compatible date with the TO_DATE function. I know that my date conversion works correctly, given the IBM date is an actual date.

My question is, how could I code in an exception to either ignore incorrectly formatted data, or how could I return data that is formatted incorrectly so that I could write an exception in my code?

Here is my code (hopefully the comments are helpful):

```<code>SELECT xh.ITNBR, yh.VNDNR, zh.VN35VM, yh.BUYNO, xh.Create_Date -- Item #, Vendor #, Vendor Name, Buyer, Create_Date
  FROM
   (SELECT PO_IH.ITNBR, -- Item #
           max(TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH.ACTDT,2,2))), 'MM/DD/YY')) as Create_Date -- Converts IBM date format to work with Microsoft Query
      FROM POHISTI as PO_IH, POHSTM as PO_MH
     WHERE PO_IH.ORDNO = PO_MH.ORDNO AND
           (TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH.ACTDT,2,2))), 'MM/DD/YY')) =
           (SELECT MIN((TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH.ACTDT,2,2))), 'MM/DD/YY'))) -- All of this chaos basically removes duplicate information and converts IBM date
              FROM POHSTM as PO_MH2
             WHERE PO_MH.ORDNO = PO_MH2.ORDNO AND
                   PO_MH.ACTDT NOT LIKE '0%' AND -- Removes dates that start with 0 (i.e. IBM's way of saying "no date")
                   PO_MH.ACTDT NOT LIKE '9%') -- Removes dates from 20th century
  GROUP BY PO_IH.ITNBR) xh
 LEFT JOIN
   (SELECT PO_IH2.ITNBR, -- Item #
           PO_IH2.BUYNO, -- Buyer
           PO_IH2.VNDNR, -- Vendor
           (TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH2.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH2.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH2.ACTDT,2,2))), 'MM/DD/YY')) as Create_Date
    FROM POHISTI as PO_IH2, POHSTM as PO_MH2
   WHERE PO_IH2.ORDNO = PO_MH2.ORDNO AND
         PO_MH2.ACTDT NOT LIKE '0%' AND -- Removes dates that start with 0 (i.e. IBM's way of saying "no date")
         PO_MH2.ACTDT NOT LIKE '9%') yh -- Removes dates from 20th century
      ON xh.ITNBR = yh.ITNBR AND xh.Create_Date = yh.Create_Date
LEFT JOIN VENNAML0 zh -- Vendor Name
      ON yh.VNDNR = zh.VNDRVM
</code>```

Here is the output in Microsoft Query:

```<code>ITNBR           VNDNR   VN35VM          BUYNO   CREATE_DATE

A-FUL           76      HOLLAND COMP    SUSY    2016-12-06 00:00:00.000000
A-MINI          76      HOLLAND COMP    SUSY    2016-11-28 00:00:00.000000
A-SHIMBOX       76      HOLLAND COMP    SUSY    2014-10-16 00:00:00.000000
A-001           76      HOLLAND COMP    SUSY    2016-12-19 00:00:00.000000
A-002           76      HOLLAND COMP    SUSY    2016-12-19 00:00:00.000000
....
</code>```

Like I said, the information displays perfectly in Microsoft Query but when I return it to Excel I get the above error. I tried using the above "NOT LIKE" statements to deal with the two most common errors, but I'm at a loss as to how to find other errors.

I don't really care if I get bad data, as long as it dumps into Excel. At that point I can correct it. But I suspect that if Microsoft Query can't convert a date, it won't return the data to Excel.

Thanks.

答:
You have a numeric field that is formatted like CYYMMDD. This is a common date format in the IBM i world where C is a century code (0=>19, 1=>20, 2=>21, ..., 9=>28). This came about because most decimal dates were stored in packed decimal format with 2 digit years before the Y2K remediation. Packed decimal always has room for an odd number of digits due to the configuration of the format, but most dates were defined as (6,0) (length,decimal places). This left room on disk for one extra digit to the left of the date, and folks could define the dates as (7,0) without changing the format of the data in the records. thus the 7 digit date was born as a result of Y2K. Synon was the first company I am aware of that did this in their 2E code generator. It was quite popular, and the format is everywhere. It even found its way into the IBM operating system.

So when SQL casts that to CHAR a date like 0951107 will look like 951107, and when SQL casts 1171107 to CHAR, it will look like 1171107. Unfortunately, NOT LIKE '9%' will be unreliable at some point, because that leading 9 could be the first non-zero digit of a 1990 era date, or it could be a 2800 era date. Even worse, 1900's dates chast to a CHAR could start with anything from 1-9. For example a date of 1985/12/05 would look like 0851205 in CYYMMDD digit format. That would be cast to 851205. So when dealing with dates you need to use DIGITS to cast the number to a CHAR so you don't loose the leading 0 character. And you need to test your date field for 0 which is literally 0000000 (not 00/00/00 even though that is what it looks like when it is formatted with EDITC(Y)).

Here is an example of what is happening:

```<code>create table datetest
  (decdt       decimal(7,0));
insert into datetest
  values (0), (941107), (1170304), (1000101);

select substr(decdt,4,2) || '/' ||
       substr(decdt,6,2) || '/' ||
       substr(decdt,2,2),
       decdt
from datetest;
</code>```

results in:

```<code>  /  /      0
10/7 /41    941,107
03/04/17    1,170,304
01/01/00    1,000,101
</code>```

I bet your procedure TO_DATE() is not handling invalid dates properly as they are almost certainly being passed. If you use digits in the substr function, you will get something more sane.

```<code>select substr(digits(decdt),4,2) || '/' ||
       substr(digits(decdt),6,2) || '/' ||
       substr(digits(decdt),2,2),
       decdt
from datetest
</code>```

results in:

```<code>00/00/00    0
11/07/94    941,107
03/04/17    1,170,304
01/01/00    1,000,101
</code>```

Notice that the month day and year parts are all in the correct place now, and all you have to code for is the 0 date which means no date. In any case the function to_date() needs to detect an invalid date and either ignore it, or set it to something usable like 0001-01-01 or null.

Body:
Good morning,

I have a semi-functioning SQL query to pull data from the IBM AS/400 into Microsoft Excel. The data displays correctly inside Microsoft Query, but when I click on "Return Data" to return the data to Excel, I receive the following error message:

[IBM][System i Access ODBC Driver][DB2 for i5/OS]SQ20448 - Expression not
valid using format string specified for TIMESTAMP_FORMAT.

Essentially, my code is joining a few files to provide me with item information and uses dates to remove duplicates so that I can get the most recent transactions.

I use practically an identical code for other files that functions correctly, so I suspect there may be an incorrectly formatted date in my original data, which would cause an error when converting the IBM date to the Microsoft-compatible date with the TO_DATE function. I know that my date conversion works correctly, given the IBM date is an actual date.

My question is, how could I code in an exception to either ignore incorrectly formatted data, or how could I return data that is formatted incorrectly so that I could write an exception in my code?

Here is my code (hopefully the comments are helpful):

SELECT xh.ITNBR, yh.VNDNR, zh.VN35VM, yh.BUYNO, xh.Create_Date -- Item #, Vendor #, Vendor Name, Buyer, Create_Date
  FROM
   (SELECT PO_IH.ITNBR, -- Item #
           max(TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH.ACTDT,2,2))), 'MM/DD/YY')) as Create_Date -- Converts IBM date format to work with Microsoft Query
      FROM POHISTI as PO_IH, POHSTM as PO_MH
     WHERE PO_IH.ORDNO = PO_MH.ORDNO AND
           (TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH.ACTDT,2,2))), 'MM/DD/YY')) =
           (SELECT MIN((TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH.ACTDT,2,2))), 'MM/DD/YY'))) -- All of this chaos basically removes duplicate information and converts IBM date
              FROM POHSTM as PO_MH2
             WHERE PO_MH.ORDNO = PO_MH2.ORDNO AND
                   PO_MH.ACTDT NOT LIKE '0%' AND -- Removes dates that start with 0 (i.e. IBM's way of saying "no date")
                   PO_MH.ACTDT NOT LIKE '9%') -- Removes dates from 20th century
  GROUP BY PO_IH.ITNBR) xh
 LEFT JOIN
   (SELECT PO_IH2.ITNBR, -- Item #
           PO_IH2.BUYNO, -- Buyer
           PO_IH2.VNDNR, -- Vendor
           (TO_DATE((CONCAT(
         CONCAT(
         (CONCAT(SUBSTRING(PO_MH2.ACTDT,4,2), '/')),
         (CONCAT(SUBSTRING(PO_MH2.ACTDT,6,2), '/'))),
         SUBSTRING(PO_MH2.ACTDT,2,2))), 'MM/DD/YY')) as Create_Date
    FROM POHISTI as PO_IH2, POHSTM as PO_MH2
   WHERE PO_IH2.ORDNO = PO_MH2.ORDNO AND
         PO_MH2.ACTDT NOT LIKE '0%' AND -- Removes dates that start with 0 (i.e. IBM's way of saying "no date")
         PO_MH2.ACTDT NOT LIKE '9%') yh -- Removes dates from 20th century
      ON xh.ITNBR = yh.ITNBR AND xh.Create_Date = yh.Create_Date
LEFT JOIN VENNAML0 zh -- Vendor Name
      ON yh.VNDNR = zh.VNDRVM

Here is the output in Microsoft Query:

ITNBR           VNDNR   VN35VM          BUYNO   CREATE_DATE

A-FUL           76      HOLLAND COMP    SUSY    2016-12-06 00:00:00.000000
A-MINI          76      HOLLAND COMP    SUSY    2016-11-28 00:00:00.000000
A-SHIMBOX       76      HOLLAND COMP    SUSY    2014-10-16 00:00:00.000000
A-001           76      HOLLAND COMP    SUSY    2016-12-19 00:00:00.000000
A-002           76      HOLLAND COMP    SUSY    2016-12-19 00:00:00.000000
....

Like I said, the information displays perfectly in Microsoft Query but when I return it to Excel I get the above error. I tried using the above "NOT LIKE" statements to deal with the two most common errors, but I'm at a loss as to how to find other errors.

I don't really care if I get bad data, as long as it dumps into Excel. At that point I can correct it. But I suspect that if Microsoft Query can't convert a date, it won't return the data to Excel.

Thanks.

Body:
You have a numeric field that is formatted like CYYMMDD. This is a common date format in the IBM i world where C is a century code (0=>19, 1=>20, 2=>21, ..., 9=>28). This came about because most decimal dates were stored in packed decimal format with 2 digit years before the Y2K remediation. Packed decimal always has room for an odd number of digits due to the configuration of the format, but most dates were defined as (6,0) (length,decimal places). This left room on disk for one extra digit to the left of the date, and folks could define the dates as (7,0) without changing the format of the data in the records. thus the 7 digit date was born as a result of Y2K. Synon was the first company I am aware of that did this in their 2E code generator. It was quite popular, and the format is everywhere. It even found its way into the IBM operating system.

So when SQL casts that to CHAR a date like 0951107 will look like 951107, and when SQL casts 1171107 to CHAR, it will look like 1171107. Unfortunately, NOT LIKE '9%' will be unreliable at some point, because that leading 9 could be the first non-zero digit of a 1990 era date, or it could be a 2800 era date. Even worse, 1900's dates chast to a CHAR could start with anything from 1-9. For example a date of 1985/12/05 would look like 0851205 in CYYMMDD digit format. That would be cast to 851205. So when dealing with dates you need to use DIGITS to cast the number to a CHAR so you don't loose the leading 0 character. And you need to test your date field for 0 which is literally 0000000 (not 00/00/00 even though that is what it looks like when it is formatted with EDITC(Y)).

Here is an example of what is happening:

create table datetest
  (decdt       decimal(7,0));
insert into datetest
  values (0), (941107), (1170304), (1000101);

select substr(decdt,4,2) || '/' ||
       substr(decdt,6,2) || '/' ||
       substr(decdt,2,2),
       decdt
from datetest;

results in:

  /  /      0
10/7 /41    941,107
03/04/17    1,170,304
01/01/00    1,000,101

I bet your procedure TO_DATE() is not handling invalid dates properly as they are almost certainly being passed. If you use digits in the substr function, you will get something more sane.

select substr(digits(decdt),4,2) || '/' ||
       substr(digits(decdt),6,2) || '/' ||
       substr(digits(decdt),2,2),
       decdt
from datetest

results in:

00/00/00    0
11/07/94    941,107
03/04/17    1,170,304
01/01/00    1,000,101

Notice that the month day and year parts are all in the correct place now, and all you have to code for is the 0 date which means no date. In any case the function to_date() needs to detect an invalid date and either ignore it, or set it to something usable like 0001-01-01 or null.


问:
Pl/SQL procedure to rank highest GPA to lowest without Rank Function
Pl/SQL procedure to rank highest GPA to lowest

I'm referring to the question above. Is it possible to rank a student and their GPA without the rank function?

```<code>FETCH c1 INTO queryResult;
 INSERT INTO GPA VALUES (queryResult.snum, queryResult.sname, rank,queryResult.OrderFrequency);
 rank := rank + 1;
 EXIT WHEN k = rank;
 END LOOP;
 CLOSE c1;
 COMMIT;
END;
</code>```

答:
Is it possible to rank a student and their GPA without the rank
  function?

Yes, use plain SQL with left self-join, group by and a count.

But it is expected to be slower than a version using RANK function

live demo: http://sqlfiddle.com/#!4/bde51/7

```<code>SELECT s1. snum,
       s1.sname,
       s1.gpa,
       count( s2.gpa ) + 1 as rank
FROM students s1
LEFT JOIN students s2
ON s1.GPA < s2.GPA
GROUP BY s1. snum,
         s1.sname,
         s1.gpa
ORDER BY 4;

| SNUM |     SNAME | GPA | RANK |
|------|-----------|-----|------|
|    6 | Student 6 |   4 |    1 |
|    4 | Student 4 |   3 |    2 |
|    3 | Student 3 |   2 |    3 |
|    1 | Student 1 |   2 |    3 |
|    2 | Student 2 |   1 |    5 |
|    5 | Student 5 |   1 |    5 |
</code>```

```<code>select snum,
       sname,
       GPA,
       RANK() OVER (ORDER BY GPA desc) as srank
from students
ORDER BY 4

| SNUM |     SNAME | GPA | SRANK |
|------|-----------|-----|-------|
|    6 | Student 6 |   4 |     1 |
|    4 | Student 4 |   3 |     2 |
|    1 | Student 1 |   2 |     3 |
|    3 | Student 3 |   2 |     3 |
|    5 | Student 5 |   1 |     5 |
|    2 | Student 2 |   1 |     5 |
</code>```

Body:
Pl/SQL procedure to rank highest GPA to lowest

I'm referring to the question above. Is it possible to rank a student and their GPA without the rank function?

FETCH c1 INTO queryResult;
 INSERT INTO GPA VALUES (queryResult.snum, queryResult.sname, rank,queryResult.OrderFrequency);
 rank := rank + 1;
 EXIT WHEN k = rank;
 END LOOP;
 CLOSE c1;
 COMMIT;
END;

Body:
Is it possible to rank a student and their GPA without the rank
  function?

Yes, use plain SQL with left self-join, group by and a count.

But it is expected to be slower than a version using RANK function

live demo: http://sqlfiddle.com/#!4/bde51/7

SELECT s1. snum,
       s1.sname,
       s1.gpa,
       count( s2.gpa ) + 1 as rank
FROM students s1
LEFT JOIN students s2
ON s1.GPA < s2.GPA
GROUP BY s1. snum,
         s1.sname,
         s1.gpa
ORDER BY 4;

| SNUM |     SNAME | GPA | RANK |
|------|-----------|-----|------|
|    6 | Student 6 |   4 |    1 |
|    4 | Student 4 |   3 |    2 |
|    3 | Student 3 |   2 |    3 |
|    1 | Student 1 |   2 |    3 |
|    2 | Student 2 |   1 |    5 |
|    5 | Student 5 |   1 |    5 |

select snum,
       sname,
       GPA,
       RANK() OVER (ORDER BY GPA desc) as srank
from students
ORDER BY 4

| SNUM |     SNAME | GPA | SRANK |
|------|-----------|-----|-------|
|    6 | Student 6 |   4 |     1 |
|    4 | Student 4 |   3 |     2 |
|    1 | Student 1 |   2 |     3 |
|    3 | Student 3 |   2 |     3 |
|    5 | Student 5 |   1 |     5 |
|    2 | Student 2 |   1 |     5 |


问:
R: How to read selected columns from a RDS files?
How to read part of the data from very large files?

The sample data is generated as:

```<code>set.seed(123)
df <- data.frame(replicate(10, sample(0:2000, 15 * 10^5, rep = TRUE)),
                 replicate(10, stringi::stri_rand_strings(1000, 5)))
head(df)
#     X1   X2   X3   X4   X5   X6   X7   X8   X9  X10  X1.1  X2.1  X3.1  X4.1  X5.1  X6.1  X7.1  X8.1  X9.1 X10.1
# 1  575 1843 1854  883  592 1362 1075  210 1526 1365 Qk8NP Xvw9z OYRa1 8BGIV bejiv CCoIE XDKJN HR7zc 2kKNY 1I5h8
# 2 1577  390 1861  912  277  636  758 1461 1978 1865 ZaHFl QLsli E7lbs YGq8u DgUAW c6JQ0 RAZFn Sc0Zt mif8I 3Ys6U
# 3  818 1076  147 1221  257 1115  759 1959 1088 1292 jM5Uw ctM3y 0HiXR hjOHK BZDOP ULQWm Ei8qS BVneZ rkKNL 728gf
# 4 1766  884 1331 1144 1260  768 1620 1231 1428 1193 r4ZCI eCymC 19SwO Ht1O0 repPw YdlSW NRgfL RX4ta iAtVn Hzm0q
# 5 1881 1851 1324 1930 1584 1318  940 1796  830   15 w8d1B qK1b0 CeB8u SlNll DxndB vaufY ZtlEM tDa0o SEMUX V7tLQ
# 6   91  264 1563  414  914 1507 1935 1970  287  409 gsY1u FxIgu 2XqS4 8kreA ymngX h0hkK reIsn tKgQY ssR7g W3v6c
</code>```

saveRDS is used to save the file.

```<code>saveRDS(df, 'df.rds')
</code>```

The file size is looked using the below commands:

```<code>file.info('df.rds')$size
# [1] 29935125
utils:::format.object_size(29935125, "auto")
# [1] "28.5 Mb"
</code>```

The saved file is read using the below function.

```<code>readRDS('df.rds')
</code>```

However, some of my files are in GBs and would need only few columns for certain processing. Is it possible to read selected columns from RDS files?

Note: I already have RDS files, generated after considerably large amounts of processing. Now, I want to know the best possible way to read selected columns from the existing RDS files.

答:
I don't think you can read only a portion of an rds or rda file.

An alternative would be to use feather. As an example, using a large-ish feather I'm working with:

```<code>library(feather)
file.info("../feathers/C1.feather")["size"]
#                              size
#  ../feathers/C1.feather 498782328

system.time( c1whole <- read_feather("../feathers/C1.feather") )
#     user  system elapsed
#    0.860   0.856   5.540
system.time( c1dyn <- feather("../feathers/C1.feather") )
#     user  system elapsed
#        0       0       0

ls.objects()
#             Type      Size PrettySize          Dim
#  c1dyn   feather      3232     3.2 Kb 2886147 x 36
#  c1whole  tbl_df 554158688   528.5 Mb 2886147 x 36
</code>```

You can react with both variables as full data.frames: though c1whole is already in memory (so may be a little faster), accessing c1dyn is still quite speedy.

NB: some functions (e.g., several within dplyr) do not work on feather as they do on data.frame or tbl_df. If your intent is solely to pick-and-choose specific columns, then you'll be fine.

Body:
How to read part of the data from very large files?

The sample data is generated as:

set.seed(123)
df <- data.frame(replicate(10, sample(0:2000, 15 * 10^5, rep = TRUE)),
                 replicate(10, stringi::stri_rand_strings(1000, 5)))
head(df)
#     X1   X2   X3   X4   X5   X6   X7   X8   X9  X10  X1.1  X2.1  X3.1  X4.1  X5.1  X6.1  X7.1  X8.1  X9.1 X10.1
# 1  575 1843 1854  883  592 1362 1075  210 1526 1365 Qk8NP Xvw9z OYRa1 8BGIV bejiv CCoIE XDKJN HR7zc 2kKNY 1I5h8
# 2 1577  390 1861  912  277  636  758 1461 1978 1865 ZaHFl QLsli E7lbs YGq8u DgUAW c6JQ0 RAZFn Sc0Zt mif8I 3Ys6U
# 3  818 1076  147 1221  257 1115  759 1959 1088 1292 jM5Uw ctM3y 0HiXR hjOHK BZDOP ULQWm Ei8qS BVneZ rkKNL 728gf
# 4 1766  884 1331 1144 1260  768 1620 1231 1428 1193 r4ZCI eCymC 19SwO Ht1O0 repPw YdlSW NRgfL RX4ta iAtVn Hzm0q
# 5 1881 1851 1324 1930 1584 1318  940 1796  830   15 w8d1B qK1b0 CeB8u SlNll DxndB vaufY ZtlEM tDa0o SEMUX V7tLQ
# 6   91  264 1563  414  914 1507 1935 1970  287  409 gsY1u FxIgu 2XqS4 8kreA ymngX h0hkK reIsn tKgQY ssR7g W3v6c

saveRDS is used to save the file.

saveRDS(df, 'df.rds')

The file size is looked using the below commands:

file.info('df.rds')$size
# [1] 29935125
utils:::format.object_size(29935125, "auto")
# [1] "28.5 Mb"

The saved file is read using the below function.

readRDS('df.rds')

However, some of my files are in GBs and would need only few columns for certain processing. Is it possible to read selected columns from RDS files?

Note: I already have RDS files, generated after considerably large amounts of processing. Now, I want to know the best possible way to read selected columns from the existing RDS files.

Body:
I don't think you can read only a portion of an rds or rda file.

An alternative would be to use feather. As an example, using a large-ish feather I'm working with:

library(feather)
file.info("../feathers/C1.feather")["size"]
#                              size
#  ../feathers/C1.feather 498782328

system.time( c1whole <- read_feather("../feathers/C1.feather") )
#     user  system elapsed
#    0.860   0.856   5.540
system.time( c1dyn <- feather("../feathers/C1.feather") )
#     user  system elapsed
#        0       0       0

ls.objects()
#             Type      Size PrettySize          Dim
#  c1dyn   feather      3232     3.2 Kb 2886147 x 36
#  c1whole  tbl_df 554158688   528.5 Mb 2886147 x 36

You can react with both variables as full data.frames: though c1whole is already in memory (so may be a little faster), accessing c1dyn is still quite speedy.

NB: some functions (e.g., several within dplyr) do not work on feather as they do on data.frame or tbl_df. If your intent is solely to pick-and-choose specific columns, then you'll be fine.


问:
How can I launch facebook messenger with to enable user to user chat
Users log into my app through the facebook sdk. If one user clicks on another user I'd like to enable them to chat via facebook messenger. I can launch messenger from my app, but is there a way to launch into the chat screen with a specific user.</p>

答:
You can open a conversation in Messenger with deep links:

http://m.me/{user_name} <- this is official link for Messenger. You'll need to ask user for his Messenger's username.

fb-messenger://user/{user_id} <- this link is not documented, so it can break any time (Deep linking). user_id probably is the Facebook User Id, so it will be easier to obtain, however you'll need to ask for user_profile permission to get user id (Messenger Permissions)


问:
Does the location background mode work in swift when the app is terminated?
Right now, I'm trying to implement the location background mode for my app. When the user location is updated, I'm going to schedule a notification (eventually I'll schedule them conditionally, but for right now I'm just scheduling them so I know it works). I have the following code:

```<code> func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        currentLocation = location
    }
    if UIApplication.shared.applicationState == .background {
    // if the app is in the background
         let notif = UNMutableNotificationContent()
    notif.title = "Location was updated"
    var message = " "
    notif.body = message
    let identifier = String(arc4random())
    var dc = DateComponents()
    var date = Date()
    date = Calendar.current.date(byAdding: .second, value: 3, to: date)!
    dc.hour = Calendar.current.component(.hour, from: date)
    dc.minute = Calendar.current.component(.minute, from: date)
    dc.second = Calendar.current.component(.second, from: date)
    let notifTrigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false)
    let request = UNNotificationRequest(identifier: identifier, content: notif, trigger: notifTrigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil {
            print(error!)
        } else {
            print("Notification scheduled!")
        }
    })
</code>```

This works great when the app is in the background, but when the app gets terminated, my function isn't called, and the notifications aren't getting delivered. My question is: Is this possible with Swift? Or does the locationManager function I'm using only work if the app is backgrounded, but not terminated?

Side note: I've tried taking out if UIApplication.shared.applicationState == .background and it does not fix the problem

答:
When you terminate the app, the normal* location services stop, until you run startUpdatingLocation from a non-background state.

*visit Location Service, region monitoring, significant Location Changes are not normal location tracking and are managed on the OS level not app level.

Non-normal location tracking won't get stopped after app termination.

Body:
Right now, I'm trying to implement the location background mode for my app. When the user location is updated, I'm going to schedule a notification (eventually I'll schedule them conditionally, but for right now I'm just scheduling them so I know it works). I have the following code:

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        currentLocation = location
    }
    if UIApplication.shared.applicationState == .background {
    // if the app is in the background
         let notif = UNMutableNotificationContent()
    notif.title = "Location was updated"
    var message = " "
    notif.body = message
    let identifier = String(arc4random())
    var dc = DateComponents()
    var date = Date()
    date = Calendar.current.date(byAdding: .second, value: 3, to: date)!
    dc.hour = Calendar.current.component(.hour, from: date)
    dc.minute = Calendar.current.component(.minute, from: date)
    dc.second = Calendar.current.component(.second, from: date)
    let notifTrigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false)
    let request = UNNotificationRequest(identifier: identifier, content: notif, trigger: notifTrigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil {
            print(error!)
        } else {
            print("Notification scheduled!")
        }
    })

This works great when the app is in the background, but when the app gets terminated, my function isn't called, and the notifications aren't getting delivered. My question is: Is this possible with Swift? Or does the locationManager function I'm using only work if the app is backgrounded, but not terminated?

Side note: I've tried taking out if UIApplication.shared.applicationState == .background and it does not fix the problem


问:
Replacing part of a string in pandas column with `and` condition
I have a pandas dataframe that looks like this:

```<code>    Size    Measure     Location    Messages
    Small     1         Washington  TXT0123 TXT0875 TXT874 TXT0867 TXT0875 TXT0874
    Medium    2         California  TXT020 TXT017 TXT120 TXT012
    Large     3         Texas       TXT0123 TXT0123 TXT0123 TXT0123 TXT0217 TXT0206
    Small     4         California  TXT020 TXT0217 TXT006
    Tiny      5         Nevada      TXT0206 TXT0217 TXT0206
</code>```

I am trying to remove the 0 from the individual words in the Messages column if the length equals 7 and the fourth character is 0.

I've tried for loop, but it's removing all 0's:

```<code>for line in df.Messages:
    for message in line.split():
        if len(message) == 7 and message[3] == '0':
            print(message.replace('0', ''))
</code>```

I also tried .map which gave me some errors:

```<code>df.Messages = df.Messages.map(lambda x: x.replace('0', '') for message in line.split() for line in df.Messages if (len(message) == 7 and message[3] == '0'))

TypeError: 'generator' object is not callable
</code>```

Is there a way to do this with .map that includes the if and and conditionals?

答:
IIUC:</p>

```<code>In [17]: df['Messages'] = df['Messages'].str.replace(r'(\D+)0(\d{3})',r'\1\2')

In [18]: df
Out[18]:
     Size  Measure    Location                                   Messages
0   Small        1  Washington  TXT123 TXT875 TXT874 TXT867 TXT875 TXT874
1  Medium        2  California                TXT020 TXT017 TXT120 TXT012
2   Large        3       Texas  TXT123 TXT123 TXT123 TXT123 TXT217 TXT206
3   Small        4  California                       TXT020 TXT217 TXT006
4    Tiny        5      Nevada                       TXT206 TXT217 TXT206
</code>```

Body:
I have a pandas dataframe that looks like this:

    Size    Measure     Location    Messages
    Small     1         Washington  TXT0123 TXT0875 TXT874 TXT0867 TXT0875 TXT0874
    Medium    2         California  TXT020 TXT017 TXT120 TXT012
    Large     3         Texas       TXT0123 TXT0123 TXT0123 TXT0123 TXT0217 TXT0206
    Small     4         California  TXT020 TXT0217 TXT006
    Tiny      5         Nevada      TXT0206 TXT0217 TXT0206

I am trying to remove the 0 from the individual words in the Messages column if the length equals 7 and the fourth character is 0.

I've tried for loop, but it's removing all 0's:

for line in df.Messages:
    for message in line.split():
        if len(message) == 7 and message[3] == '0':
            print(message.replace('0', ''))

I also tried .map which gave me some errors:

df.Messages = df.Messages.map(lambda x: x.replace('0', '') for message in line.split() for line in df.Messages if (len(message) == 7 and message[3] == '0'))

TypeError: 'generator' object is not callable

Is there a way to do this with .map that includes the if and and conditionals?

Body:
IIUC:

In [17]: df['Messages'] = df['Messages'].str.replace(r'(\D+)0(\d{3})',r'\1\2')

In [18]: df
Out[18]:
     Size  Measure    Location                                   Messages
0   Small        1  Washington  TXT123 TXT875 TXT874 TXT867 TXT875 TXT874
1  Medium        2  California                TXT020 TXT017 TXT120 TXT012
2   Large        3       Texas  TXT123 TXT123 TXT123 TXT123 TXT217 TXT206
3   Small        4  California                       TXT020 TXT217 TXT006
4    Tiny        5      Nevada                       TXT206 TXT217 TXT206


问:
Sending characters A to D as part of DTMF tone using Twilio
I have a question related to sending DTMF tones using Twilio.

I am able to send the number 0 to 9 and characters # and * as DTMF Tones using sendDigits option given in the below URL. https://www.twilio.com/docs/api/twiml/number#attributes-sendDigits

I have a need to send the characters A to D (A, B, C, D) as DTMF Tones.

Let me know, if there is a way to do that using Twilio.

Appreciate your help.

Thanks.

答:
REST API spits out this error when I tried:

```<code>Unable to create record: Invalid sendDigits: 123abcd'
</code>```

So I would think your only option is to create audio files of the DTMF for A,B,C and D and use them in conjunction with the play verb in your TwiML

Body:
REST API spits out this error when I tried:

Unable to create record: Invalid sendDigits: 123abcd'

So I would think your only option is to create audio files of the DTMF for A,B,C and D and use them in conjunction with the play verb in your TwiML


问:
Does the Retina display eliminate the need for anti-aliasing?
With the iPhone 4, the Retina display's resolution is so high that most people cannot distinguish the pixels from one another (supposedly). If this is the case, do apps that support the Retina display still need anti-aliasing to make fonts and images smooth, or is this no longer necessary?

Edit: I'm interested in more detailed information. Started a bounty.

答:
There's no question at all - you still need to do antialiasing mathematics, because of the complexity of curves, second order curves, intersecting curves, and different types of joins.

(Note too that, very simply, since this question appeared two years ago. Retina displays are now ubiquitous and - indeed - antialiasing is, in fact, done everywhere on every Retina display.)

Sure, straight lines (perhaps at 45 degrees) may conceivably test as well in A/B tests.  But just look at a shallower line, or a changing differential.

And wait - there's a knock-down argument here............

Don't forget that you can display typography really, really small on a retina display!!!

One could say that you need antialiasing, whenever letter are less than (let's say) 50 pixels high.  Thus if you had a crappy 10 dot per inch display ... but the letters were 80 feet high (8000 pixels high) you would NOT need antialiasing.  We've just proved you "don't need" antialiasing on a 10 ppi display.

Conversely, let's say Steve's next display has 1000 pixels per inch.  You would STILL need antialiasing for very small type -- and any very small detail -- that is 50 pixels or less!

Furthermore: don't forget that the detail in type ... which is a vector image ... is infinite!

You might be saying, oh the "body" of a baskerville "M" looks fine with no antialiasing, on a retina display.  Well, what about the curves of the serifs?  What about the chipping on the ends of the serifs?  And so on down the line.

Another way to look at it:  ok, on your typical Mac display, you don't need antialiasing on flat lines, or maybe 45degree lines.  further, on a retina display you can get away with no atialiasing on maybe 22.5 degree lines, and even 12.25 degree lines.

But so what?  If you add antialiasing, on a retina display, you can successfully draw ridiculously shallow lines, much shallower than on for example a pre-retina MacBook display.

Once again as in the previous example, say the next iPhone has one zillion pixels per inch.  Still, adding antialiasing will let you have EVEN SHALLOWER good-looking lines -- by definition, yes, it will always make it look better because it will always improve detail.

Note that the "eye resolution" business from the magazine articles is total and complete nonsense.

Even on say 50 dpi displays, you're only seeing a fuzzy amalgam created by the mathematics of the pixel display strategy.

If you don't believe this is so, look at this writing right now on your Mac, and count the pixels in the letter "r".  Of course, it's inconceivable you could do that!!  You could maybe "resolve" pixels on a 10 dpi display. What matters is the mathematics of the fuzz created by the display strategy.

Antialiasing always creates "better fuzz," as it were. If you have more pixels to begin with, antialiasing just gives even better again fuzz.  Again, simply put under consideration even smaller features, and of course you'd want to antialias them.

That seems to be the state of affairs!


问:
Creating the hyperlink preview in iOS
I am trying to create the preview of a hyperlink. I am unable to get any leads about the same. My project is written in Objective C.
I searched the web and found a few third party libraries which are written in Swift.
Thanks in advance.</p>

答: To generate a hyperlink preview, make sure the link is either at the beginning of a text message, or at the end of the text message. If the hyperlink is in the middle of the text message, iOS won't show a hyperlink preview. Also make sure that the hyperlink starts with http:// or https://.</p>

Title: Creating the hyperlink preview in iOS


问:
Importing prices for multiple store views using Magmi
I am trying to update prices using Magmi on 2 store views but I am having issues. Here is my setup.

Website Name (Code: bab)
Store Name (Root Category: BAB)

Has 2 store views
Storeview 1 (Code: abc)
Storeview 2 (Code: bab)

As I am just wanting to update prices for the storeviews my csv file is as follows:
store, websites, sku, price
admin, faf, 1001, 5.00
admin, gpf, 1001, 7.00

Unfortunately the prices are just not updating as needed. Only 1 store price updates, while the other one doesn't.

I have tried importing in different ways.

I imported the prices as 2 separate csv files, 1 for each store view.

I imported both store prices in one csv file. With all products for 1st store at top of csv. Then the 2nd block of products after the 1st store products.

I also tried a csv in the above format where there are 2 rows for each sku with the store view specified on each row.

I also tried adding a 3rd row with admin, website (left blank), sku, price. To account for a default value. In case a default value was needed to be specified also. I tried adding the default row, before both storeviews and also as the 3rd row, after both storeviews.

None of these approaches are applying the price to both. I either get just 1 price update. Or I get the default price show in 1 store, and the other store not updating at all.

I have also been re-indexing after each magmi import, clearing magento cache and my chrome cache.

I have also checked to make sure there are no discounts or pricing rules effecting any products.

So I am hoping someone can advise me on anything I am doing wrong or anything else I need to check. Maybe I am configuring my csv file wrong?

Nore: I have over 5000 products and I don't think I can use magneto's default import feature / data profiles as it is really slow and often just crashes.

Thanks and hope you can help. Would be much appreciated.
Paul

答:
Open magmi/engines/magmi_productimportengine.php and add this condition

```<code>if ($attrcode == "price" && $attrdesc["is_configurable"] == 1){
            $scope=0;
            }
</code>```

After

```<code>if ($attrcode != "price" && $attrdesc["is_configurable"] == 1)
            {
                $scope = 0;
            }
</code>```

https://github.com/dweeves/magmi-git/issues/435

Body:
Open magmi/engines/magmi_productimportengine.php and add this condition

if ($attrcode == "price" && $attrdesc["is_configurable"] == 1){
            $scope=0;
            }

After

if ($attrcode != "price" && $attrdesc["is_configurable"] == 1)
            {
                $scope = 0;
            }

https://github.com/dweeves/magmi-git/issues/435


问:
generic function to test if objects in enumeration contain a property, and if it is equal to 10
In my test cases, I want to loop through a collection of objects (different objects, depending on the scenerio), and if the objects in the collection contain the property location_id I want to verify the id has a value of e.g. 10

All the objects in the collection will be of the same type, but not all collections will have the same type i.e. some may be a collection of users, or a collection or articles etc.

I need this for my rspec tests.

答:
Assuming that by "contain a property" means "responds to a getter method":

```<code>def test_for_value( collection, getter_method, value )
  # Only look deeper if the collection isn't empty
  # and the first element has the method
  if (o=collection.first) && o.respond_to?( getter_method )
    collection.find{ |o| o.send(getter_method)==value }
  end
end

Person = Struct.new( :name, :age )

people = []
p test_for_value( people, :age, 38 )
#=> nil

people << Person.new( "Gavin", 38 )
people << Person.new( "Imogen", 5 )

p test_for_value( people, :age, 38 )
#=> #<struct Person name="Gavin", age=38>

p test_for_value( people, :age, 5 )
#=> #<struct Person name="Imogen", age=5>

p test_for_value( people, :horns, true )
#=> nil
</code>```

If instead you are talking about collections of hashes and you want to lookup the hash key:

```<code>def test_for_value( collection, key, value )
  if (o=collection.first) && o.key?( key )
    collection.find{ |o| o[key]==value }
  end
end
</code>```

Body:
Assuming that by "contain a property" means "responds to a getter method":

def test_for_value( collection, getter_method, value )
  # Only look deeper if the collection isn't empty
  # and the first element has the method
  if (o=collection.first) && o.respond_to?( getter_method )
    collection.find{ |o| o.send(getter_method)==value }
  end
end

Person = Struct.new( :name, :age )

people = []
p test_for_value( people, :age, 38 )
#=> nil

people << Person.new( "Gavin", 38 )
people << Person.new( "Imogen", 5 )

p test_for_value( people, :age, 38 )
#=> #<struct Person name="Gavin", age=38>

p test_for_value( people, :age, 5 )
#=> #<struct Person name="Imogen", age=5>

p test_for_value( people, :horns, true )
#=> nil

If instead you are talking about collections of hashes and you want to lookup the hash key:

def test_for_value( collection, key, value )
  if (o=collection.first) && o.key?( key )
    collection.find{ |o| o[key]==value }
  end
end


问:
Should I error-check Close() on a response body?
The docs for net/http have the following example:

```<code>resp, err := http.Get("http://example.com/")
if err != nil {
    panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("%s", body)
</code>```

Close returns an error, but it is not checked. Is there something I'm missing here? The importance of checking every error is frequently emphasized in go, but I see this defer resp.Body.Close() pattern a lot with no error checks.

答:
This is a downside of using defer

It would be advised, as a responsible developer, that you check for all possible error prone points, and handle them as gracefully as you can.

Here are some of the options you can choose in handling this situation:

Option #1

Do not use defer, instead manually call close once you're done with the response's body and simply check for errors then.

Option #2

Create an anonymous function that wraps the closing and error checking code. Something like this:

```<code>defer func() {
    err := resp.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
}()
</code>```

Avoid using panics in your programs. Try to handle the errors gracefully by doing something or at least logging the error.

Additional information can be found here.

Body:
The docs for net/http have the following example:

resp, err := http.Get("http://example.com/")
if err != nil {
    panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("%s", body)

Close returns an error, but it is not checked. Is there something I'm missing here? The importance of checking every error is frequently emphasized in go, but I see this defer resp.Body.Close() pattern a lot with no error checks.

Body:
This is a downside of using defer

It would be advised, as a responsible developer, that you check for all possible error prone points, and handle them as gracefully as you can.

Here are some of the options you can choose in handling this situation:

Option #1

Do not use defer, instead manually call close once you're done with the response's body and simply check for errors then.

Option #2

Create an anonymous function that wraps the closing and error checking code. Something like this:

defer func() {
    err := resp.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
}()

Avoid using panics in your programs. Try to handle the errors gracefully by doing something or at least logging the error.

Additional information can be found here.


问:
Enabling Chrome Extension in Incognito Mode via CLI flags?
I'm using selenium to test a chrome extension and part of the extension requires the user to be in incognito mode. Currently, I've not been able to enable the extension to be allowed in incognito mode upon startup except by adding the argument user-data-dir=/path/to/directory.

The problem with this is that it loads the extension from the depths of my file system, rather than in a way I can check into git.

I've also tried navigating selenium to the chrome extensions settings page but it seems that selenium can't drive chrome:// pages.

Any ideas on to how to enable incognito on the chrome extension on boot of the chrome driver?

答:
If you are trying to enable the already installed extension in incodnito, then try the below code . It should work with chrome.</p>

```<code> driver.get("chrome://extensions-frame");
  WebElement checkbox = driver.findElement(By.xpath("//label[@class='incognito-control']/input[@type='checkbox']"));
  if (!checkbox.isSelected()) {
    checkbox.click();
  }
</code>```

Body:
If you are trying to enable the already installed extension in incodnito, then try the below code . It should work with chrome.

 driver.get("chrome://extensions-frame");
  WebElement checkbox = driver.findElement(By.xpath("//label[@class='incognito-control']/input[@type='checkbox']"));
  if (!checkbox.isSelected()) {
    checkbox.click();
  }


问:
Rotating a cube around its center Y axis, works first time
I've made a cube with html/css.

The first time I apply a rotation transformation the cube rotates very nicely in place around its center Y axis.

The second time however, the cube kind of "comes forward" and then "moves back" while rotating. The cube ends up in the same position, but the transition is different.

```<code>#wrapper {
    -webkit-perspective: 1100px;
    -webkit-perspective-origin: 50% 300px;
    perspective: 1100px;
    perspective-origin: 50% 300px;
    margin-top: 25px;
}

#cube {
    position: relative;
    margin: 0 auto;
    height: 1150px;
    width: 1150px;
    -webkit-transform-style: preserve-3d;
    -webkit-transition: all 2s ease;
    transform-style: preserve-3d;
    transition: all 2s ease;
    transform: translateZ(-100000px);
}

.face {
    position: absolute;
    height: 1140px;
    width: 1140px;
    padding: 20px;
    background-color: white;
    border: solid 1px black;
}

 #cube .one {
            transform: translateZ(600px);
        }

        #cube .two {
            transform: rotateY(90deg) translateZ(600px);
        }

        #cube .three {
            transform: rotateY(180deg) translateZ(600px);
        }

        #cube .four {
            transform: rotateY(-90deg) translateZ(600px);
        }

        #cube .five {
            transform: rotateX(-90deg) translateZ(600px) rotate(180deg);
        }

        #cube .six {
            transform: rotateX(90deg) translateZ(600px);
        }
</code>```

Bit of Javascript to move to cube into a good view

```<code>$("#cube").css("transform", "translateZ(-2500px) translateX(-380px)");
</code>```

JavaScript to Apply Rotation

```<code>if (direction == "left") {
        if (face == 1) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateX(2500px) translateZ(-380px)");
            face++;
        }
        else if (face == 2) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateZ(2500px)  translateX(380px)  ");
            face++;
        }
        else if (face == 3) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateX(-2500px) translateZ(380px) ");
            face++;
        }
        else if (face == 4) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateZ(-2500px) translateX(-380px) ");

            face = 1;
        }
    }
</code>```

答:
I think you have different width on your cube panels!! you have fixed width in css but paddings increase outer width.
check to see if they all have the same width with your inspect element. try working around box-sizing. </p>

Body:
I've made a cube with html/css.

The first time I apply a rotation transformation the cube rotates very nicely in place around its center Y axis.

The second time however, the cube kind of "comes forward" and then "moves back" while rotating. The cube ends up in the same position, but the transition is different.

#wrapper {
    -webkit-perspective: 1100px;
    -webkit-perspective-origin: 50% 300px;
    perspective: 1100px;
    perspective-origin: 50% 300px;
    margin-top: 25px;
}

#cube {
    position: relative;
    margin: 0 auto;
    height: 1150px;
    width: 1150px;
    -webkit-transform-style: preserve-3d;
    -webkit-transition: all 2s ease;
    transform-style: preserve-3d;
    transition: all 2s ease;
    transform: translateZ(-100000px);
}

.face {
    position: absolute;
    height: 1140px;
    width: 1140px;
    padding: 20px;
    background-color: white;
    border: solid 1px black;
}

 #cube .one {
            transform: translateZ(600px);
        }

        #cube .two {
            transform: rotateY(90deg) translateZ(600px);
        }

        #cube .three {
            transform: rotateY(180deg) translateZ(600px);
        }

        #cube .four {
            transform: rotateY(-90deg) translateZ(600px);
        }

        #cube .five {
            transform: rotateX(-90deg) translateZ(600px) rotate(180deg);
        }

        #cube .six {
            transform: rotateX(90deg) translateZ(600px);
        }

Bit of Javascript to move to cube into a good view

$("#cube").css("transform", "translateZ(-2500px) translateX(-380px)");

JavaScript to Apply Rotation

if (direction == "left") {
        if (face == 1) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateX(2500px) translateZ(-380px)");
            face++;
        }
        else if (face == 2) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateZ(2500px)  translateX(380px)  ");
            face++;
        }
        else if (face == 3) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateX(-2500px) translateZ(380px) ");
            face++;
        }
        else if (face == 4) {

            angle = angle + 90;
            $("#cube").css("transform", "rotateY(" + angle + "deg) translateZ(-2500px) translateX(-380px) ");

            face = 1;
        }
    }


答:
There are two things to consider: What would you do with it if you checked it and there was an error? And, what would the side-effects be if there was an error?

In most cases, for closing a response body, the answer to both questions is... absolutely nothing. If there's nothing you'd do if there was an error and the error has no appreciable impact, there's no reason to check it.

Also note that Close() returns an error in order to fulfill the io.Closer interface; the function doesn't necessarily return an error. You'd need to check the source to know for sure if it has an error case.

Title: Should I error-check Close() on a response body?


问:
How to call function after submit form aspx
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

```<code><div id="HiddenFormTarget" style="display:none;">
    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>
<iframe id="frmPrint" name="frmPrint" width="0" height="0" runat="server">
</iframe>

<script language="javascript" type="text/javascript">
    $("#formImpressao").submit(function () {
       alert('Test');
    });
    $("#formImpressao").submit();

</script>
</code>```

答:
```<code><form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>
</code>```

Now you can use two ways to submit the form using only jQuery,Recommended method

```<code>        <script>
        $(document).ready(function(){
          //instead of id selector use tag selector
            $("form").submit(function () {
               alert('Test');
            });
         });
           </script>
</code>```

Another using id selector which is already posted

Body:
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>

Body:
<form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>

Now you can use two ways to submit the form using only jQuery,Recommended method

        <script>
        $(document).ready(function(){
          //instead of id selector use tag selector
            $("form").submit(function () {
               alert('Test');
            });
         });
           </script>

Another using id selector which is already posted


问:
message queue thinking
We have implemented a message queue by using C# Queue. We know we only have ONE consumer to take available message out from the queue for processing with a while loop. We also know there is only ONE producer to put message onto the queue.

We have a lock on above message queue to make sure the consumer and producer cannot access the queue simultaneously.

My question is is that lock necessary? If the Queue increase its Count property AFTER an item is actually added and if the consumer check the Count before retrieve, the consumer should get a complete message item even we don't have that lock. Right? So we will not face a partial message item issue. Then we can get rid of that lock?

That lock will slow down the system and occasionally we can see the retrieve thread is blocked for a while because we have a very heavy producer.

EDIT:

Unfortunately we are using .Net 3.5.

答:
BTW, Lockless queues for a single reader and a single writer are fairly easy to write.  This is a very primitive example of the concept, but it does the job:</p>

```<code>class LocklessQueue<T>
{
    class Item
    {
        public Item Next;
        bool _valid;
        T _value;
        public Item(bool valid, T value)
        {
            _valid = valid;
            _value = value;
            Next = null;
        }
        public bool IsValid { get { return _valid; } }
        public T TakeValue()
        {
            T value = _value;
            _valid = false;
            _value = default(T);
            return value;
        }
    }

    Item _first;
    Item _last;

    public LocklessQueue()
    {
        _first = _last = new Item(false, default(T));
    }

    public bool IsEmpty
    {
        get
        {
            while (!_first.IsValid && _first.Next != null)
                _first = _first.Next;
            return false == _first.IsValid;
        }
    }

    public void Enqueue(T value)
    {
        Item i = new Item(true, value);
        _last.Next = i;
        _last = i;
    }

    public T Dequeue()
    {
        while (!_first.IsValid && _first.Next != null)
            _first = _first.Next;

        if (IsEmpty)
            throw new InvalidOperationException();//queue is empty

        return _first.TakeValue();
    }
}
</code>```

Title: message queue thinking

Body:
BTW, Lockless queues for a single reader and a single writer are fairly easy to write.  This is a very primitive example of the concept, but it does the job:

class LocklessQueue<T>
{
    class Item
    {
        public Item Next;
        bool _valid;
        T _value;
        public Item(bool valid, T value)
        {
            _valid = valid;
            _value = value;
            Next = null;
        }
        public bool IsValid { get { return _valid; } }
        public T TakeValue()
        {
            T value = _value;
            _valid = false;
            _value = default(T);
            return value;
        }
    }

    Item _first;
    Item _last;

    public LocklessQueue()
    {
        _first = _last = new Item(false, default(T));
    }

    public bool IsEmpty
    {
        get
        {
            while (!_first.IsValid && _first.Next != null)
                _first = _first.Next;
            return false == _first.IsValid;
        }
    }

    public void Enqueue(T value)
    {
        Item i = new Item(true, value);
        _last.Next = i;
        _last = i;
    }

    public T Dequeue()
    {
        while (!_first.IsValid && _first.Next != null)
            _first = _first.Next;

        if (IsEmpty)
            throw new InvalidOperationException();//queue is empty

        return _first.TakeValue();
    }
}


问:
How to add another textarea when inner text of first textarea exceed one page
Consider we're going to create a page containing a textarea for typing an article. the size of textarea is set to an A5 paper size. For long Texts when User types and completes the first textarea, It's required to add another textarea following to the first textarea to allow user continue typing in next page(something like MS word).
What's your suggestion?

.A5 {
  width: 148mm;
  padding: 1cm;
  margin: 1px;
  box-sizing: border-box;
  height: 210mm;
  border: solid 1px;
  resize: none;
  display: block;
}

@page {
  size: A5;
  margin: 0;
  padding: 0;
}

@media print {
  .A5 {
    visibility: visible;
    position: fixed;
    top:0;
    left:0;
    z-index: 99;
    border:none;
  }
  body> :not(.A5){
    color: red;
    display:none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<h1>
Paper Print Test
</h1>
<input type="button" value="print" onclick="window.print()"/>
<textarea class="A5">
  Article Text
</textarea></code>```

答:
Yes it is possible, see the link(please cheek carefully).

This is preview link: https://codepen.io/ziruhel/pen/VrzpqG

There might have more related issue. I think you can solved it, if you need help, please let me know.

If You want it with print preview, Then this solution is for you.

Preview link: https://codepen.io/ziruhel/pen/ZaJpNe

HTML:

```<code><h1>
Paper Print Test
</h1>
<input type="button" value="print" onclick="window.print()"/>
<div class="A5-print">g</div>
<textarea class="A5">
  Article Text

</textarea>
</code>```

CSS:

```<code>.A5,.A5-print {
  width: 148mm;
  padding: 1cm;
  margin: 1px;
  box-sizing: border-box;
}
.A5{
  border: solid 1px;
  height: 210mm;
  resize: none;
  display: block;
}
.A5-print{
  display: none;
}
@page {
  size: A5;
  margin: 0;
  padding: 0;
}

@media print {

  .A5-print{
    visibility: visible;
    z-index: 99;
    display: block;
    page-break-after: always !important;
    overflow: visible;
    white-space: pre;
    white-space: pre-wrap;
  }
  body :not(.A5-print){
     display:none;
  }
  *{
    page-break-after: always !important;
  }
}
</code>```

jQuery:

```<code>jQuery(function($){
  function copy_to_print_helper(){
    $('.A5-print').text($('textarea').val());
  }
  $('textarea').bind('keydown keyup keypress cut copy past blur change', function(){
    copy_to_print_helper(); // consider debouncing this to avoid slowdowns!
  });
  copy_to_print_helper(); // on initial page load
});
</code>```

Preview link: https://codepen.io/ziruhel/pen/ZaJpNe

Body:
Consider we're going to create a page containing a textarea for typing an article. the size of textarea is set to an A5 paper size. For long Texts when User types and completes the first textarea, It's required to add another textarea following to the first textarea to allow user continue typing in next page(something like MS word).
What's your suggestion?

.A5 {
  width: 148mm;
  padding: 1cm;
  margin: 1px;
  box-sizing: border-box;
  height: 210mm;
  border: solid 1px;
  resize: none;
  display: block;
}

@page {
  size: A5;
  margin: 0;
  padding: 0;
}

@media print {
  .A5 {
    visibility: visible;
    position: fixed;
    top:0;
    left:0;
    z-index: 99;
    border:none;
  }
  body> :not(.A5){
    color: red;
    display:none;
  }
}

Paper Print Test

<input type="button" value="print" onclick="window.print()"/>
<textarea class="A5">
  Article Text
</textarea>

Body:
Yes it is possible, see the link(please cheek carefully).

This is preview link: https://codepen.io/ziruhel/pen/VrzpqG

There might have more related issue. I think you can solved it, if you need help, please let me know.

If You want it with print preview, Then this solution is for you.

Preview link: https://codepen.io/ziruhel/pen/ZaJpNe

HTML:

<h1>
Paper Print Test
</h1>
<input type="button" value="print" onclick="window.print()"/>
<div class="A5-print">g</div>
<textarea class="A5">
  Article Text

</textarea>

CSS:

.A5,.A5-print {
  width: 148mm;
  padding: 1cm;
  margin: 1px;
  box-sizing: border-box;
}
.A5{
  border: solid 1px;
  height: 210mm;
  resize: none;
  display: block;
}
.A5-print{
  display: none;
}
@page {
  size: A5;
  margin: 0;
  padding: 0;
}

@media print {

  .A5-print{
    visibility: visible;
    z-index: 99;
    display: block;
    page-break-after: always !important;
    overflow: visible;
    white-space: pre;
    white-space: pre-wrap;
  }
  body :not(.A5-print){
     display:none;
  }
  *{
    page-break-after: always !important;
  }
}

jQuery:

jQuery(function($){
  function copy_to_print_helper(){
    $('.A5-print').text($('textarea').val());
  }
  $('textarea').bind('keydown keyup keypress cut copy past blur change', function(){
    copy_to_print_helper(); // consider debouncing this to avoid slowdowns!
  });
  copy_to_print_helper(); // on initial page load
});

Preview link: https://codepen.io/ziruhel/pen/ZaJpNe