问:
My stylesheet works only when in mobile view, it worked fine yesterday but today all styles are gone if viewed on desktop
So I wrote a small website and everything was working great, all styles were working but today it only displays the style sheet in mobile view in the normal desktop view it disregards all the styles in my css/style.css

The navbar and header imag keeps their style regardless of the size of the browser just the rest of the styles are gone when in desktop view

My header and footer is included in all pages with php includes the files is in includes/header.php and includes/footer.php

Here is the link to the project as well  to look at maxi.maxihome.co.za

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">

   <!-- Bootstrap--!>
   <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</code>```

```<code> <!-- Style sheet -->
 <link rel="stylesheet" href="css/style.css">

 <!--Google Fonts  -->
 <link href="https://fonts.googleapis.com/css?
 family=Acme|Neuton&display=swap" rel="stylesheet"><link
 href="https://fonts.googleapis.com/css?
 family=Acme|Neuton|PT+Mono&display=swap" rel="stylesheet"><link
 href="https://fonts.googleapis.com/css?
 family=Acme|Neuton|PT+Mono|Sintony&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?
family=Acme|Molengo|Neuton|PT+Mono|Sintony&display=swap"
 rel="stylesheet">

 <!-- js script header -->
<script type="text/javascript"src="js/app.js">

</script>

<title>Maxi Home Renovations</title>
</head>
<body>
<section class="header">

  <!-- custom menu -->
  <div class="nav">
      <div class="logo">
   <img class="imagelogo"src="images/name.png" alt="">
      </div>

      <div class="togg">
          <div></div>
          <div></div>
          <div></div>
      </div>
   <ul class="firstlevel">
   <li><a href=""></a></li>
   <li><a href=""></a></li>
   <li><a href="index.php">Home</a></li>
   <li><a href="services.php">Services</a></li>
   <li class="has-sub"><a>Renovations</a>
              <ul class="sub">
                      <li><a href="kitchen.php">Kitchen</a></li>
                      <li><a href="bathroom.php">Bathroom</a></li>
                      <li><a href="living.php">Living Area</a></li>
                      <li><a href="total.php">Total Renovation</a></li>
                  </ul></li>
          <li><a href="contact.php">Contact Us</a></li>
          <li><a href=""><i class="fa fa-facebook-square"></i></a></li>

        </ul>

    </div>

  <img class="headerImage" src="images/headerImg.png"
  alt="HeaderImage">

</section>

</body>
</code>```

```<code>/*index page*/

<?php
include "includes/header.php" ?>

<section class="feature">

<div class="container">
<div class="row">
  <div class="col-sm-6">
    <div id="carouselExampleInterval" class="carousel slide" data-
       ride="carousel">
      <div class="carousel-inner">
        <div class="carousel-item active" data-interval="5000">
          <img class="imgCar"src="images/h1.JPG" class="d-block w-100"
             alt="...">
        </div>
        <div class="carousel-item" data-interval="5000">
          <img class="imgCar"src="images/h2.JPG" class="d-block w-100"
         alt="...">
        </div>
        <div class="carousel-item" data-interval="5000">
          <img class="imgCar" src="images/h3.jpg" class="d-block w-100"
           alt="...">
        </div>
      </div>
      <a class="carousel-control-prev" href="#carouselExampleInterval"
             role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true">
        </span>
        <span class="sr-only">Previous</span>
      </a>
      <a class="carousel-control-next" href="#carouselExampleInterval"
          role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true">
          </span>
        <span class="sr-only">Next</span>
      </a>
    </div>

  </div>
  <?php
include "includes/footer.php" ?>

.headerImage{
 width: 100%;
 heigth: 300px;
 padding-top:75px;
 color:#bf2132;
 }

 .fimage{
  width: 100%;
  heigth: 300px;
  padding-top:75px;

  }

  .navbar-default{
  background-color:#bf2132;
   border-color: #bf2132;
    }

       /* navigation */

  .nav
   {
   width:100%;
   background-color:#ccc;
   position:fixed;
   top:0;
   left:0;
   z-index: 9999;
   }

  .nav .logo
  {
   display:flex;
   width:200px;
   height: 50px;
   flex-wrap:wrap;
   justify-content: center;
   align-items: center;
   text-transform:uppercase;
   cursor:pointer;
   }
   .imagelogo{
   width:100px;
   heigth:50px;
   }
  .togg
   {
   position:absolute;
   right:40px;
   top:20px;
   display:none;
   z-index: 5;
   }
  .togg div {
   width: 36px;
   height: 2px;
   background-color: red;
   margin: 6px 0px;
   position: relative;
   transition:all .8s ease;
   }
  .togg.lijo div
     {
      position:absolute;
       transition:all .8s ease;
       }
     .togg.lijo div:nth-child(1){
     transform: rotate(48deg);
       top: 7px;
     /* position: absolute; */
     right: 0px;
        }
     .togg.lijo div:nth-child(2)
        {

       width:0px;
       top: 7px;
      /* position: absolute; */
       right: 0px;
       }
       .togg.lijo div:nth-child(3)
      {
       transform: rotate(-48deg);
       top: 7px;
       right: 0px;
       }
     .nav ul.firstlevel
      {
      list-style:none;
      width:calc(100% - 200px);
      background: rgb(191,33,50);
      background: linear-gradient(0deg, rgba(191,33,50,1) 0%,
      rgba(247,77,5,0.9976365546218487) 33%, rgba(191,33,50,1) 100%);
      margin-bottom:0px;
      padding-left:0px;
      }
      .nav ul.firstlevel li
       {
        display:inline-block;
        margin-bottom:0px;
        color:#000;

         }

      .nav ul.firstlevel li a
        {
        cursor:pointer;
         display:block;
        padding:15px;
        transition:.8s ease;
        text-decoration:none;
        text-transform:uppercase;
        color:#fff;
       }
    .nav ul.firstlevel li a:hover
     {
      text-decoration:none;
      }
    .nav ul.firstlevel li ul.sub li {
       display: block;
        background-color:rgba(191,33,50,1);
       }
    .nav ul.firstlevel li ul.sub li:hover {
     display: block;
     background-color:rgba(172, 78, 2, 0.79);
      }
   .nav ul.firstlevel li ul.sub li a{
    color:#fff;
      }
    .nav ul.firstlevel li ul.sub
       {
     width:200px;
     position:absolute;
     padding-left:0px;
     opacity:0;
     visibility: hidden;
    transform:translateY(30px);
    transition:.5s linear;
    padding-top:20px;
   }
  .nav ul.firstlevel li ul.sub:after {
   content: '';
   width: 41px;
   height: 20px;
   border-bottom: solid 18px rgba(191,33,50,1);
   border-left: solid 20px transparent;
   border-right: solid 21px transparent;
   top: 0px;
   display: block;
   position: absolute;
   left: 16px;
    }
  @media(min-width:1024px)
   {
    .nav ul.firstlevel li:hover ul.sub
   {
    visibility:visible;
    opacity:1;
    transform:translateY(0px);
  }
  .nav ul.firstlevel li:hover
 {
   display:inline-block;
   margin-bottom:0px;
   background-color: rgba(27, 27, 27, 0.32);;
   color:#fff !important;
  }
  .nav ul.firstlevel li:hover a
  {
   color:#fff !important;
   }
   }

  @media(max-width:1024px)
  {
   .nav
   {
       min-height:50px;
   }
  .togg
  {
   display:block;
   top:10px;
  }
  .nav ul.firstlevel
   {
    position: absolute;
   top: 50px;
   transform: translateX(100%);
    right: 0;
    transition:.8s ease;
    width:40%;
    height: calc(100vh - 50px);
    z-index: fixed;
  }
  .nav ul.firstlevel li {
   display: block;
   }
 .nav ul.firstlevel.surya {
  transform: translateX(0%);
  }
 .nav ul.firstlevel li ul.sub
 {
  opacity: 1;
  visibility: visible;
  display:none;
  position:relative;
  padding-top:0px;
  width:100%;
  transition:0s;
  transform: translateY(0px);
  }
.nav ul.firstlevel li ul.sub:after
 {
 display:none;
 }

 /* Feature */

 .feature{
 padding-left: 100px;
 padding-right: 100px;
 padding-top: 70px;
 padding-bottom: 70px;
 background-image: url("../images/paper.jpg");
 text-align:center;
 }
.houseimg{
 width: 400px;
 height: 350px;
 border:5px solid rgb(191,33,50);
background-color:#ff0;

 }
.about{
 padding-right: 100px;
 padding-left: 100px;
 padding-bottom: 70px;
 text-align:center;
 background-image: url("../images/paper.jpg");
 }

 /* spinning text */
 #blink{
    width:100%;
    height: 50px;
    padding: 15px;
    text-align: center;
    line-height: 50px;
}
.htext{

    font-family: "Alfa Slab One";
    color: rgb(191,33,50);
    animation: blink 1.5s linear infinite;
     padding-bottom: 100px;
}
     @keyframes blink{
     0%{opacity: 0;}
    50%{opacity: .5;}
   100%{opacity: 1;}
   }

   /* paragraph background */
  .backpar{
   border-radius: 25px;
   background: rgb(191,33,50);
   background: linear-gradient(0deg, rgba(191,33,50,1) 0%,
   rgba(247,77,5,0.9976365546218487) 33%, rgba(191,33,50,1) 100%);
  padding: 20px;
   width: 100%;
   height: 100%;
  color: white;
  font-family: "Concert One";
   }
 .footer{
   background-image: url("../images/footer.png");
    }
    /* Contact */
      .contact{
      padding-left: 70px;
       padding-right: 70px;
       padding-top: 70px;
       padding-bottom: 70px;
       background-image:url("../images/paper.jpg");
      }
     .jumbotron {
        background: rgb(191,33,50);
         color: #FFF;
        border-radius: 0px;

           }
        .jumbotron-sm { padding-top: 24px;
        padding-bottom: 24px; }
       .jumbotron small {
       color: #FFF;
       }
     .h1 small {
     font-size: 24px;
     }

     /*  carousel homepage*/
     .carousel-item{
    width: 100% !important;
     Height: 350px !important;}

   .imgCar{
   width: 100% !important;
   Height: 350px !important;
   border: 2px solid red;
   border-radius: 5px;
   }
</code>```

答:
I have noticed I left out a curly bracket everything is working again

Embarrassed Thank you

Body:
So I wrote a small website and everything was working great, all styles were working but today it only displays the style sheet in mobile view in the normal desktop view it disregards all the styles in my css/style.css

The navbar and header imag keeps their style regardless of the size of the browser just the rest of the styles are gone when in desktop view

My header and footer is included in all pages with php includes the files is in includes/header.php and includes/footer.php

Here is the link to the project as well  to look at maxi.maxihome.co.za

<!DOCTYPE html>

    <meta charset="utf-8">

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

 <link href="https://fonts.googleapis.com/css?
 family=Acme|Neuton&display=swap" rel="stylesheet"><link
 href="https://fonts.googleapis.com/css?
 family=Acme|Neuton|PT+Mono&display=swap" rel="stylesheet"><link
 href="https://fonts.googleapis.com/css?
 family=Acme|Neuton|PT+Mono|Sintony&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?
family=Acme|Molengo|Neuton|PT+Mono|Sintony&display=swap"
 rel="stylesheet">

<title>Maxi Home Renovations</title>

Home

Services

Renovations

Kitchen

Bathroom

Living Area

Total Renovation

Contact Us

/*index page*/

<?php
include "includes/header.php" ?>

        Previous

        Next

  <?php
include "includes/footer.php" ?>

.headerImage{
 width: 100%;
 heigth: 300px;
 padding-top:75px;
 color:#bf2132;
 }

 .fimage{
  width: 100%;
  heigth: 300px;
  padding-top:75px;

  }

  .navbar-default{
  background-color:#bf2132;
   border-color: #bf2132;
    }

       /* navigation */

  .nav
   {
   width:100%;
   background-color:#ccc;
   position:fixed;
   top:0;
   left:0;
   z-index: 9999;
   }

  .nav .logo
  {
   display:flex;
   width:200px;
   height: 50px;
   flex-wrap:wrap;
   justify-content: center;
   align-items: center;
   text-transform:uppercase;
   cursor:pointer;
   }
   .imagelogo{
   width:100px;
   heigth:50px;
   }
  .togg
   {
   position:absolute;
   right:40px;
   top:20px;
   display:none;
   z-index: 5;
   }
  .togg div {
   width: 36px;
   height: 2px;
   background-color: red;
   margin: 6px 0px;
   position: relative;
   transition:all .8s ease;
   }
  .togg.lijo div
     {
      position:absolute;
       transition:all .8s ease;
       }
     .togg.lijo div:nth-child(1){
     transform: rotate(48deg);
       top: 7px;
     /* position: absolute; */
     right: 0px;
        }
     .togg.lijo div:nth-child(2)
        {

       width:0px;
       top: 7px;
      /* position: absolute; */
       right: 0px;
       }
       .togg.lijo div:nth-child(3)
      {
       transform: rotate(-48deg);
       top: 7px;
       right: 0px;
       }
     .nav ul.firstlevel
      {
      list-style:none;
      width:calc(100% - 200px);
      background: rgb(191,33,50);
      background: linear-gradient(0deg, rgba(191,33,50,1) 0%,
      rgba(247,77,5,0.9976365546218487) 33%, rgba(191,33,50,1) 100%);
      margin-bottom:0px;
      padding-left:0px;
      }
      .nav ul.firstlevel li
       {
        display:inline-block;
        margin-bottom:0px;
        color:#000;

         }

      .nav ul.firstlevel li a
        {
        cursor:pointer;
         display:block;
        padding:15px;
        transition:.8s ease;
        text-decoration:none;
        text-transform:uppercase;
        color:#fff;
       }
    .nav ul.firstlevel li a:hover
     {
      text-decoration:none;
      }
    .nav ul.firstlevel li ul.sub li {
       display: block;
        background-color:rgba(191,33,50,1);
       }
    .nav ul.firstlevel li ul.sub li:hover {
     display: block;
     background-color:rgba(172, 78, 2, 0.79);
      }
   .nav ul.firstlevel li ul.sub li a{
    color:#fff;
      }
    .nav ul.firstlevel li ul.sub
       {
     width:200px;
     position:absolute;
     padding-left:0px;
     opacity:0;
     visibility: hidden;
    transform:translateY(30px);
    transition:.5s linear;
    padding-top:20px;
   }
  .nav ul.firstlevel li ul.sub:after {
   content: '';
   width: 41px;
   height: 20px;
   border-bottom: solid 18px rgba(191,33,50,1);
   border-left: solid 20px transparent;
   border-right: solid 21px transparent;
   top: 0px;
   display: block;
   position: absolute;
   left: 16px;
    }
  @media(min-width:1024px)
   {
    .nav ul.firstlevel li:hover ul.sub
   {
    visibility:visible;
    opacity:1;
    transform:translateY(0px);
  }
  .nav ul.firstlevel li:hover
 {
   display:inline-block;
   margin-bottom:0px;
   background-color: rgba(27, 27, 27, 0.32);;
   color:#fff !important;
  }
  .nav ul.firstlevel li:hover a
  {
   color:#fff !important;
   }
   }

  @media(max-width:1024px)
  {
   .nav
   {
       min-height:50px;
   }
  .togg
  {
   display:block;
   top:10px;
  }
  .nav ul.firstlevel
   {
    position: absolute;
   top: 50px;
   transform: translateX(100%);
    right: 0;
    transition:.8s ease;
    width:40%;
    height: calc(100vh - 50px);
    z-index: fixed;
  }
  .nav ul.firstlevel li {
   display: block;
   }
 .nav ul.firstlevel.surya {
  transform: translateX(0%);
  }
 .nav ul.firstlevel li ul.sub
 {
  opacity: 1;
  visibility: visible;
  display:none;
  position:relative;
  padding-top:0px;
  width:100%;
  transition:0s;
  transform: translateY(0px);
  }
.nav ul.firstlevel li ul.sub:after
 {
 display:none;
 }

 /* Feature */

 .feature{
 padding-left: 100px;
 padding-right: 100px;
 padding-top: 70px;
 padding-bottom: 70px;
 background-image: url("../images/paper.jpg");
 text-align:center;
 }
.houseimg{
 width: 400px;
 height: 350px;
 border:5px solid rgb(191,33,50);
background-color:#ff0;

 }
.about{
 padding-right: 100px;
 padding-left: 100px;
 padding-bottom: 70px;
 text-align:center;
 background-image: url("../images/paper.jpg");
 }

 /* spinning text */
 #blink{
    width:100%;
    height: 50px;
    padding: 15px;
    text-align: center;
    line-height: 50px;
}
.htext{

    font-family: "Alfa Slab One";
    color: rgb(191,33,50);
    animation: blink 1.5s linear infinite;
     padding-bottom: 100px;
}
     @keyframes blink{
     0%{opacity: 0;}
    50%{opacity: .5;}
   100%{opacity: 1;}
   }

   /* paragraph background */
  .backpar{
   border-radius: 25px;
   background: rgb(191,33,50);
   background: linear-gradient(0deg, rgba(191,33,50,1) 0%,
   rgba(247,77,5,0.9976365546218487) 33%, rgba(191,33,50,1) 100%);
  padding: 20px;
   width: 100%;
   height: 100%;
  color: white;
  font-family: "Concert One";
   }
 .footer{
   background-image: url("../images/footer.png");
    }
    /* Contact */
      .contact{
      padding-left: 70px;
       padding-right: 70px;
       padding-top: 70px;
       padding-bottom: 70px;
       background-image:url("../images/paper.jpg");
      }
     .jumbotron {
        background: rgb(191,33,50);
         color: #FFF;
        border-radius: 0px;

           }
        .jumbotron-sm { padding-top: 24px;
        padding-bottom: 24px; }
       .jumbotron small {
       color: #FFF;
       }
     .h1 small {
     font-size: 24px;
     }

     /*  carousel homepage*/
     .carousel-item{
    width: 100% !important;
     Height: 350px !important;}

   .imgCar{
   width: 100% !important;
   Height: 350px !important;
   border: 2px solid red;
   border-radius: 5px;
   }


来源: stackexchange

问:
How to display a pdf document within an iframe by google docs viewer stored in firebase storage?
I have an iframe in which I want to put a preview of my pdf document hosted in firebase storage through google docs viewer. I am creating the html view in javascript dynamically and adding it by jquery's ('.someClass').html() method.

I tried to plug in the download url of the document to the iframe directly and it works just fine and displays the preview.

But I can't get it to display the preview through google docs.

What I meant is that this works just fine:

```<code>....making  my html on the fly in javascript

myHtml+='<iframe src="'+downloadUrlFirebaseStorage+'" width="100%"   frameborder="0"/>'

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);
</code>```

But this gets me an error:

```<code>....making  my html on the fly in javascript

myHtml+='<iframe src="https://docs.google.com/viewer?url='+downloadUrlFirebaseStorage+'&embedded=true" width="100%"   frameborder="0"/>'

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);
</code>```

The error I get is this:

```<code>Refused to display 'https://docs.google.com/gview?url=https://firebasestorage.googleapis.com/v0/b/habiganjmedicalcollege.appspot.com/o/documents%2FSampleDoc.pdf?alt=media&token=51df7c93-0c59-46a4-9229-267bc527705b%26embedded=true' in a frame because it set 'X-Frame-Options' to 'sameorigin'
</code>```

答:
I just had to encode the URI and change the '%26' to '&':</p>

```<code>var encodedUrl = encodeURIComponent(downloadUrlFirebaseStorage);

....making  my html on the fly in javascript

myHtml+='<iframe src="https://docs.google.com/viewer?url='+encodedUrl+'&embedded=true" width="100%"   frameborder="0"/>'

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an iframe in which I want to put a preview of my pdf document hosted in firebase storage through google docs viewer. I am creating the html view in javascript dynamically and adding it by jquery's ('.someClass').html() method.

I tried to plug in the download url of the document to the iframe directly and it works just fine and displays the preview.

But I can't get it to display the preview through google docs.

What I meant is that this works just fine:

....making  my html on the fly in javascript

myHtml+=''

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);

But this gets me an error:

....making  my html on the fly in javascript

myHtml+=''

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);

The error I get is this:

Refused to display 'https://docs.google.com/gview?url=https://firebasestorage.googleapis.com/v0/b/habiganjmedicalcollege.appspot.com/o/documents%2FSampleDoc.pdf?alt=media&token=51df7c93-0c59-46a4-9229-267bc527705b%26embedded=true' in a frame because it set 'X-Frame-Options' to 'sameorigin'

Body:
I just had to encode the URI and change the '%26' to '&':

var encodedUrl = encodeURIComponent(downloadUrlFirebaseStorage);

....making  my html on the fly in javascript

myHtml+='<iframe src="https://docs.google.com/viewer?url='+encodedUrl+'&embedded=true" width="100%"   frameborder="0"/>'

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);


问:
RegEx for finding matches between quotes
Here i am trying to find String within double quotes .

```<code>   List<String> getList(String value){
    String regex = "\"[^\"]*\"|[^,]+";
    List<String> allMatches = new ArrayList<String>();
    if (StringUtils.isNotBlank(value)) {
        Matcher m = Pattern.compile(regex).matcher(value);
        while (m.find() && StringUtils.isNotBlank(m.group())) {
            String str=m.group().replaceAll("^\"|\"$", "");
            allMatches.add(str.trim());
        }
    }
    return allMatches;
  }

  result = getList(400,test,\"don't split, this\",15);
  result have [400,test,don't split, this,15] all comma seperated string except inside quotes.
</code>```

It is working well for pattern "" but not for “” .  "foo,bar", is different than "foo,bar"  here is not working regex

答:
Try this:

```<code>Pattern regex = Pattern.compile("[\"\u201C](.*)[\"\u201D]");
List<> allMatches = new ArrayList<String>();
Matcher m = regex.matcher(value);
while (m.find()) {
    allMatches.add(m.group(1).trim());
}
</code>```

A lot simpler and does exactly what you want (matches things in either normal quotes, or 'nice' quotes, but not if you mix them or if you fail to start or close them).

Body:
Here i am trying to find String within double quotes .

   List<String> getList(String value){
    String regex = "\"[^\"]*\"|[^,]+";
    List<String> allMatches = new ArrayList<String>();
    if (StringUtils.isNotBlank(value)) {
        Matcher m = Pattern.compile(regex).matcher(value);
        while (m.find() && StringUtils.isNotBlank(m.group())) {
            String str=m.group().replaceAll("^\"|\"$", "");
            allMatches.add(str.trim());
        }
    }
    return allMatches;
  }

  result = getList(400,test,\"don't split, this\",15);
  result have [400,test,don't split, this,15] all comma seperated string except inside quotes.

It is working well for pattern "" but not for “” .  "foo,bar", is different than "foo,bar"  here is not working regex

Body:
Try this:

Pattern regex = Pattern.compile("[\"\u201C](.*)[\"\u201D]");
List<> allMatches = new ArrayList<String>();
Matcher m = regex.matcher(value);
while (m.find()) {
    allMatches.add(m.group(1).trim());
}

A lot simpler and does exactly what you want (matches things in either normal quotes, or 'nice' quotes, but not if you mix them or if you fail to start or close them).


问:
How to make a splitscreen with a listview on one side
I want the right side of the activity to show different items depending which item of the listview on the left is selected. I was able to follow the Android ListView example where the listview  takes up the whole activity screen, but was unable to expand that to split screen. Here is my xml with the list view on the left and a simple button on the right for now. I'm having trouble figuring out the code that will populate my listview.

system_status.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/activity_system_status"
       android:title="@string/system_status"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="horizontal">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">

        <ListView
        android:id="@+id/my_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        </ListView>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
    </LinearLayout>
    </LinearLayout>
</code>```

UPDATE:
I figured it out with the help of Scythe's post. Here is the code that got it working. The xml above works as is.

```<code>public class SystemStatusActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView lv = (ListView) findViewById(R.id.my_list);
    String[] stats = getResources().getStringArray(R.array.array_system_status);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, stats));
}
}
</code>```

list_item.xml:

```<code>     <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>
</code>```

答:
Try something like

```<code><LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
The above block was new
<LinearLayout
    android:layout_width="0dp" <--BIG CHANGE HERE
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_weight="1">

    <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    </ListView>

</LinearLayout>

<LinearLayout
    android:layout_width="0dp" Big change here
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_weight="1">
    <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
</LinearLayout>

</Linearlayout> NEW
</code>```

The big changes here were to change the layout_width for the linearlayouts you had, so they evenly share the space, and I also put them both in a horizontal linear layout.

ContentLicense: CC BY-SA 3.0

Body:
I want the right side of the activity to show different items depending which item of the listview on the left is selected. I was able to follow the Android ListView example where the listview  takes up the whole activity screen, but was unable to expand that to split screen. Here is my xml with the list view on the left and a simple button on the right for now. I'm having trouble figuring out the code that will populate my listview.

system_status.xml:

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/activity_system_status"
       android:title="@string/system_status"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="horizontal">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">

        <ListView
        android:id="@+id/my_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        </ListView>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
    </LinearLayout>
    </LinearLayout>

UPDATE:
I figured it out with the help of Scythe's post. Here is the code that got it working. The xml above works as is.

public class SystemStatusActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView lv = (ListView) findViewById(R.id.my_list);
    String[] stats = getResources().getStringArray(R.array.array_system_status);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, stats));
}
}

list_item.xml:

     <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

Body:
Try something like

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
The above block was new
<LinearLayout
    android:layout_width="0dp" <--BIG CHANGE HERE
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_weight="1">

    <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    </ListView>

</LinearLayout>

<LinearLayout
    android:layout_width="0dp" Big change here
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_weight="1">
    <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
</LinearLayout>

</Linearlayout> NEW

The big changes here were to change the layout_width for the linearlayouts you had, so they evenly share the space, and I also put them both in a horizontal linear layout.


问:
Jenkins Diamond Dependency with Passed Parameter
I would like to be able to set up dependencies between my builds like so:

```<code>B ---> D
^      ^
|      |
A ---> C
</code>```

Where A is passed a date parameter. Which is passed to B and C, and then to D.

I know there is the Parameterized Trigger Plugin. This, for example, lets me configure in A: "when finished, run B and C with my parameters"

But I don't understand how I then make D wait until both B and C are finished and get passed the parameter.

How do I achieve this?

More info: A will run periodically, it has a date parameter on it which defaults to the current date. I want this date to be passed to the downstream jobs in case they run on the following day.

答:
My solution was to use a parameterized pipeline, with a date parameter asof, and the following pipeline script:

node {
    echo "${asof}"
    build(job: "A", parameters: [string(name: "asof", value: "${asof}")])
    parallel(
        "B": {
            build(job: "B", parameters: [string(name: "asof", value: "${asof}")])
        },
        "C": {
            build(job: "C", parameters: [string(name: "asof", value: "${asof}")])
        }
    )
    build(job: "D", parameters: [string(name: "asof", value: "${asof}")])
}
```

Body:
I would like to be able to set up dependencies between my builds like so:

B ---> D
^      ^
|      |
A ---> C

Where A is passed a date parameter. Which is passed to B and C, and then to D.

I know there is the Parameterized Trigger Plugin. This, for example, lets me configure in A: "when finished, run B and C with my parameters"

But I don't understand how I then make D wait until both B and C are finished and get passed the parameter.

How do I achieve this?

More info: A will run periodically, it has a date parameter on it which defaults to the current date. I want this date to be passed to the downstream jobs in case they run on the following day.


问:
Adding two lambda-functions in C++
I am trying to add two c++ lambda-funtions. What I mean by that is the following:

Assume you have two functions f and g with one or more arguments each, lets say f(x,y) and g(x,y). I want to add both of them into a new function h like this:

```<code>h = f + g
</code>```

And the evaluation should work like this:

```<code>h(x,y) = f(x,y) + g(x,y)
</code>```

So far I have tried the following code, but it does not work. The "cin" at the end is just there to prevent the console from closing automatically.

```<code>#include <iostream>
#include <functional>

using namespace std;

function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
    return [&](int x, int y)->int{return g(x, y) + f(x, y); };
}

int main()
{
    int i = 0;

    function<int (int,int)> sum = [](int x, int y)->int { return x + y; };
    function<int (int,int)> mul = [](int x, int y)->int { return x * y; };
    cout << sum(1, 2) << endl;
    cout << mul(3, 4) << endl;

    function<int(int, int)> s = add(sum, mul);

    cout << s(2, 3) << endl;

    cin >> i;
}
</code>```

The code compiles but it stops working when I try to evaluate s(2,3). It just says the programm stopped working and I have to close it. I am using Visual Studio 2013.

Does anyone know how to do this right? Or do you know any libraries that can do this out of the box?

答:
It's subtle.

```<code>function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
    return [&](int x, int y)->int{return g(x, y) + f(x, y); };
         // ^-- This here
}
</code>```

You capture g and f by reference, and store those references in the std::function you return. But those are references to a function's local variables, so they dangle the second you return. Your code therefore simply has undefined behavior.

A simple fix would be to capture by value [=].

Title: Adding two lambda-functions in C++

Body:
I am trying to add two c++ lambda-funtions. What I mean by that is the following:

Assume you have two functions f and g with one or more arguments each, lets say f(x,y) and g(x,y). I want to add both of them into a new function h like this:

h = f + g

And the evaluation should work like this:

h(x,y) = f(x,y) + g(x,y)

So far I have tried the following code, but it does not work. The "cin" at the end is just there to prevent the console from closing automatically.

#include <iostream>
#include <functional>

using namespace std;

function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
    return [&](int x, int y)->int{return g(x, y) + f(x, y); };
}

int main()
{
    int i = 0;

    function<int (int,int)> sum = [](int x, int y)->int { return x + y; };
    function<int (int,int)> mul = [](int x, int y)->int { return x * y; };
    cout << sum(1, 2) << endl;
    cout << mul(3, 4) << endl;

    function<int(int, int)> s = add(sum, mul);

    cout << s(2, 3) << endl;

    cin >> i;
}

The code compiles but it stops working when I try to evaluate s(2,3). It just says the programm stopped working and I have to close it. I am using Visual Studio 2013.

Does anyone know how to do this right? Or do you know any libraries that can do this out of the box?

Body:
It's subtle.

function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
    return [&](int x, int y)->int{return g(x, y) + f(x, y); };
         // ^-- This here
}

You capture g and f by reference, and store those references in the std::function you return. But those are references to a function's local variables, so they dangle the second you return. Your code therefore simply has undefined behavior.

A simple fix would be to capture by value [=].


问:
Click behind fragment when DialogFragment is shown
I need to have access for click on my behind fragment ( such as click on a button ) when DialogFragment is shown.

But when I click outside of DialogFragment, this will dismiss.

Used code to show DialogFragment:

```<code>FragmentManager fragmentManager = getFragmentManager();

MyDialogMapFragment dialogFragment = new MyDialogMapFragment();
dialogFragment.show( fragmentManager, "" );
</code>```

MyDialogMapFragment Class:

```<code>public class MyDialogMapFragment extends DialogFragment {

    private Activity mActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.dialog_map_info, container, false);

        return rootView;

    }

    public Dialog onCreateDialog(Bundle savedInstanceState) {

        Dialog dialog = new Dialog(getActivity(), R.style.DialogMap);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_map_info);
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;

        dialog.getWindow().setAttributes(lp);

        return dialog;

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }

    }

}
</code>```

dialog_map_info.xml Layout:

```<code><FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="90dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp">

    <RelativeLayout
        android:id="@+id/mainFrame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:clickable="true"
        android:focusable="true"
        android:background="@drawable/background_map_info">

        <ProgressBar
            android:id="@+id/progress_loader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_centerInParent="true"
            style="?android:attr/progressBarStyle" />

        <TextView
            android:id="@+id/itemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Test" />

    </RelativeLayout>

</FrameLayout>
</code>```

Below image will describe what is my layout:

答:
If you need to detect a click the while a dialog is being shown it would be easier to set an onClickListener to a view on your dialog.

When you the onClickListener is called then you can either perform a click on the button button.perfomClick() or even better call the function that the button onClickListener calls.

Body:
I need to have access for click on my behind fragment ( such as click on a button ) when DialogFragment is shown.

But when I click outside of DialogFragment, this will dismiss.

Used code to show DialogFragment:

FragmentManager fragmentManager = getFragmentManager();

MyDialogMapFragment dialogFragment = new MyDialogMapFragment();
dialogFragment.show( fragmentManager, "" );

MyDialogMapFragment Class:

public class MyDialogMapFragment extends DialogFragment {

    private Activity mActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.dialog_map_info, container, false);

        return rootView;

    }

    public Dialog onCreateDialog(Bundle savedInstanceState) {

        Dialog dialog = new Dialog(getActivity(), R.style.DialogMap);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_map_info);
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;

        dialog.getWindow().setAttributes(lp);

        return dialog;

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }

    }

}

dialog_map_info.xml Layout:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="90dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp">

    <RelativeLayout
        android:id="@+id/mainFrame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:clickable="true"
        android:focusable="true"
        android:background="@drawable/background_map_info">

        <ProgressBar
            android:id="@+id/progress_loader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_centerInParent="true"
            style="?android:attr/progressBarStyle" />

        <TextView
            android:id="@+id/itemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Test" />

    </RelativeLayout>

</FrameLayout>

Below image will describe what is my layout:


问:
Fastest way to fill a matrix with Random bytes
I want to fill an array with random values. The code I wrote is this one:

```<code>public class PersonalityMap
{
    const int size = 16;
    byte[,] fullMap = new byte[size, size];

    /// <summary>
    /// Generates a random map
    /// </summary>
    public PersonalityMap()
    {
        Random random = new Random();
        byte[] row = new byte[size];
        for (int i = 0; i < size; i++)
        {
            random.NextBytes(row);
            for (int j = 0; j < size; j++)
                fullMap[i, j] = row[j];
        }
    }
}
</code>```

But I feel there's a way to do it faster.

答:
Jagged arrays (arrays of arrays) are consider faster than multidimensional arrays, but you will get speed up of a few ms. Is this worth it?

This optimization is not worth to spend your time on it.

Body:
I want to fill an array with random values. The code I wrote is this one:

public class PersonalityMap
{
    const int size = 16;
    byte[,] fullMap = new byte[size, size];

    ///
    /// Generates a random map
    ///
    public PersonalityMap()
    {
        Random random = new Random();
        byte[] row = new byte[size];
        for (int i = 0; i < size; i++)
        {
            random.NextBytes(row);
            for (int j = 0; j < size; j++)
                fullMap[i, j] = row[j];
        }
    }
}

But I feel there's a way to do it faster.


问:
How can I restructure this dataframe?
I'm trying to get data from a sqlite query into a format for pygal.

I need to get from something like this -

```<code>count(id)  pdate         station
1          2019-05-19    Gem 106
1          2019-05-14    Absolute Radio
2          2019-04-26    Gem 106
2          2019-05-01    Gem 106
2          2019-04-27    Gem 106
1          2019-05-17    Absolute Radio
1          2019-05-05    Gem 106
3          2019-05-12    Kiss
</code>```

to something like this -

```<code>pdate       Gem 106   Absolute Radio    Kiss
2019-05-19  3         0                 5
2019-05-20  6         6                 5
</code>```

I don't think pivots are the answer but don't understand stack / unstack well enough - could do with a pointer or two?

Many thanks

答:
Duh - yeah, it's a pivot table. Funny how you can't see things sometimes - especially when it's late.

Apols for an imperfect question - the example I gave didn't add up.

Thanks for the replies though.

Title: How can I restructure this dataframe?

Body:
I'm trying to get data from a sqlite query into a format for pygal.

I need to get from something like this -

count(id)  pdate         station
1          2019-05-19    Gem 106
1          2019-05-14    Absolute Radio
2          2019-04-26    Gem 106
2          2019-05-01    Gem 106
2          2019-04-27    Gem 106
1          2019-05-17    Absolute Radio
1          2019-05-05    Gem 106
3          2019-05-12    Kiss

to something like this -

pdate       Gem 106   Absolute Radio    Kiss
2019-05-19  3         0                 5
2019-05-20  6         6                 5

I don't think pivots are the answer but don't understand stack / unstack well enough - could do with a pointer or two?

Many thanks


问:
How do I make a build system for Sublime 3 to compile the current cs file? (C#)
For example, if my current file in sublime is foo.cs, I want it to run "csc /out:foo.exe foo.cs". I don't want to run a full msbuild.</p>

答:
You can create a new Build System with the following configurations.</p>

```<code>{
"cmd":["csc","$file"],
"selector":"source.cs",
"variants" :
[
    {
        "cmd" : "$file_base_name.exe",
        "name"  : "run",
        "shell" : true,
    }
]
}
</code>```

Body:
You can create a new Build System with the following configurations.

{
"cmd":["csc","$file"],
"selector":"source.cs",
"variants" :
[
    {
        "cmd" : "$file_base_name.exe",
        "name"  : "run",
        "shell" : true,
    }
]
}


问:
Prevent GroovyDefaultMethods join() from shadowing join() method of Java class?
I'm trying to use a Java library in Groovy, but Groovy is overriding one of the methods name join with its own method.

The following code fails:

```<code>%%classpath add mvn
tech.tablesaw tablesaw-core 0.32.6
tech.tablesaw tablesaw-beakerx 0.32.6
com.jimmoores quandl-tablesaw 2.0.0

%import com.jimmoores.quandl.*
%import com.jimmoores.quandl.tablesaw.*
%import tech.tablesaw.api.*

// display Tablesaw tables with BeakerX table display widget
tech.tablesaw.beakerx.TablesawDisplayer.register()

TableSawQuandlSession session = TableSawQuandlSession.create();
Table table1 = session.getDataSet(DataSetRequest.Builder.of("FRED/BCNSDODNS").build());
table1.column("Value").setName("Corporate Credit");
Table table2 = session.getDataSet(DataSetRequest.Builder.of("FRED/CMDEBT").build());
table2.column("Value").setName("Household Credit");
Table result = table1.join("Date").inner(table2, "Date");
</code>```

The error is:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.inner() is applicable for argument types: (tech.tablesaw.api.Table, java.lang.String)

This is strange Table.join(String) returns a DataFrameJoiner: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.32.6/tech/tablesaw/api/Table.html#join-java.lang.String...-

I think what's happening is that Table is an Iterable<Row> so maybe Groovy is picking up its own join method.

Where it gets really strange is that it works if I switch the Tablesaw version from 0.32.6 to 0.24.9 even though Table also implements Iterable<Row> in that version

Any idea how I can force Groovy to use the join method from the Tablesaw library instead of its own join method?

答:
You run into this problem because the prototype of the Table.join() method is the following:

```<code>public DataFrameJoiner join(String... columnNames)
</code>```

Source: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.32.6/tech/tablesaw/api/Table.html#join-java.lang.String...-

You have already noticed that Groovy enhances Iterable<T> class with its join() method, but its prototype is the following:

```<code>public String join(String separator)
</code>```

Source: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#join(java.lang.String)

This is why in the case of the following:

```<code>table1.join("Date").inner(table2, "Date");
</code>```

Groovy resolves Iterable<T>.join(String separator) instead of the method from the Table class. It worked fine with the version 0.24.9 only because it was providing a method with the following prototype:

```<code>public DataFrameJoiner join(String columnName)
</code>```

Source: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.24.9/tech/tablesaw/api/Table.html#join-java.lang.String-

So in this case, Table.join(String columnName) was overriding a method Iterable<T>.join(String separator).

The solution

You can solve this problem by making a call with an explicit String[] parameter information, so Groovy picks the correct method right away.

```<code>table1.join(["Date"] as String[]).inner(table2, "Date")
</code>```

It would work without any explicit parameter type information if you pass two strings to make Groovy pick the varargs method.

```<code>table1.join("Date", "Something").inner(table2, "Date")
</code>```

However, in case of a single string argument, you need to make an explicit parameter choice because of the two overloading methods definition.

Body:
I'm trying to use a Java library in Groovy, but Groovy is overriding one of the methods name join with its own method.

The following code fails:

%%classpath add mvn
tech.tablesaw tablesaw-core 0.32.6
tech.tablesaw tablesaw-beakerx 0.32.6
com.jimmoores quandl-tablesaw 2.0.0

%import com.jimmoores.quandl.*
%import com.jimmoores.quandl.tablesaw.*
%import tech.tablesaw.api.*

// display Tablesaw tables with BeakerX table display widget
tech.tablesaw.beakerx.TablesawDisplayer.register()

TableSawQuandlSession session = TableSawQuandlSession.create();
Table table1 = session.getDataSet(DataSetRequest.Builder.of("FRED/BCNSDODNS").build());
table1.column("Value").setName("Corporate Credit");
Table table2 = session.getDataSet(DataSetRequest.Builder.of("FRED/CMDEBT").build());
table2.column("Value").setName("Household Credit");
Table result = table1.join("Date").inner(table2, "Date");

The error is:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.inner() is applicable for argument types: (tech.tablesaw.api.Table, java.lang.String)

This is strange Table.join(String) returns a DataFrameJoiner: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.32.6/tech/tablesaw/api/Table.html#join-java.lang.String...-

I think what's happening is that Table is an Iterable<Row> so maybe Groovy is picking up its own join method.

Where it gets really strange is that it works if I switch the Tablesaw version from 0.32.6 to 0.24.9 even though Table also implements Iterable<Row> in that version

Any idea how I can force Groovy to use the join method from the Tablesaw library instead of its own join method?

Body:
You run into this problem because the prototype of the Table.join() method is the following:

public DataFrameJoiner join(String... columnNames)

Source: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.32.6/tech/tablesaw/api/Table.html#join-java.lang.String...-

You have already noticed that Groovy enhances Iterable<T> class with its join() method, but its prototype is the following:

public String join(String separator)

Source: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#join(java.lang.String)

This is why in the case of the following:

table1.join("Date").inner(table2, "Date");

Groovy resolves Iterable<T>.join(String separator) instead of the method from the Table class. It worked fine with the version 0.24.9 only because it was providing a method with the following prototype:

public DataFrameJoiner join(String columnName)

Source: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.24.9/tech/tablesaw/api/Table.html#join-java.lang.String-

So in this case, Table.join(String columnName) was overriding a method Iterable<T>.join(String separator).

The solution

You can solve this problem by making a call with an explicit String[] parameter information, so Groovy picks the correct method right away.

table1.join(["Date"] as String[]).inner(table2, "Date")

It would work without any explicit parameter type information if you pass two strings to make Groovy pick the varargs method.

table1.join("Date", "Something").inner(table2, "Date")

However, in case of a single string argument, you need to make an explicit parameter choice because of the two overloading methods definition.


问:
YouTube API quota been reduced
I have encounter some problems when using YouTube API recently, and I would like to ask if you have the same problem like I do and if anyone have any solution.

Before, I had 100 millions and 50 millions quotas per day, but I just found out that the quota of some keys with less usage has decreased a lot (500 millions has decreased to 300K and the one with 1 million has decreased to 600K and 10K  )

The info that I found are all from the project of 2016, and the quotas are all 10K or other case like the whole project had been shut down, so the quota is 0. And none of them is the same as the problem that we have encountered. So I would like to ask if anybody knows why does this happen and how can we prevent and resolve it. Thanks a lot!

答:
The default quota limit is now 10,000 units:

Projects that enable the YouTube Data API have a default quota
  allocation of 10 thousand units per day, an amount sufficient for the
  overwhelming majority of our API users...
  https://developers.google.com/youtube/v3/getting-started#quota

Previously they had given 1 million units to new accounts. My own APIs were each reduced from 1 million to 10k also, because I never use even 5k units. You can ask for more units if you reach the quota limit, inside your Developer Console, IAM & Admin > Quotas > EDIT QUOTAS:

Title: YouTube API quota been reduced


问:
exec() runs differently in command line and script
When I try exec() to execute this code in python console and script, it has different results

python console:

```<code>>>> def test():
...     x = 13
...     exec('b = x + 1')
...     print(b)
...
>>> test()
14
>>>
</code>```

python script

```<code>def test2():
    x = 13
    exec('b = x + 1')
    print(b)
</code>```

```<code>  NameError: name 'b' is not defined
</code>```

But with this code, they are the same

python console

```<code>>>> def test1():
...     x = 0
...     exec('x += 1')
...     print(x)
...
>>> test1()
0
</code>```

python script

```<code>def test1():
    x = 0
    exec('x += 1')
    print(x)

test1()
# 0
</code>```

答:
"""
But with this code, they are the same

python console

```<code>>>> def test1():
...     x = 0
...     exec('x += 1')
...     print(x)
...
>>> test1()
0
</code>```

python script

```<code>def test1():
    x = 0
    exec('x += 1')
    print(x)

test1()
# 0
</code>```

"""

Because with this code, x is define , so your function 'exec()' don't work here
it's the same that you have'nt write 'exec'

Body:
When I try exec() to execute this code in python console and script, it has different results

python console:

>>> def test():
...     x = 13
...     exec('b = x + 1')
...     print(b)
...
>>> test()
14
>>>

python script

def test2():
    x = 13
    exec('b = x + 1')
    print(b)

  NameError: name 'b' is not defined

But with this code, they are the same

python console

>>> def test1():
...     x = 0
...     exec('x += 1')
...     print(x)
...
>>> test1()
0

python script

def test1():
    x = 0
    exec('x += 1')
    print(x)

test1()
# 0

Body:
"""
But with this code, they are the same

python console

>>> def test1():
...     x = 0
...     exec('x += 1')
...     print(x)
...
>>> test1()
0

python script

def test1():
    x = 0
    exec('x += 1')
    print(x)

test1()
# 0

"""

Because with this code, x is define , so your function 'exec()' don't work here
it's the same that you have'nt write 'exec'


问:
How do you change the elements in a div using ajax?
have blade files in list format and blade files in image format. There are two span buttons here, and I want to show you a list of different formats when I click each button. How do I write the code?

```<code> <span id="penpal-image-view" class="fa fa-th float-right" style="font- size: 25px;"></span>
        <span id="penpal-list-view" class="fa fa-list float-right" style="font-size: 25px;padding-right:7px;"></span>
</code>```

Currently, two blade files are only checked using the if statement, but I want to change that file when I press span

```<code>  @if( 2 == 2 )
                <div class="row">
                    <div class="col"></div>
                    <div class="col">
                            @include('penpal.component.indexTableList')
                    </div>
                    <div class="col"></div>
                </div>
            @else
                @include('penpal.component.indexImageList')
            @endif
        @endif
</code>```

答:
suppose this is file1 and we getting an image from this file to file 2. This is a file containing image

```<code>echo "<img src="someimage.jpg" />";
</code>```

This is file2 code
we get the image from file1 through AJAX like this:

```<code>$("#penpal-image-view").click( function(){
$.ajax({
    url: "url/to/file1",
    method: "POST",
    success:function(data){
        $(".CLASS-OF-DIV").html(data);
    }
});
</code>```

Body:
have blade files in list format and blade files in image format. There are two span buttons here, and I want to show you a list of different formats when I click each button. How do I write the code?

Currently, two blade files are only checked using the if statement, but I want to change that file when I press span

  @if( 2 == 2 )

                            @include('penpal.component.indexTableList')

            @else
                @include('penpal.component.indexImageList')
            @endif
        @endif

Body:
suppose this is file1 and we getting an image from this file to file 2. This is a file containing image

echo "<img src="someimage.jpg" />";

This is file2 code
we get the image from file1 through AJAX like this:

$("#penpal-image-view").click( function(){
$.ajax({
    url: "url/to/file1",
    method: "POST",
    success:function(data){
        $(".CLASS-OF-DIV").html(data);
    }
});


问:
How to find out the correct encoding when using beautifulsoup?
In python3 and beautifulsoup4 I want to get information from a website, after making the requests. I did so:

```<code>import requests
from bs4 import BeautifulSoup

req = requests.get('https://sisgvarmazenamento.blob.core.windows.net/prd/PublicacaoPortal/Arquivos/201901.htm').text

soup = BeautifulSoup(req,'lxml')

soup.find("h1").text
'\r\n                        CÃ\x82MARA MUNICIPAL DE SÃ\x83O PAULO'
</code>```

I do not know what the encoding is, but it's a site with Brazilian Portuguese, so it should be utf-8 or latin1

Please, is there a way to find out which encoding is correct?

And then do the beautifulsoup read this encoding correctly?

答:
Requests determines encoding like this:

When you receive a response, Requests makes a guess at the encoding to use for decoding the response when you access the Response.text attribute. Requests will first check for an encoding in the HTTP header, and if none is present, will use chardet to attempt to guess the encoding.

The only time Requests will not do this is if no explicit charset is present in the HTTP headers and the Content-Type header contains text. In this situation, RFC 2616 specifies that the default charset must be ISO-8859-1. Requests follows the specification in this case. If you require a different encoding, you can manually set the Response.encoding property, or use the raw Response.content.

Inspecting the request headers show that indeed "no explicit charset is present in the HTTP headers and the Content-Type header contains text"

```<code>>>> req.headers['content-type']
'text/html'
</code>```

So requests faithfully follows the standard and decodes as ISO-8859-1 (latin-1).

In the response content, a charset is specified:

```<code><META http-equiv="Content-Type" content="text/html; charset=utf-16">
</code>```

however this is wrong: decoding as UTF-16 produces mojibake.

chardet correctly identifies the encoding as UTF-8.

So to summarise:

there is no general way to determine text encoding with complete accuracy

in this particular case, the correct encoding is UTF-8.

Working code:

```<code>>>> req.encoding = 'UTF-8'
>>> soup = bs4.BeautifulSoup(req.text,'lxml')
>>> soup.find('h1').text
'\r\n                        CÂMARA MUNICIPAL DE SÃO PAULO'
</code>```

Body:
In python3 and beautifulsoup4 I want to get information from a website, after making the requests. I did so:

import requests
from bs4 import BeautifulSoup

req = requests.get('https://sisgvarmazenamento.blob.core.windows.net/prd/PublicacaoPortal/Arquivos/201901.htm').text

soup = BeautifulSoup(req,'lxml')

soup.find("h1").text
'\r\n                        CÃ\x82MARA MUNICIPAL DE SÃ\x83O PAULO'

I do not know what the encoding is, but it's a site with Brazilian Portuguese, so it should be utf-8 or latin1

Please, is there a way to find out which encoding is correct?

And then do the beautifulsoup read this encoding correctly?

Body:
Requests determines encoding like this:

When you receive a response, Requests makes a guess at the encoding to use for decoding the response when you access the Response.text attribute. Requests will first check for an encoding in the HTTP header, and if none is present, will use chardet to attempt to guess the encoding.

The only time Requests will not do this is if no explicit charset is present in the HTTP headers and the Content-Type header contains text. In this situation, RFC 2616 specifies that the default charset must be ISO-8859-1. Requests follows the specification in this case. If you require a different encoding, you can manually set the Response.encoding property, or use the raw Response.content.

Inspecting the request headers show that indeed "no explicit charset is present in the HTTP headers and the Content-Type header contains text"

>>> req.headers['content-type']
'text/html'

So requests faithfully follows the standard and decodes as ISO-8859-1 (latin-1).

In the response content, a charset is specified:

<META http-equiv="Content-Type" content="text/html; charset=utf-16">

however this is wrong: decoding as UTF-16 produces mojibake.

chardet correctly identifies the encoding as UTF-8.

So to summarise:

there is no general way to determine text encoding with complete accuracy

in this particular case, the correct encoding is UTF-8.

Working code:

>>> req.encoding = 'UTF-8'
>>> soup = bs4.BeautifulSoup(req.text,'lxml')
>>> soup.find('h1').text
'\r\n                        CÂMARA MUNICIPAL DE SÃO PAULO'


问:
KStreams : How do you get the (originating) topic of a record?
I have the following

//Config setup
Properties props = ...; //setup

List<String> topicList = Arrays.asList({"A", "B", "C"});

StreamBuilder builder = new StreamBuilder();
KStream<String, String> source = builder.stream(topicList);

source
  .map((k,v) -> {

    //How can i get the topic of the record here

  })
  .to((k,v,r) -> {//busy code for topic routing});

new KafkaStream(builder.build(), properties).start();
```

答:
You can get a topic name you need using ProcessorContext.topic().
To get an access to ProcessorContext use KStream.process() providing it with an appropriate Processor implementation.

Also you can use KStream.transform():

```<code>KStream<InputKeyType, InputValueType> stream2 = stream.transform(new TransformerSupplier<InputKeyType, InputValueType, KeyValue<OutputKeyType, OutputValueType>>() {
            @Override
            public Transformer<InputKeyType, InputValueType, KeyValue<OutputKeyType, OutputValueType>> get() {
                return new Transformer<InputKeyType, InputValueType, KeyValue<OutputKeyType, OutputValueType>>() {
                    private ProcessorContext context;

                    @Override
                    public void init(ProcessorContext context) {
                        this.context = context;
                    }

                    @Override
                    public KeyValue<OutputKeyType, OutputValueType> transform(InputKeyType key, InputValueType value) {

                        this.context.topic() // topic name you need
                        // logic here
                        return new KeyValue<>(OutputKeyType key, OutputValueType value);

                    }

                    @Override
                    public void close() {

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

Body:
You can get a topic name you need using ProcessorContext.topic().
To get an access to ProcessorContext use KStream.process() providing it with an appropriate Processor implementation.

Also you can use KStream.transform():

KStream<InputKeyType, InputValueType> stream2 = stream.transform(new TransformerSupplier<InputKeyType, InputValueType, KeyValue<OutputKeyType, OutputValueType>>() {
            @Override
            public Transformer<InputKeyType, InputValueType, KeyValue<OutputKeyType, OutputValueType>> get() {
                return new Transformer<InputKeyType, InputValueType, KeyValue<OutputKeyType, OutputValueType>>() {
                    private ProcessorContext context;

                    @Override
                    public void init(ProcessorContext context) {
                        this.context = context;
                    }

                    @Override
                    public KeyValue<OutputKeyType, OutputValueType> transform(InputKeyType key, InputValueType value) {

                        this.context.topic() // topic name you need
                        // logic here
                        return new KeyValue<>(OutputKeyType key, OutputValueType value);

                    }

                    @Override
                    public void close() {

                    }
                };
            }
        });


问:
How can I secure the use of my dll by other applications
I made some UI controls by WPF and wrap it into a DLL.

As we know, everyone can reference the DLL easily but I don't want it being like that.

I want only the program which I made to use it.

In my opinion, I think I can add something such a password when the user creates the control. However, I don't know if it is a good idea.

I want to know more about that. Would you please tell me? Thank you.

答:
Obfuscating only obscures your source code. What you're actually looking for is .NET Code Access Security ... the linked article demonstrates how to ensure that the calling code has the right permissions to use your code.

This solution however doesn't stop anyone from decompiling your source code and just copying it over bypassing your security (from what I can tell with a quick skim through anyway) so using a combination of obfuscation and implementing code access security might be your best bet.

Using passwords when a user creates your controls also isn't going to work, you can't implement it in that fashion, instead, the person using your controls will need to possess a valid digital signature to use it.


问:
How do I install scitools module on Python3 with Anaconda?
I need to install the scitools module in Anaconda. The commands

```<code>conda install scitools
conda install --channel johannr scitools
conda install -c asmeurer scitools
</code>```

don't work. I'm using Python 3 on Windows 10. I would appreciate any help.

答:
The packages you are trying to install are only available for linux and osx, you can try with this one:

```<code>conda install -c krisvanneste scitools_no_easyviz
</code>```

Though as the name states it seems to not have support for EasyViz

Body:
I need to install the scitools module in Anaconda. The commands

conda install scitools
conda install --channel johannr scitools
conda install -c asmeurer scitools

don't work. I'm using Python 3 on Windows 10. I would appreciate any help.

Body:
The packages you are trying to install are only available for linux and osx, you can try with this one:

conda install -c krisvanneste scitools_no_easyviz

Though as the name states it seems to not have support for EasyViz


问:
I'm having troubles with Java sockets in a client/server type application when having to accept many connections
First of all, thanks for reading. This is my first time in stackoverflow as user, although I've always read it and found useful solutions :D. By the way, sorry if I'm not clear enough explaining myself, I know that my English isn't very good.

My socket based program is having a strange behaviour, and some performance issues. The client and server communicate with each other by reading/writing serialized objects into object input and output streams, in a multi-threaded way. Let me show you the code basics. I have simplified it to be more readable and a complete exception handling for example is intentionally ommited. The server works like this:

Server:

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

public void serve() {
    if (serverSocket == null) {
        try {
            serverSocket = (SSLServerSocket) SSLServerSocketFactory
                                    .getDefault().createServerSocket(port);
            serving = true;
            System.out.println("Waiting for clients...");
            while (serving) {
                SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
                System.out.println("Client accepted.");
                //LjServerThread class is below
                new LjServerThread(clientSocket).start();
            }
        } catch (Exception e) {
            // Exception handling code (...)
        }
    }
}

public void stop() {
    serving = false;
    serverSocket = null;
}

public boolean isServing() {
    return serving;
}
</code>```

LjServerThread class, one instance created per client:

```<code>private SSLSocket clientSocket;
private String IP;
private long startTime;

public LjServerThread(SSLSocket clientSocket) {
        this.clientSocket = clientSocket;
        startTime = System.currentTimeMillis();
        this.IP = clientSocket.getInetAddress().getHostAddress();
}

public synchronized String getClientAddress() {
    return IP;
}

@Override
public void run() {
    ObjectInputStream in = null;
    ObjectOutputStream out = null;
    //This is my protocol handling object, and as you will see below,
    //it works processing the object received and returning another as response.
    LjProtocol protocol = new LjProtocol();
    try {
        try {
            in = new ObjectInputStream(new BufferedInputStream(
                                     clientSocket.getInputStream()));
            out = new ObjectOutputStream(new BufferedOutputStream(
                                    clientSocket.getOutputStream()));
            out.flush();
        } catch (Exception ex) {
            // Exception handling code (...)
        }
        LjPacket output;
        while (true) {
            output = protocol.processMessage((LjPacket) in.readObject());
            // When the object received is the finish mark,
            // protocol.processMessage()object returns null.
            if (output == null) {
                break;
            }
            out.writeObject(output);
            out.flush();
            out.reset();
        }
        System.out.println("Client " + IP + " finished successfully.");
    } catch (Exception ex) {
        // Exception handling code (...)
    } finally {
        try {
            out.close();
            in.close();
            clientSocket.close();
        } catch (Exception ex) {
            // Exception handling code (...)
        } finally {
            long stopTime = System.currentTimeMillis();
            long runTime = stopTime - startTime;
            System.out.println("Run time: " + runTime);
        }
    }
}
</code>```

And, the client, is like this:

```<code>    private SSLSocket socket;

    @Override
    public void run() {
        LjProtocol protocol = new LjProtocol();
        try {
            socket = (SSLSocket) SSLSocketFactory.getDefault()
                     .createSocket(InetAddress.getByName("here-goes-hostIP"),
                                                                       4444);
        } catch (Exception ex) {

        }
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
        out = new ObjectOutputStream(new BufferedOutputStream(
                                         socket.getOutputStream()));
        out.flush();
        in = new ObjectInputStream(new BufferedInputStream(
                                          socket.getInputStream()));
        LjPacket output;
        // As the client is which starts the connection, it sends the first
        //object.
        out.writeObject(/* First object */);
        out.flush();
        while (true) {
            output = protocol.processMessage((LjPacket) in.readObject());
            out.writeObject(output);
            out.flush();
            out.reset();
        }
        } catch (EOFException ex) {
            // If all goes OK, when server disconnects EOF should happen.
            System.out.println("suceed!");
        } catch (Exception ex) {
            // (...)
        } finally {
            try {
                // FIRST STRANGE BEHAVIOUR:
                // I have to comment the "out.close()" line, else, Exception is
                // thrown ALWAYS.
                out.close();
                in.close();
                socket.close();
            } catch (Exception ex) {
                System.out.println("This shouldn't happen!");
            }
        }
    }
}
</code>```

Well, as you see, the LjServerThread class which handles accepted clients in the server side, measures the time it takes... Normally, it takes between 75 - 120 ms (where the x is the IP):

Client x finished successfully.

Run time: 82

Client x finished successfully.

Run time: 80

Client x finished successfully.

Run time: 112

Client x finished successfully.

Run time: 88

Client x finished successfully.

Run time: 90

Client x finished successfully.

Run time: 84

But suddenly, and with no predictable pattern (at least for me):

Client x finished successfully.

Run time: 15426

Sometimes reaches 25 seconds!
Ocasionally a small group of threads go a little slower but that doesn't worry me much:

Client x finished successfully.

Run time: 239

Client x finished successfully.

Run time: 243

Why is this happening? Is this perhaps because my server and my client are in the same machine, with the same IP? (To do this tests I execute the server and the client in the same machine, but they connect over internet, with my public IP).

This is how I test this, I make requests to the server like this in main():

```<code>    for (int i = 0; i < 400; i++) {
        try {
            new LjClientThread().start();
            Thread.sleep(100);
        } catch (Exception ex) {
            // (...)
        }
    }
</code>```

If I do it in loop without "Thread.sleep(100)", I get some connection reset exceptions (7 or 8 connections resetted out of 400, more or less), but I think I understand why it happens: when serverSocket.accept() accepts a connection, a very small amount of time has to be spent to reach serverSocket.accept() again. During that time, the server cannot accept connections. Could it be because of that? If not, why? It would be rare 400 connections arriving to my server exactly at the same time, but it could happen. Without "Thread.sleep(100)", the timing issues are worse also.

Thanks in advance!

UPDATED:

How stupid, I tested it in localhost... and it doesn't give any problem! With and without "Thread.sleep(100)", doesn't matter, it works fine! Why! So, as I can see, my theory about why the connection reset is beeing thrown is not correct. This makes things even more strange! I hope somebody could help me... Thanks again! :)

UPDATED (2):

I have found sightly different behaviours in different operating systems. I usually  develop in Linux, and the behaviour I explained was about what was happening in my Ubuntu 10.10. In Windows 7, when I pause 100ms between connections, all its fine, and all threads are lighting fast, no one takes more than 150ms or so (no slow connection issues!). This is not what is happening in Linux. However, when I remove the "Thread.sleep(100)", instead of only some of the connections getting the connection reset exception, all of them fail and throw the exception (in Linux only some of them, 6 or so out of 400 were failing).

Phew! I've just find out that not only the OS, the JVM enviroment has a little impact also! Not a big deal, but noteworthy. I was using OpenJDK in Linux, and now, with the Oracle JDK, I see that as I reduce the sleep time between connections, it starts failing earlier (with 50 ms OpenJDK works fine, no exceptions are thrown, but with Oracle's one quite a lot with 50ms sleep time, while with 100ms works fine).

答: The server socket has a queue that holds incoming connection attempts. A client will encounter a connection reset error if that queue is full. Without the Thread.sleep(100) statement, all of your clients are trying to connect relatively simultaneously, which results in some of them encountering the connection reset error.

Body:
First of all, thanks for reading. This is my first time in stackoverflow as user, although I've always read it and found useful solutions :D. By the way, sorry if I'm not clear enough explaining myself, I know that my English isn't very good.

My socket based program is having a strange behaviour, and some performance issues. The client and server communicate with each other by reading/writing serialized objects into object input and output streams, in a multi-threaded way. Let me show you the code basics. I have simplified it to be more readable and a complete exception handling for example is intentionally ommited. The server works like this:

Server:

// (...)

public void serve() {
    if (serverSocket == null) {
        try {
            serverSocket = (SSLServerSocket) SSLServerSocketFactory
                                    .getDefault().createServerSocket(port);
            serving = true;
            System.out.println("Waiting for clients...");
            while (serving) {
                SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
                System.out.println("Client accepted.");
                //LjServerThread class is below
                new LjServerThread(clientSocket).start();
            }
        } catch (Exception e) {
            // Exception handling code (...)
        }
    }
}

public void stop() {
    serving = false;
    serverSocket = null;
}

public boolean isServing() {
    return serving;
}

LjServerThread class, one instance created per client:

private SSLSocket clientSocket;
private String IP;
private long startTime;

public LjServerThread(SSLSocket clientSocket) {
        this.clientSocket = clientSocket;
        startTime = System.currentTimeMillis();
        this.IP = clientSocket.getInetAddress().getHostAddress();
}

public synchronized String getClientAddress() {
    return IP;
}

@Override
public void run() {
    ObjectInputStream in = null;
    ObjectOutputStream out = null;
    //This is my protocol handling object, and as you will see below,
    //it works processing the object received and returning another as response.
    LjProtocol protocol = new LjProtocol();
    try {
        try {
            in = new ObjectInputStream(new BufferedInputStream(
                                     clientSocket.getInputStream()));
            out = new ObjectOutputStream(new BufferedOutputStream(
                                    clientSocket.getOutputStream()));
            out.flush();
        } catch (Exception ex) {
            // Exception handling code (...)
        }
        LjPacket output;
        while (true) {
            output = protocol.processMessage((LjPacket) in.readObject());
            // When the object received is the finish mark,
            // protocol.processMessage()object returns null.
            if (output == null) {
                break;
            }
            out.writeObject(output);
            out.flush();
            out.reset();
        }
        System.out.println("Client " + IP + " finished successfully.");
    } catch (Exception ex) {
        // Exception handling code (...)
    } finally {
        try {
            out.close();
            in.close();
            clientSocket.close();
        } catch (Exception ex) {
            // Exception handling code (...)
        } finally {
            long stopTime = System.currentTimeMillis();
            long runTime = stopTime - startTime;
            System.out.println("Run time: " + runTime);
        }
    }
}

And, the client, is like this:

    private SSLSocket socket;

    @Override
    public void run() {
        LjProtocol protocol = new LjProtocol();
        try {
            socket = (SSLSocket) SSLSocketFactory.getDefault()
                     .createSocket(InetAddress.getByName("here-goes-hostIP"),
                                                                       4444);
        } catch (Exception ex) {

        }
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
        out = new ObjectOutputStream(new BufferedOutputStream(
                                         socket.getOutputStream()));
        out.flush();
        in = new ObjectInputStream(new BufferedInputStream(
                                          socket.getInputStream()));
        LjPacket output;
        // As the client is which starts the connection, it sends the first
        //object.
        out.writeObject(/* First object */);
        out.flush();
        while (true) {
            output = protocol.processMessage((LjPacket) in.readObject());
            out.writeObject(output);
            out.flush();
            out.reset();
        }
        } catch (EOFException ex) {
            // If all goes OK, when server disconnects EOF should happen.
            System.out.println("suceed!");
        } catch (Exception ex) {
            // (...)
        } finally {
            try {
                // FIRST STRANGE BEHAVIOUR:
                // I have to comment the "out.close()" line, else, Exception is
                // thrown ALWAYS.
                out.close();
                in.close();
                socket.close();
            } catch (Exception ex) {
                System.out.println("This shouldn't happen!");
            }
        }
    }
}

Well, as you see, the LjServerThread class which handles accepted clients in the server side, measures the time it takes... Normally, it takes between 75 - 120 ms (where the x is the IP):

Client x finished successfully.

Run time: 82

Client x finished successfully.

Run time: 80

Client x finished successfully.

Run time: 112

Client x finished successfully.

Run time: 88

Client x finished successfully.

Run time: 90

Client x finished successfully.

Run time: 84

But suddenly, and with no predictable pattern (at least for me):

Client x finished successfully.

Run time: 15426

Sometimes reaches 25 seconds!
Ocasionally a small group of threads go a little slower but that doesn't worry me much:

Client x finished successfully.

Run time: 239

Client x finished successfully.

Run time: 243

Why is this happening? Is this perhaps because my server and my client are in the same machine, with the same IP? (To do this tests I execute the server and the client in the same machine, but they connect over internet, with my public IP).

This is how I test this, I make requests to the server like this in main():

    for (int i = 0; i < 400; i++) {
        try {
            new LjClientThread().start();
            Thread.sleep(100);
        } catch (Exception ex) {
            // (...)
        }
    }

If I do it in loop without "Thread.sleep(100)", I get some connection reset exceptions (7 or 8 connections resetted out of 400, more or less), but I think I understand why it happens: when serverSocket.accept() accepts a connection, a very small amount of time has to be spent to reach serverSocket.accept() again. During that time, the server cannot accept connections. Could it be because of that? If not, why? It would be rare 400 connections arriving to my server exactly at the same time, but it could happen. Without "Thread.sleep(100)", the timing issues are worse also.

Thanks in advance!

UPDATED:

How stupid, I tested it in localhost... and it doesn't give any problem! With and without "Thread.sleep(100)", doesn't matter, it works fine! Why! So, as I can see, my theory about why the connection reset is beeing thrown is not correct. This makes things even more strange! I hope somebody could help me... Thanks again! :)

UPDATED (2):

I have found sightly different behaviours in different operating systems. I usually  develop in Linux, and the behaviour I explained was about what was happening in my Ubuntu 10.10. In Windows 7, when I pause 100ms between connections, all its fine, and all threads are lighting fast, no one takes more than 150ms or so (no slow connection issues!). This is not what is happening in Linux. However, when I remove the "Thread.sleep(100)", instead of only some of the connections getting the connection reset exception, all of them fail and throw the exception (in Linux only some of them, 6 or so out of 400 were failing).

Phew! I've just find out that not only the OS, the JVM enviroment has a little impact also! Not a big deal, but noteworthy. I was using OpenJDK in Linux, and now, with the Oracle JDK, I see that as I reduce the sleep time between connections, it starts failing earlier (with 50 ms OpenJDK works fine, no exceptions are thrown, but with Oracle's one quite a lot with 50ms sleep time, while with 100ms works fine).


问:
express route with param overriding the static route
I have a code like below

```<code>app.get('/all', callback2);
app.get('/:id', callback);
</code>```

/:id is overriding the route /all.

答:
a good way of solving this problem even though it isnt the best is to define

```<code>app.get('/all', callback2);
</code>```

before the

```<code>app.get('/:id', callback);
</code>```

now the router would first check the first route before the other ones

Body:
I have a code like below

app.get('/all', callback2);
app.get('/:id', callback);

/:id is overriding the route /all.

Body:
a good way of solving this problem even though it isnt the best is to define

app.get('/all', callback2);

before the

app.get('/:id', callback);

now the router would first check the first route before the other ones


问:
How is the r-value reference being passed in here?
```<code>void test(vector<int> v) {
    for(int i:v) cout<< i<<" ";
}
int main()
{
    vector<int> v{ 1,2,3 };
    test(move(v));
    cout << "v is gone....";
}
</code>```

I am new to move semantics and rvalue references. In the code above, the vector is printed. Clearly the move worked.

What I don't understand is how it worked. Why don't I have to define a function that takes in an rvalue reference? My best guess is the compiler is generating this automatically:

```<code>void test(vector<int>&& v) {
    for(int i:v) cout<< i<<" ";
}
</code>```

答:
You can create a vector with an r-value reference to it:

```<code>std::vector<int> a = {1, 2, 3};

std::vector<int> b = std::move(a); // Constructs b from r-value reference
</code>```

This invokes std::vector's move constructor, which basically just copies the data pointer from the first vector to the second vector.

When you invoke the function void test(std::vector<int> v) in your example, the same thing happens: the compiler calls std::vector's move constructor, and creates a new vector in the stack space allocated for the parameter v. No functions are implicitly generated.

The difference between void test(std::vector<int> v), and void test(std::vector<int>&& v).

In the first case, you're passing the vector by value. That means that whenever you call test, the function calling test allocates space for a new vector on the stack before invoking test. It has to call std::vector's constructor, and in the process, it either

moves a vector;

copies a vector; or

magically constructs the vector in-place (this happens if you construct the vector at the site where you call test, for example in test(std::vector<int>{1, 2, 3}))

On the other hand, test(std::vector<int>&& v) takes the argument by reference. This means that when you call this version of test by moving a variable, no new vector gets created. Whatever vector you give it is passed by reference, and as a result any changes that test(std::vector<int>&&) makes to the vector will show up on the original.

For example:

```<code>// Even though v is passed as an r-value reference,
// v is never moved-from inside test(). An object is only moved-from
// If an r-value reference to it is used to construct a new object.
void test(std::vector<int>&& v) {
    v.push_back(4);
}

std::vector<int> myList = {1, 2, 3};
test(std::move(myList)); // Adds 4 to the end of myList

// Prints 1 2 3 4
for(int i : myList) {
    std::cout << i << " ";
}
</code>```

Body:
void test(vector<int> v) {
    for(int i:v) cout<< i<<" ";
}
int main()
{
    vector<int> v{ 1,2,3 };
    test(move(v));
    cout << "v is gone....";
}

I am new to move semantics and rvalue references. In the code above, the vector is printed. Clearly the move worked.

What I don't understand is how it worked. Why don't I have to define a function that takes in an rvalue reference? My best guess is the compiler is generating this automatically:

void test(vector<int>&& v) {
    for(int i:v) cout<< i<<" ";
}

Body:
You can create a vector with an r-value reference to it:

std::vector<int> a = {1, 2, 3};

std::vector<int> b = std::move(a); // Constructs b from r-value reference

This invokes std::vector's move constructor, which basically just copies the data pointer from the first vector to the second vector.

When you invoke the function void test(std::vector<int> v) in your example, the same thing happens: the compiler calls std::vector's move constructor, and creates a new vector in the stack space allocated for the parameter v. No functions are implicitly generated.

The difference between void test(std::vector<int> v), and void test(std::vector<int>&& v).

In the first case, you're passing the vector by value. That means that whenever you call test, the function calling test allocates space for a new vector on the stack before invoking test. It has to call std::vector's constructor, and in the process, it either

moves a vector;

copies a vector; or

magically constructs the vector in-place (this happens if you construct the vector at the site where you call test, for example in test(std::vector<int>{1, 2, 3}))

On the other hand, test(std::vector<int>&& v) takes the argument by reference. This means that when you call this version of test by moving a variable, no new vector gets created. Whatever vector you give it is passed by reference, and as a result any changes that test(std::vector<int>&&) makes to the vector will show up on the original.

For example:

// Even though v is passed as an r-value reference,
// v is never moved-from inside test(). An object is only moved-from
// If an r-value reference to it is used to construct a new object.
void test(std::vector<int>&& v) {
    v.push_back(4);
}

std::vector<int> myList = {1, 2, 3};
test(std::move(myList)); // Adds 4 to the end of myList

// Prints 1 2 3 4
for(int i : myList) {
    std::cout << i << " ";
}


问:
Autoencoder model either oscillates or doesn't converge on MNIST dataset
Already ran the code 3 months ago with intended results. Changed nothing. Tried troubleshooting by using codes from (several) earlier versions, including among the earliest (which definitely worked). The problem persists.

# 4 - Constructing the undercomplete architecture
class autoenc(nn.Module):
    def __init__(self, nodes = 100):
        super(autoenc, self).__init__() # inheritence
        self.full_connection0 = nn.Linear(784, nodes) # encoding weights
        self.full_connection1 = nn.Linear(nodes, 784) # decoding weights
        self.activation = nn.Sigmoid()

    def forward(self, x):
        x = self.activation(self.full_connection0(x)) # input encoding
        x = self.full_connection1(x) # output decoding
        return x

# 5 - Initializing autoencoder, squared L2 norm, and optimization algorithm
model = autoenc().cuda()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(),
                          lr = 1e-3, weight_decay = 1/2)

# 6 - Training the undercomplete autoencoder model
num_epochs = 500
batch_size = 32
length = int(len(trn_data) / batch_size)

loss_epoch1 = []

for epoch in range(num_epochs):
    train_loss = 0
    score = 0.

    for num_data in range(length - 2):
        batch_ind = (batch_size * num_data)
        input = Variable(trn_data[batch_ind : batch_ind + batch_size]).cuda()

        # === forward propagation ===
        output = model(input)
        loss = criterion(output, trn_data[batch_ind : batch_ind + batch_size])

        # === backward propagation ===
        loss.backward()

        # === calculating epoch loss ===
        train_loss += np.sqrt(loss.item())
        score += 1. #<- add for average loss error instead of total
        optimizer.step()

    loss_calculated = train_loss/score
    print('epoch: ' + str(epoch + 1) + '   loss: ' + str(loss_calculated))
    loss_epoch1.append(loss_calculated)
```

When plotting the loss now, it oscillates oscillates wildly (at lr = 1e-3). Whereas 3 months ago, it was steadily converging (at lr = 1e-3).

Can't upload pictures yet due to recently created account.

How it looks like now.

Though this is when I reduce the learning rate to 1e-5. When it's at 1e-3, it's just all over the places.

How it should look like, and used to look like at lr = 1e-3.

答:
You should do optimizer.zero_grad() before you do loss.backward() since the gradients accumulate. This is most likely causing the issue.

The general order to be followed during training phase :

```<code>optimizer.zero_grad()
output = model(input)
loss = criterion(output, label)
loss.backward()
optimizer.step()
</code>```

Also, the value of weight decay used (1 / 2) was causing an issue.

Body:
Already ran the code 3 months ago with intended results. Changed nothing. Tried troubleshooting by using codes from (several) earlier versions, including among the earliest (which definitely worked). The problem persists.

# 4 - Constructing the undercomplete architecture
class autoenc(nn.Module):
    def __init__(self, nodes = 100):
        super(autoenc, self).__init__() # inheritence
        self.full_connection0 = nn.Linear(784, nodes) # encoding weights
        self.full_connection1 = nn.Linear(nodes, 784) # decoding weights
        self.activation = nn.Sigmoid()

    def forward(self, x):
        x = self.activation(self.full_connection0(x)) # input encoding
        x = self.full_connection1(x) # output decoding
        return x

# 5 - Initializing autoencoder, squared L2 norm, and optimization algorithm
model = autoenc().cuda()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(),
                          lr = 1e-3, weight_decay = 1/2)

# 6 - Training the undercomplete autoencoder model
num_epochs = 500
batch_size = 32
length = int(len(trn_data) / batch_size)

loss_epoch1 = []

for epoch in range(num_epochs):
    train_loss = 0
    score = 0.

    for num_data in range(length - 2):
        batch_ind = (batch_size * num_data)
        input = Variable(trn_data[batch_ind : batch_ind + batch_size]).cuda()

        # === forward propagation ===
        output = model(input)
        loss = criterion(output, trn_data[batch_ind : batch_ind + batch_size])

        # === backward propagation ===
        loss.backward()

        # === calculating epoch loss ===
        train_loss += np.sqrt(loss.item())
        score += 1. #<- add for average loss error instead of total
        optimizer.step()

    loss_calculated = train_loss/score
    print('epoch: ' + str(epoch + 1) + '   loss: ' + str(loss_calculated))
    loss_epoch1.append(loss_calculated)

When plotting the loss now, it oscillates oscillates wildly (at lr = 1e-3). Whereas 3 months ago, it was steadily converging (at lr = 1e-3).

Can't upload pictures yet due to recently created account.

How it looks like now.

Though this is when I reduce the learning rate to 1e-5. When it's at 1e-3, it's just all over the places.

How it should look like, and used to look like at lr = 1e-3.

Body:
You should do optimizer.zero_grad() before you do loss.backward() since the gradients accumulate. This is most likely causing the issue.

The general order to be followed during training phase :

optimizer.zero_grad()
output = model(input)
loss = criterion(output, label)
loss.backward()
optimizer.step()

Also, the value of weight decay used (1 / 2) was causing an issue.


问:
Checking if a string contains a dot
Today I was trying to detect if a string contains a dot, but my code isn't working</p>

```<code> String s = "test.test";
 if(s.contains("\\.")) {
     System.out.printLn("string contains dot");
 }
</code>```

答:
The easiest way is to check with a .contains() statement.

Note: .contains() works only for strings.

From

 String s = "test.test";
 if(s.contains("\\.")) {
     System.out.printLn("string contains dot");
 }
```
<p><strong>To</strong></p>
<pre class="lang-java prettyprint-override"><code>String s = "test.test";
 if(s.contains(".")) {
     System.out.printLn("string contains dot");
 }
</code>```

Do like this to check any symbol or character in a string.

Title: Checking if a string contains a dot

Body:
Today I was trying to detect if a string contains a dot, but my code isn't working

 String s = "test.test";
 if(s.contains("\\.")) {
     System.out.printLn("string contains dot");
 }

Body:
The easiest way is to check with a .contains() statement.

Note: .contains() works only for strings.

From

 String s = "test.test";
 if(s.contains("\\.")) {
     System.out.printLn("string contains dot");
 }

To

String s = "test.test";
 if(s.contains(".")) {
     System.out.printLn("string contains dot");
 }

Do like this to check any symbol or character in a string.