问:
JavaScript time convert
I am very new to JavaScript. My guess is that there is a very easy answer.
I need to convert time in the format hh:mm:ss to Seconds.

答:
try this</p>

```<code>  <SCRIPT LANGUAGE="JavaScript1.1"><!--
function split(string,text) {
    splitArray = string.split(text);
    splitIndex = splitArray.length;
}
//--></SCRIPT>

    <SCRIPT LANGUAGE="JavaScript"><!--
    var splitIndex = 0;
    var splitArray = new Array();

    function calculateTime() {
        splitIndex = 0;
        split(document.myForm.myTime.value,':');

        for (var i=splitIndex-1, j=1, answer=0; i>=0; i=i-1, j=j*60)
            answer += splitArray[i]*j - 0;

        document.myForm.mySeconds.value = answer;
    }
    //--></SCRIPT>

    <FORM NAME="myForm">
    <P>HH:MM:SS = <INPUT NAME="myTime" TYPE="TEXT" MAXLENGTH="8" LENGTH="10">
    <P>Seconds = <INPUT NAME="mySeconds" TYPE="TEXT">
    <P><INPUT TYPE="BUTTON" VALUE="Calculate" onClick="calculateTime()">
    </FORM>
</code>```

Title: JavaScript time convert

Body:
try this

  <SCRIPT LANGUAGE="JavaScript1.1"><!--
function split(string,text) {
    splitArray = string.split(text);
    splitIndex = splitArray.length;
}
//--></SCRIPT>

    <SCRIPT LANGUAGE="JavaScript"><!--
    var splitIndex = 0;
    var splitArray = new Array();

    function calculateTime() {
        splitIndex = 0;
        split(document.myForm.myTime.value,':');

        for (var i=splitIndex-1, j=1, answer=0; i>=0; i=i-1, j=j*60)
            answer += splitArray[i]*j - 0;

        document.myForm.mySeconds.value = answer;
    }
    //--></SCRIPT>

    <FORM NAME="myForm">
    <P>HH:MM:SS = <INPUT NAME="myTime" TYPE="TEXT" MAXLENGTH="8" LENGTH="10">
    <P>Seconds = <INPUT NAME="mySeconds" TYPE="TEXT">
    <P><INPUT TYPE="BUTTON" VALUE="Calculate" onClick="calculateTime()">
    </FORM>


来源: stackexchange

问:
wp v2 rest request from Android App overload CPU usage
I have created Android App for news website (wordpress), i used WP v2 API to get posts from database, the problem that even less than 10 users that using the App in same time can overload the server (CPU usage).

When user open the App i send get request (using retrofit2) and get the first page (json array with 10 objects of that represent posts).

```<code>/wp-json/wp/v2/posts?page=1
</code>```

Then for every post i send another request for media to get image.

```<code>/wp-json/wp/v2/media/21342
</code>```

Without the App the server overloads when 600-700 users browse the website, with the App it overloads at 300 users and 10 App users.

Why it happen what is the difference between wp-v2 request and browser website loading?

答:
Try to reduce the number of requests by passing down the image URL with the inital request. I have done this using this embedded parameter:

https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/

Additionally, maybe try using something like S3 Offload Media plugin to serve your images off of a different server than your application server.

Pantheon has a whole site dedicated to WP at Scale: https://scalewp.io

ContentLicense: CC BY-SA 3.0

Body:
I have created Android App for news website (wordpress), i used WP v2 API to get posts from database, the problem that even less than 10 users that using the App in same time can overload the server (CPU usage).

When user open the App i send get request (using retrofit2) and get the first page (json array with 10 objects of that represent posts).

/wp-json/wp/v2/posts?page=1

Then for every post i send another request for media to get image.

/wp-json/wp/v2/media/21342

Without the App the server overloads when 600-700 users browse the website, with the App it overloads at 300 users and 10 App users.

Why it happen what is the difference between wp-v2 request and browser website loading?


问:
URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "</"
I am getting this exception while trying to generate a .PDF file from my application.

```<code>URLDecoder: Illegal hex characters in escape (%) pattern - For input string:....
</code>```

Here is the stack trace

```<code>java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "</"
    at java.net.URLDecoder.decode(Unknown Source)

</code>```

Here is the code

```<code>StringBuffer outBuffer = new StringBuffer();
//some values are added to outBuffer .
String pdfXmlView = URLDecoder.decode(outBuffer.toString(), "utf-8");
</code>```

While trying to decode using URLDecoder.decode() it is throwing that exception. I got the cause for the exception, it is coming because of % character in outBuffer.

If anyone knows how to solve this problem?

答:
```<code>If you are facing issue only with **%**. Then this would help:

   protected static String encoder(String localTopic1){
        String localTopic =localTopic1;
        try {
            StringBuffer tempBuffer = new StringBuffer();
            int incrementor = 0;
            int dataLength = localTopic.length();
            while (incrementor < dataLength) {
            char characterAt = localTopic.charAt(incrementor);
            int next_char_index = incrementor+1;
            int third_index = next_char_index+1;
            Character charAt_nextIndex = ' ';
            char charAt_thirdIndex = ' ';
            String stringAt_nextIndex = "";

            if(next_char_index < dataLength){
                    charAt_nextIndex = localTopic.charAt(next_char_index);
                    stringAt_nextIndex = charAt_nextIndex.toString();
            }
            if(third_index < dataLength)
                    charAt_thirdIndex = localTopic.charAt(third_index);

            if (characterAt == '%') {
                    if(stringAt_nextIndex.matches("[A-F2-9]")){

                            if(charAt_thirdIndex == ' ' || charAt_thirdIndex == '%'){
                                    tempBuffer.append("<percentage>");
                            }
                            else{
                                    tempBuffer.append(characterAt);
                            }
                    }
                    else{
                            tempBuffer.append("<percentage>");
                    }

            }else {
                    tempBuffer.append(characterAt);
            }
            incrementor++;
    }
    localTopic = tempBuffer.toString();
} catch (Exception e) {
    e.printStackTrace();
}
return localTopic;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting this exception while trying to generate a .PDF file from my application.

URLDecoder: Illegal hex characters in escape (%) pattern - For input string:....

Here is the stack trace

java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "</"
    at java.net.URLDecoder.decode(Unknown Source)

Here is the code

StringBuffer outBuffer = new StringBuffer();
//some values are added to outBuffer .
String pdfXmlView = URLDecoder.decode(outBuffer.toString(), "utf-8");

While trying to decode using URLDecoder.decode() it is throwing that exception. I got the cause for the exception, it is coming because of % character in outBuffer.

If anyone knows how to solve this problem?


问:
Console calculator program in C++ not working correctly
I'm kind of new to programming in C++, and after a bit of learning how it works, I tried making this console calculator application, which takes in two numbers from the user x and y, and then adds, subtracts, multiplies or divides the two numbers depending on the third z input. I'm using code blocks as the IDE, and the code is as follows:

```<code>#include <iostream>

//First input value
int x;
//Second input value;
int y;
//Operator value;
int z;
int main()
{
    //Asks user for first number
    std::cout << "Input first number" << std::endl;
    std::cin >> x;
    std::cout << "" << std::endl;

    //Asks user for second number
    std::cout << "Input second number" << std::endl;
    std::cin >> y;
    std::cout << "" << std::endl;

    //Asks user for operation
    std::cout << "Input operation: 1 for add, 2 for sub, 3 for multiply, 4 for divide" << std::endl;
    std::cin >> z;

    //Displaying the desired output
    if (z = 1)
    {
        std::cout << x + y << std::endl;
    }
    else if (z = 2)
    {
        std::cout << x - y << std::endl;
    }
    else if (z = 3)
    {
        std::cout << x * y << std::endl;
    }
    else (z = 4);
    {
        std::cout << x / y << std::endl;
    }

    //Just a stupid comment
    std::cout << "Thank you for using this piece of shit xD. Press any key to end" << std::endl;
    return 0;
}
</code>```

Even though it compiles without any errors, every operation input seems to add the numbers together rather than the desired operation. Could anyone tell me what I'm doing wrong here?

答:
Your if else conditions are wrong, you are using assignment operator (=) instead of equalto (==) comparison operator.

Do if(z=1) --> if(z==1) an same for remaining else conditions.

Note that the division will return an integer rounded value, hence it's preferable to cast your numerator to double before division.

Just do x/y --> (x*1.0)/y

Body:
I'm kind of new to programming in C++, and after a bit of learning how it works, I tried making this console calculator application, which takes in two numbers from the user x and y, and then adds, subtracts, multiplies or divides the two numbers depending on the third z input. I'm using code blocks as the IDE, and the code is as follows:

#include <iostream>

//First input value
int x;
//Second input value;
int y;
//Operator value;
int z;
int main()
{
    //Asks user for first number
    std::cout << "Input first number" << std::endl;
    std::cin >> x;
    std::cout << "" << std::endl;

    //Asks user for second number
    std::cout << "Input second number" << std::endl;
    std::cin >> y;
    std::cout << "" << std::endl;

    //Asks user for operation
    std::cout << "Input operation: 1 for add, 2 for sub, 3 for multiply, 4 for divide" << std::endl;
    std::cin >> z;

    //Displaying the desired output
    if (z = 1)
    {
        std::cout << x + y << std::endl;
    }
    else if (z = 2)
    {
        std::cout << x - y << std::endl;
    }
    else if (z = 3)
    {
        std::cout << x * y << std::endl;
    }
    else (z = 4);
    {
        std::cout << x / y << std::endl;
    }

    //Just a stupid comment
    std::cout << "Thank you for using this piece of shit xD. Press any key to end" << std::endl;
    return 0;
}

Even though it compiles without any errors, every operation input seems to add the numbers together rather than the desired operation. Could anyone tell me what I'm doing wrong here?


问:
How to parse data between  and
I want to parse the information between ...	 under Number of samples	.For example, after parsing the following html will return 64.

```<code>...
<tr class="border">
    <th>Average FPKM</th>
    <td colspan="2">0.8</td>
</tr>
<tr class="border">
    <th>Number of samples</th>
    <td colspan="2">64</td>
</tr>
...
</code>```

How to get only return the value 64 here?

Thanks

答:
Assuming you need the last cell of the last row of a table and that you are using jQuery.

```<code>let result = $('table tr:last-child td:last-child').text();
</code>```

Here is example

Title: How to parse data between <td colspan="2"> and </td>

Body:
I want to parse the information between ...	 under Number of samples	.For example, after parsing the following html will return 64.

...

    Average FPKM
    0.8

    Number of samples
    64

...

How to get only return the value 64 here?

Thanks

Body:
Assuming you need the last cell of the last row of a table and that you are using jQuery.

let result = $('table tr:last-child td:last-child').text();

Here is example


问:
How to add image inside svg path?
I want to add an image to SVG path. I tried at some level but it's a half-baked code and image is not taking a proper shape of SVG.

Here's the HTML for that:

```<code><div class="top-fold">
 <div class="curve-img" id="shapeContainer">
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1280" height="564" viewBox="0 0 1280 564" preserveAspectRatio="none">
              <defs>
                <rect id="bg-a" width="1280" height="575"/>
                <linearGradient id="bg-b" x1="50%" x2="71.552%" y1="-4.763%" y2="100%">
                  <stop offset="0%" stop-color="#FAFBFC"/>
                  <stop offset="100%" stop-color="#EBF3F9"/>
                </linearGradient>
              </defs>
              <g fill="none" fill-rule="evenodd">
                <mask id="bg-c" fill="#fff">
                  <use xlink:href="#bg-a"/>
                </mask>
                <path fill="url(#bg-b)" d="M0,0 L1280,0 L1280,465.166826 C1282.16971,484.337191 1283.83637,494.281583 1285,495 C1358.96463,540.665449 1275.63125,544.202225 1034,558.75895 C786.666667,573.659188 442,550.377565 0,488.914081 L0,0 Z" mask="url(#bg-c)"/>
              </g>
            </svg>

    </div><!-- curve-img end -->
  </div> <!-- top fold end -->
</code>```

Here's the CSS for that.

```<code>.top-fold {
  width: 100%;
  position: relative;
  height: 80vh;
 }

.curve-img {
  position: absolute;
  height: 100%;
  width: 100%;
  background-size: cover;
  top: 0;
  left: 0;
  z-index: 4;
}

#shapeContainer {
  width: 100%;
  height: 100%;
  margin: auto;
  background-image: linear-gradient(
      to bottom,
      rgba(255, 159, 63, 0.2),
      rgba(255, 159, 63, 0.8)
    ),
    url(https://www.nature.org/cs/groups/webcontent/@web/documents/media/2016-photocontest-yosemite-w-1.jpg);
  background-size: cover;
  background-position: center top;
  overflow: hidden;
}

#shapeContainer svg {
  display: block;
  width: 100%;
  height: 100%;
}
@media screen and (max-height: 400px) {
  #shapeContainer {
    background-size: auto 150%;
  }
}
@media screen and (max-height: 200px) {
  #shapeContainer {
    background-size: auto 200%;
  }
}
@media screen and (max-height: 100px) {
  #shapeContainer {
    background-size: auto 300%;
  }
}
</code>```

Here's the codepen link for your reference. https://codepen.io/enworl/pen/xPyMxL

Thanks in advance for your help.

答:
There is a lot in you sample, that I'm not sure about.  A lot of it is unrelated to the main thrust of your question about having a mask with a curved bottom.

Anyway, creating the mask is actually quite simple.  See the example below.

.top-fold {
  position: relative;
  width: 100%;
  height: 80vh;
 }

.curve-img {
  position: absolute;
  height: 100%;
  width: 100%;
}

#shapeContainer svg {
  display: block;
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top-fold">
  <div class="curve-img" id="shapeContainer">
    <svg>
      <defs>
        <mask id="bg-c" maskContentUnits="objectBoundingBox">
          <path fill="white"
                transform="scale(0.000781, 0.001742)"
                d="M0,0 L1280,0 L1280,465.166826 C1282.16971,484.337191 1283.83637,494.281583 1285,495 C1358.96463,540.665449 1275.63125,544.202225 1034,558.75895 C786.666667,573.659188 442,550.377565 0,488.914081 L0,0 Z"/>
        </mask>
      </defs>

      <image xlink:href="https://www.nature.org/cs/groups/webcontent/@web/documents/media/2016-photocontest-yosemite-w-1.jpg"
             width="100%" height="100%" preserveAspectRatio="xMidYMid slice" mask="url(#bg-c)"/>
    </svg>

  </div><!-- curve-img end -->
</div> <!-- top fold end --></code>```

Note that there are still some quirks with applying masks to HTML content, so for now, the easiest approach is to put the image in the SVG instead.

I have removed the viewBox and preserveAspectRatio="none" from the SVG as we want it to scale up with its parent without distorting the image.

We are also switching the mask to use objectBoundingBox units, so that it fits the image no matter what size it ends up as.

If you need the orange gradient wash on top, you can do it like this.

.top-fold {
  position: relative;
  width: 100%;
  height: 80vh;
 }

.curve-img {
  position: absolute;
  height: 100%;
  width: 100%;
}

#shapeContainer svg {
  display: block;
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top-fold">
  <div class="curve-img" id="shapeContainer">
    <svg>
      <defs>
        <mask id="bg-c" maskContentUnits="objectBoundingBox">
          <path fill="white"
                transform="scale(0.000781, 0.001742)"
                d="M0,0 L1280,0 L1280,465.166826 C1282.16971,484.337191 1283.83637,494.281583 1285,495 C1358.96463,540.665449 1275.63125,544.202225 1034,558.75895 C786.666667,573.659188 442,550.377565 0,488.914081 L0,0 Z"/>
        </mask>
        <linearGradient id="bg-b" x2="0" y2="1">
          <stop offset="0%" stop-color="rgba(255, 159, 63, 0.2)"/>
          <stop offset="100%" stop-color="rgba(255, 159, 63, 0.8)"/>
        </linearGradient>
      </defs>

      <g mask="url(#bg-c)">
        <image xlink:href="https://www.nature.org/cs/groups/webcontent/@web/documents/media/2016-photocontest-yosemite-w-1.jpg"
               width="100%" height="100%" preserveAspectRatio="xMidYMid slice"/>
        <rect width="100%" height="100%" fill="url(#bg-b)"/>
      </g>
    </svg>

  </div><!-- curve-img end -->
</div> <!-- top fold end --></code>```

Title: How to add image inside svg path?

Body:
I want to add an image to SVG path. I tried at some level but it's a half-baked code and image is not taking a proper shape of SVG.

Here's the HTML for that:

            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1280" height="564" viewBox="0 0 1280 564" preserveAspectRatio="none">
              <defs>
                <rect id="bg-a" width="1280" height="575"/>
                <linearGradient id="bg-b" x1="50%" x2="71.552%" y1="-4.763%" y2="100%">
                  <stop offset="0%" stop-color="#FAFBFC"/>
                  <stop offset="100%" stop-color="#EBF3F9"/>
                </linearGradient>
              </defs>
              <g fill="none" fill-rule="evenodd">
                <mask id="bg-c" fill="#fff">
                  <use xlink:href="#bg-a"/>
                </mask>
                <path fill="url(#bg-b)" d="M0,0 L1280,0 L1280,465.166826 C1282.16971,484.337191 1283.83637,494.281583 1285,495 C1358.96463,540.665449 1275.63125,544.202225 1034,558.75895 C786.666667,573.659188 442,550.377565 0,488.914081 L0,0 Z" mask="url(#bg-c)"/>
              </g>
            </svg>

Here's the CSS for that.

.top-fold {
  width: 100%;
  position: relative;
  height: 80vh;
 }

.curve-img {
  position: absolute;
  height: 100%;
  width: 100%;
  background-size: cover;
  top: 0;
  left: 0;
  z-index: 4;
}

#shapeContainer {
  width: 100%;
  height: 100%;
  margin: auto;
  background-image: linear-gradient(
      to bottom,
      rgba(255, 159, 63, 0.2),
      rgba(255, 159, 63, 0.8)
    ),
    url(https://www.nature.org/cs/groups/webcontent/@web/documents/media/2016-photocontest-yosemite-w-1.jpg);
  background-size: cover;
  background-position: center top;
  overflow: hidden;
}

#shapeContainer svg {
  display: block;
  width: 100%;
  height: 100%;
}
@media screen and (max-height: 400px) {
  #shapeContainer {
    background-size: auto 150%;
  }
}
@media screen and (max-height: 200px) {
  #shapeContainer {
    background-size: auto 200%;
  }
}
@media screen and (max-height: 100px) {
  #shapeContainer {
    background-size: auto 300%;
  }
}

Here's the codepen link for your reference. https://codepen.io/enworl/pen/xPyMxL

Thanks in advance for your help.

Body:
There is a lot in you sample, that I'm not sure about.  A lot of it is unrelated to the main thrust of your question about having a mask with a curved bottom.

Anyway, creating the mask is actually quite simple.  See the example below.

.top-fold {
  position: relative;
  width: 100%;
  height: 80vh;
 }

.curve-img {
  position: absolute;
  height: 100%;
  width: 100%;
}

#shapeContainer svg {
  display: block;
  width: 100%;
  height: 100%;
}

<div class="top-fold">
  <div class="curve-img" id="shapeContainer">
    <svg>
      <defs>
        <mask id="bg-c" maskContentUnits="objectBoundingBox">
          <path fill="white"
                transform="scale(0.000781, 0.001742)"
                d="M0,0 L1280,0 L1280,465.166826 C1282.16971,484.337191 1283.83637,494.281583 1285,495 C1358.96463,540.665449 1275.63125,544.202225 1034,558.75895 C786.666667,573.659188 442,550.377565 0,488.914081 L0,0 Z"/>
        </mask>
      </defs>

      <image xlink:href="https://www.nature.org/cs/groups/webcontent/@web/documents/media/2016-photocontest-yosemite-w-1.jpg"
             width="100%" height="100%" preserveAspectRatio="xMidYMid slice" mask="url(#bg-c)"/>
    </svg>

  </div><!-- curve-img end -->
</div> <!-- top fold end -->

Note that there are still some quirks with applying masks to HTML content, so for now, the easiest approach is to put the image in the SVG instead.

I have removed the viewBox and preserveAspectRatio="none" from the SVG as we want it to scale up with its parent without distorting the image.

We are also switching the mask to use objectBoundingBox units, so that it fits the image no matter what size it ends up as.

If you need the orange gradient wash on top, you can do it like this.

.top-fold {
  position: relative;
  width: 100%;
  height: 80vh;
 }

.curve-img {
  position: absolute;
  height: 100%;
  width: 100%;
}

#shapeContainer svg {
  display: block;
  width: 100%;
  height: 100%;
}

<div class="top-fold">
  <div class="curve-img" id="shapeContainer">
    <svg>
      <defs>
        <mask id="bg-c" maskContentUnits="objectBoundingBox">
          <path fill="white"
                transform="scale(0.000781, 0.001742)"
                d="M0,0 L1280,0 L1280,465.166826 C1282.16971,484.337191 1283.83637,494.281583 1285,495 C1358.96463,540.665449 1275.63125,544.202225 1034,558.75895 C786.666667,573.659188 442,550.377565 0,488.914081 L0,0 Z"/>
        </mask>
        <linearGradient id="bg-b" x2="0" y2="1">
          <stop offset="0%" stop-color="rgba(255, 159, 63, 0.2)"/>
          <stop offset="100%" stop-color="rgba(255, 159, 63, 0.8)"/>
        </linearGradient>
      </defs>

      <g mask="url(#bg-c)">
        <image xlink:href="https://www.nature.org/cs/groups/webcontent/@web/documents/media/2016-photocontest-yosemite-w-1.jpg"
               width="100%" height="100%" preserveAspectRatio="xMidYMid slice"/>
        <rect width="100%" height="100%" fill="url(#bg-b)"/>
      </g>
    </svg>

  </div><!-- curve-img end -->
</div> <!-- top fold end -->


问:
Only show non-default attributes in repr of attr.s class
I'm using attrs to define simple classes without boilerplate code. The decorator automatically generates a __repr__ that shows the values for all attributes. I'd like to only show attributes that do not have their default values:

```<code>>>> import attr
>>> @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=0, y=0)  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=1)  # wanted output: Coordinates(x=1)
Coordinates(x=1, y=0)
>>> Coordinates(x=1, y=1)  # output OK
Coordinates(x=1, y=1)
</code>```

Is there any reasonably easy way to achieve this?

答: No, there’s not and it’s also a fairly specific request. :)  People have been asking for more ways to customise repr’s output by passing e.g. callable so that might make your use case easier, once it lands.  However I’m not aware of anyone actively working on that right now.

Body:
I'm using attrs to define simple classes without boilerplate code. The decorator automatically generates a __repr__ that shows the values for all attributes. I'd like to only show attributes that do not have their default values:

>>> import attr
>>> @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=0, y=0)  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=1)  # wanted output: Coordinates(x=1)
Coordinates(x=1, y=0)
>>> Coordinates(x=1, y=1)  # output OK
Coordinates(x=1, y=1)

Is there any reasonably easy way to achieve this?


问:
Float left removes the hyperlinks
I know this is popular problem. I tried everything but still I could not make this work.
here is my html and css.

.unodered-item {
  float: left;
  overflow: hidden;
}
.item {
  height: 140px;
  width: 220px;
  margin-left: 10px;
  background: pink;
  //background-image: url("../resourses/tutorial-thumbnails/thumbnail.png");
  -webkit-background-size: cover;
  background-size: cover;
  overflow: hidden;
}

a.item-link {
  height: 140px;
  width: 220px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="recommended-list-items">
    <ul class="unodered unodered-recommended">
      <li class="unodered-item">
        <div class="item item'+ x +'">

        </div>
      </li>
    </ul>
</div></code>```

Help!!!

答:
Add display:block or float:left to .item-link

```<code>a.item-link {
    height: 140px;
    width: 220px;
    display: block;
}
</code>```

or

```<code>a.item-link {
    height: 140px;
    width: 220px;
    float: left;
}
</code>```

Title: Float left removes the hyperlinks

Body:
I know this is popular problem. I tried everything but still I could not make this work.
here is my html and css.

.unodered-item {
  float: left;
  overflow: hidden;
}
.item {
  height: 140px;
  width: 220px;
  margin-left: 10px;
  background: pink;
  //background-image: url("../resourses/tutorial-thumbnails/thumbnail.png");
  -webkit-background-size: cover;
  background-size: cover;
  overflow: hidden;
}

a.item-link {
  height: 140px;
  width: 220px;
}

Help!!!

Body:
Add display:block or float:left to .item-link

a.item-link {
    height: 140px;
    width: 220px;
    display: block;
}

or

a.item-link {
    height: 140px;
    width: 220px;
    float: left;
}


问:
RegEx Parser written in Prolog
I've been banging my head against the wall on this homework problem for a few hours now.  We have to parse a regular expression with Prolog. For the most part, the predicates I have work, but there's a few regular expression and string combos which cause them to run out of stack space in SWI-Prolog.  Here's a sample with two of the Regex string combinations, one that works and one that doesn't:

```<code>star(star(char(a))), []
star(star(char(a))), [a]
</code>```

The first one works and the second one runs out of stack.

Here's the predicates I'm using:

```<code>re_match(epsilon, []).
re_match(char(Letter), [Letter]).
re_match(star(_), []).
re_match(seq(Rx1, Rx2), List) :- append(List1, List2, List),  re_match(Rx2, List2),  re_match(Rx1, List1).
re_match(alt(Rx1, Rx2), List) :- re_match(Rx1, List); re_match(Rx2, List).
re_match(star(Rx), List) :- append(List1, List2, List), re_match(Rx, List1), re_match(star(Rx), List2).
</code>```

I'm not sure what change I need to make to get it to work right, but I'm not sure what else to do.

Also, changing List :- append(List1, List2, List) to [H|T] does not evaluate to true for one of the examples.

答:
I don't have access to SWI Prolog right now, but here is a guess:

Try changing

```<code>re_match(star(Rx), List) :- append(List1, List2, List),
                            re_match(Rx, List1),
                            re_match(star(Rx), List2).
</code>```

to

```<code>re_match(star(Rx), List) :- append([H|List1], List2, List),
                            re_match(Rx, [H|List1]),
                            re_match(star(Rx), List2).
</code>```

to force re_match to "eat something" when it iterates on the star construct.

ContentLicense: CC BY-SA 2.5

Title: RegEx Parser written in Prolog

Body:
I've been banging my head against the wall on this homework problem for a few hours now.  We have to parse a regular expression with Prolog. For the most part, the predicates I have work, but there's a few regular expression and string combos which cause them to run out of stack space in SWI-Prolog.  Here's a sample with two of the Regex string combinations, one that works and one that doesn't:

star(star(char(a))), []
star(star(char(a))), [a]

The first one works and the second one runs out of stack.

Here's the predicates I'm using:

re_match(epsilon, []).
re_match(char(Letter), [Letter]).
re_match(star(_), []).
re_match(seq(Rx1, Rx2), List) :- append(List1, List2, List),  re_match(Rx2, List2),  re_match(Rx1, List1).
re_match(alt(Rx1, Rx2), List) :- re_match(Rx1, List); re_match(Rx2, List).
re_match(star(Rx), List) :- append(List1, List2, List), re_match(Rx, List1), re_match(star(Rx), List2).

I'm not sure what change I need to make to get it to work right, but I'm not sure what else to do.

Also, changing List :- append(List1, List2, List) to [H|T] does not evaluate to true for one of the examples.

Body:
I don't have access to SWI Prolog right now, but here is a guess:

Try changing

re_match(star(Rx), List) :- append(List1, List2, List),
                            re_match(Rx, List1),
                            re_match(star(Rx), List2).

to

re_match(star(Rx), List) :- append([H|List1], List2, List),
                            re_match(Rx, [H|List1]),
                            re_match(star(Rx), List2).

to force re_match to "eat something" when it iterates on the star construct.


问:
Unable to switch on Install via USB on Redmi Note 4
MI Note 4

```<code>Android version: 7.0

MIUI Version: 9.0
</code>```

I'm unable to switch on Install via USB option for debugging purpose. I have tried switching to mobile data and using MI account . Also, tried turning off MIUI optimization. Nothing worked till now.

I always get the error that says "The device is temporarily restricted"

I'm stuck for 2 days now.

Could anyone here help in resolving this?

Note: It was working fine till I updated the device to Nougat. Kindly help if you're using Nougat along with MIUI 9.0

Edit: Using VPN helped.

答:
@Akash Raj
If below link is not working

1- Install app via usb: The device is temporarily restricted

2- http://en.miui.com/thread-544718-1-1.html

Then try to this way because it's working for me.

Connect your Redimi mobile with device hence come to display many option like below image

Select Transfer file now it's working.

Body:
MI Note 4

Android version: 7.0

MIUI Version: 9.0

I'm unable to switch on Install via USB option for debugging purpose. I have tried switching to mobile data and using MI account . Also, tried turning off MIUI optimization. Nothing worked till now.

I always get the error that says "The device is temporarily restricted"

I'm stuck for 2 days now.

Could anyone here help in resolving this?

Note: It was working fine till I updated the device to Nougat. Kindly help if you're using Nougat along with MIUI 9.0

Edit: Using VPN helped.


问:
Creating a dictionary from a csv file?
I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the csv.DictReader and csv.DictWriter classes, but I could only figure out how to generate a new dictionary for each row. I want one dictionary. Here is the code I am trying to use:

```<code>import csv

with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
    for rows in reader:
        k = rows[0]
        v = rows[1]
        mydict = {k:v for k, v in rows}
    print(mydict)
</code>```

When I run the above code I get a ValueError: too many values to unpack (expected 2). How do I create one dictionary from a csv file? Thanks.

答:
This isn't elegant but a one line solution using pandas.

```<code>import pandas as pd
pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()
</code>```

If you want to specify dtype for your index (it can't be specified in read_csv if you use the index_col argument because of a bug):

```<code>import pandas as pd
pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()
</code>```

Title: Creating a dictionary from a csv file?

Body:
I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the csv.DictReader and csv.DictWriter classes, but I could only figure out how to generate a new dictionary for each row. I want one dictionary. Here is the code I am trying to use:

import csv

with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
    for rows in reader:
        k = rows[0]
        v = rows[1]
        mydict = {k:v for k, v in rows}
    print(mydict)

When I run the above code I get a ValueError: too many values to unpack (expected 2). How do I create one dictionary from a csv file? Thanks.

Body:
This isn't elegant but a one line solution using pandas.

import pandas as pd
pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()

If you want to specify dtype for your index (it can't be specified in read_csv if you use the index_col argument because of a bug):

import pandas as pd
pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()


问:
Is vmware virtualization faster on same SSD as the images or on separate SSD?
I use VMware player with two SSDs, main windows 10 OS on first SSD, I will store the linux virtual images on second SSD ...

Will the virtual machines run faster if the VMware player program is installed on same SSD as the main OS or on the same drive as the virtual images ?

答: All ok.If windows10 and vmware installed together may be unloading problems.However,this situation is very small,so do not worry.</p>


问:
Get distribution of consecutive occurrences of some target value
Lets say I am given the following list

x = ['A','A','B','A','A','A', 'C', 'C', 'A', 'A']

What would be the best and most efficient way to generate the following output

```<code># key = number of consecutives
# val = number of occurrences
>>> func(x, 'A')
{2:2, 3:1}

>>> func(x, 'B')
{1:1}

>>> func(x, 'C')
{2:1}
</code>```

We may assume that the list is all strings. Any ideas?

答:
This should work:

```<code>from collections import defaultdict
def f(x, t):
    n = 0
    result = defaultdict(int)
    for c in x:
        if c == t:
            n += 1
        else:
            result[n] += 1
            n = 0
    result[n] += 1
    del result[0]
    return result
</code>```

whether it is the best is totally opinion based. IMO it is the best because I wrote it and, in my own opinion, I am the best.

On a more objective note: @schwobaseggl 's solution is more concise but a quick %timeit experiment tells me mine is 5x faster on your example and possibly a lot more on other examples... So 'best' really depends on what you value most. (even 'efficient' is rather vague: are you considering processing time, memory usage, .. ?)

Body:
Lets say I am given the following list

x = ['A','A','B','A','A','A', 'C', 'C', 'A', 'A']

What would be the best and most efficient way to generate the following output

# key = number of consecutives
# val = number of occurrences
>>> func(x, 'A')
{2:2, 3:1}

>>> func(x, 'B')
{1:1}

>>> func(x, 'C')
{2:1}

We may assume that the list is all strings. Any ideas?

Body:
This should work:

from collections import defaultdict
def f(x, t):
    n = 0
    result = defaultdict(int)
    for c in x:
        if c == t:
            n += 1
        else:
            result[n] += 1
            n = 0
    result[n] += 1
    del result[0]
    return result

whether it is the best is totally opinion based. IMO it is the best because I wrote it and, in my own opinion, I am the best.

On a more objective note: @schwobaseggl 's solution is more concise but a quick %timeit experiment tells me mine is 5x faster on your example and possibly a lot more on other examples... So 'best' really depends on what you value most. (even 'efficient' is rather vague: are you considering processing time, memory usage, .. ?)


问:
How to pair countries with almost same names in Excel?
I need help how to pair little bit different names of countries. Problem is that I have two datasets from different sources. In first sheet names of countries are based on ISO names and shortcuts, but in second sheet names are not based on ISO names.

Sheet1:

Sheet2:

I tried use VLOOKUP function to pair official iso name with name from Sheet2,  but result of United States was United Kingdom

Have you got any thoughts how to avoid replacing problem names?

Thank you!

答:
I have an approximative solution which would solve a major part of your table in VBA as below:

My Code is checking if it can find the string in the second Sheet and then enter the respective results in Sheet 1 below Metric 3.
So in A2 it tries with:

1 United States of America

2 United States of Americ

3 United States of Ameri

...

13 United States (which would be the match)

the issue is that if you have a Country like "United Kingdom" which is different in the other list like "U.K", the result given would be the one of United States of America.

Nevertheless it takes out some manual work.

```<code>Sub Find_Countries()

Dim LastRow As Long
LastRow = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

Dim i As Integer
For i = 2 To LastRow
Dim ra As Range
Dim a As Integer
a = Len(Range("A" & i))

Do
Set ra = Sheets(2).Cells.Find(What:=Left(Sheets(1).Range("A" & i), a), LookIn:=xlValues, LookAt _
        :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)

a = a - 1
Loop Until Not ra Is Nothing

Sheets(1).Range("E" & i).Value = ra.Offset(0, 1)
Next i

End Sub
</code>```

Body:
I have an approximative solution which would solve a major part of your table in VBA as below:

My Code is checking if it can find the string in the second Sheet and then enter the respective results in Sheet 1 below Metric 3.
So in A2 it tries with:

1 United States of America

2 United States of Americ

3 United States of Ameri

...

13 United States (which would be the match)

the issue is that if you have a Country like "United Kingdom" which is different in the other list like "U.K", the result given would be the one of United States of America.

Nevertheless it takes out some manual work.

Sub Find_Countries()

Dim LastRow As Long
LastRow = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

Dim i As Integer
For i = 2 To LastRow
Dim ra As Range
Dim a As Integer
a = Len(Range("A" & i))

Do
Set ra = Sheets(2).Cells.Find(What:=Left(Sheets(1).Range("A" & i), a), LookIn:=xlValues, LookAt _
        :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)

a = a - 1
Loop Until Not ra Is Nothing

Sheets(1).Range("E" & i).Value = ra.Offset(0, 1)
Next i

End Sub


问:
JavaScript associative array behaving strangely
I have two objects. When I pass these as key to an associative array, and assign a value, all the values are stored wrong ( except for the last one ).

Can anyone please tell me what I'm doing wrong ??

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";

console.log("usrMrid: " + comm[usrMrid]); // this gives TWO, when it should give ONE
console.log("usrXYZZ: " + comm[usrXYZZ]); // this works fine```

答:
well this has a problem, when you write an object in associative array style it only accepts strings. In your case it will overwrite itself and will always have the same answer for both the objects,

you need to write something like this otherwise it will always overwrite it.

```<code>var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid.name] = "ONE";
comm[usrXYZZ.name] = "TWO";

console.log(comm);// this will print your object correctly.
console.log(comm[usrMrid.name]);// this will print ONE
console.log(comm["mrid"]);// this will also print ONE
console.log(comm["xyzz"]); // This will print TWO
console.log(comm[usrXYZZ.name]); // This will print TWO
</code>```

Body:
well this has a problem, when you write an object in associative array style it only accepts strings. In your case it will overwrite itself and will always have the same answer for both the objects,

you need to write something like this otherwise it will always overwrite it.

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid.name] = "ONE";
comm[usrXYZZ.name] = "TWO";

console.log(comm);// this will print your object correctly.
console.log(comm[usrMrid.name]);// this will print ONE
console.log(comm["mrid"]);// this will also print ONE
console.log(comm["xyzz"]); // This will print TWO
console.log(comm[usrXYZZ.name]); // This will print TWO


问:
How can I dynamically create a new .java file from a Java program?
I want to create a one .java from the Java program.  When I run the program, automatically one Java file will created in my project, and also create some run time (dynamic) variable in that file.  How can I do this?

I know for this I have to use a Reflection API like Class and Method, but what are the methods in Class and Method to do this?

答:
You cannot create new classes or methods using the reflection APIs.  They are not designed for this.  (The Class and Method APIs are for performing operations on object instances in a dynamic fashion.)

If you want to create new code on the fly, there are two basic approaches to doing this:

Generate Java source code, write it to a file, use the Java compiler to compile it to a bytecode file, and then load the bytecodes.  (There are standard APIs for running the Java compiler within the JVM of a running application.)

Use BCEL or equivalent to construct a bytecode file from scratch, and then load the bytecodes.

Both approaches are tricky and computationally expensive.  The BCEL approach is particularly tricky because you need to understand a lot about the JVM to do the job.


问:
How to accept self-signed certificates with LWP::UserAgent
I am attempting to set up a node.js server that uses HTTPS. I will then write a scripts in Perl to make a HTTPS request to the server and measure latency of the round trip.

Here is my node.js:

```<code>var express = require('express');
var https = require('https');
var fs = require('fs');

var key = fs.readFileSync('encrypt/rootCA.key');
var cert = fs.readFileSync('encrypt/rootCA.pem');

// This line is from the Node.js HTTPS documentation.
var options = {
  key: key,
  cert: cert
};

https.createServer(options, function (req, res) {
    res.writeHead(200);
    res.end("hello world - https\n");
}).listen(8088);
</code>```

Key/cert generation was done as follows:

```<code>openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
</code>```

This is my Perl script:

```<code>#!/usr/bin/perl
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => 'https://127.0.0.1:8080');
my $res = $ua->request($req);

if ($res->is_success) {
  print $res->as_string;
} else {
  print "Failed: ", $res->status_line, "\n";
}
</code>```

Returning the error:

```<code>Failed: 500 Can't verify SSL peers without knowing which Certificate Authorities to trust
</code>```

The node.js documentation describes how to set up an HTTPS server but it is vague about generating primary cert and intermediate cert.

https://medium.com/netscape/everything-about-creating-an-https-server-using-node-js-2fc5c48a8d4e

答:
The typical answer to such question is to disable certificate validation at all. But, this is totally insecure and essentially disables most of the protection offered by HTTPS. If validation is disabled completely a man in the middle attacker just can use an arbitrary certificate to intercept the connection and sniff and modify the data. Thus, don't do it.

The correct way to deal with such certificates is to add these certificates as  trusted. This can be done with the SSL_ca_file argument:

```<code>my $ua = LWP::UserAgent->new;
$ua->ssl_opts(SSL_ca_file => 'rootCA.pem');
$ua->get('https://127.0.0.1:8080');
</code>```

By explicitly trusting the self-signed server certificate as CA it will no longer throw "certificate verify failed".

But, unless your server certificate is actually issued to "127.0.0.1" you will now get "hostname verification failed" since the subject of the certificate does not match the domain of the URL. This can be fixed by setting the expected hostname:

```<code>my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
    SSL_ca_file => 'rootCA.pem',
    SSL_verifycn_name => 'www.example.com',
);
$ua->get('https://127.0.0.1:8080');
</code>```

Note that SSL_ca_file needs the self-signed certificate to have the CA flag set to true, i.e. that the certificate is a CA certificate which can be used to issue other certificates. If this is not the case with your certificate or if you just want to accept a specific certificate no matter if it is expired, revoked, does not match the hostname etc you can do the validation by using the fingerprint of the certificate.

```<code>my $ua = LWP::UserAgent->new;
$ua->ssl_opts(SSL_fingerprint => 'sha1$9AA5CFED857445259D90FE1B56B9F003C0187BFF')
$ua->get('https://127.0.0.1:8080');
</code>```

The fingerprint here is the same you get with openssl x509 -noout -in rootCA.pem -fingerprint -sha1, only the algorithm added in front (sha1$...) and the colons removed.

Body:
I am attempting to set up a node.js server that uses HTTPS. I will then write a scripts in Perl to make a HTTPS request to the server and measure latency of the round trip.

Here is my node.js:

var express = require('express');
var https = require('https');
var fs = require('fs');

var key = fs.readFileSync('encrypt/rootCA.key');
var cert = fs.readFileSync('encrypt/rootCA.pem');

// This line is from the Node.js HTTPS documentation.
var options = {
  key: key,
  cert: cert
};

https.createServer(options, function (req, res) {
    res.writeHead(200);
    res.end("hello world - https\n");
}).listen(8088);

Key/cert generation was done as follows:

openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

This is my Perl script:

#!/usr/bin/perl
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => 'https://127.0.0.1:8080');
my $res = $ua->request($req);

if ($res->is_success) {
  print $res->as_string;
} else {
  print "Failed: ", $res->status_line, "\n";
}

Returning the error:

Failed: 500 Can't verify SSL peers without knowing which Certificate Authorities to trust

The node.js documentation describes how to set up an HTTPS server but it is vague about generating primary cert and intermediate cert.

https://medium.com/netscape/everything-about-creating-an-https-server-using-node-js-2fc5c48a8d4e

Body:
The typical answer to such question is to disable certificate validation at all. But, this is totally insecure and essentially disables most of the protection offered by HTTPS. If validation is disabled completely a man in the middle attacker just can use an arbitrary certificate to intercept the connection and sniff and modify the data. Thus, don't do it.

The correct way to deal with such certificates is to add these certificates as  trusted. This can be done with the SSL_ca_file argument:

my $ua = LWP::UserAgent->new;
$ua->ssl_opts(SSL_ca_file => 'rootCA.pem');
$ua->get('https://127.0.0.1:8080');

By explicitly trusting the self-signed server certificate as CA it will no longer throw "certificate verify failed".

But, unless your server certificate is actually issued to "127.0.0.1" you will now get "hostname verification failed" since the subject of the certificate does not match the domain of the URL. This can be fixed by setting the expected hostname:

my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
    SSL_ca_file => 'rootCA.pem',
    SSL_verifycn_name => 'www.example.com',
);
$ua->get('https://127.0.0.1:8080');

Note that SSL_ca_file needs the self-signed certificate to have the CA flag set to true, i.e. that the certificate is a CA certificate which can be used to issue other certificates. If this is not the case with your certificate or if you just want to accept a specific certificate no matter if it is expired, revoked, does not match the hostname etc you can do the validation by using the fingerprint of the certificate.

my $ua = LWP::UserAgent->new;
$ua->ssl_opts(SSL_fingerprint => 'sha1$9AA5CFED857445259D90FE1B56B9F003C0187BFF')
$ua->get('https://127.0.0.1:8080');

The fingerprint here is the same you get with openssl x509 -noout -in rootCA.pem -fingerprint -sha1, only the algorithm added in front (sha1$...) and the colons removed.


问:
indexing nested dictionary elements

I am trying to access the  dictionary elements in python, which looks like this:

```<code>mydict= {'message':'','result':[{'abc':1,'xyz':2}]}
</code>```

I want to access the value of key 'xyz'.Is there any direct method to access it in python.

Any help is greatly appreciated.

答:
In steps,

mydict['result'] returns [{'abc':1,'xyz':2}]

mydict['result'][0] returns {'abc':1,'xyz':2}

mydict['result'][0]['xyz'] returns 2

Title: indexing nested dictionary elements

Body:
I am trying to access the  dictionary elements in python, which looks like this:

mydict= {'message':'','result':[{'abc':1,'xyz':2}]}

I want to access the value of key 'xyz'.Is there any direct method to access it in python.

Any help is greatly appreciated.


问:
Oracle Apex ORA-00922: missing or invalid option
I tried creating a table on oracle apex but when I run it, it shows the following error: ORA-00922: missing or invalid option.
Here's my code:

```<code>CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )
/
</code>```

So what could be the problem?

答:
```<code>CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0),
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )
</code>```

removed not null enable, and it works.

Body:
I tried creating a table on oracle apex but when I run it, it shows the following error: ORA-00922: missing or invalid option.
Here's my code:

CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )
/

So what could be the problem?

Body:
CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0),
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )

removed not null enable, and it works.


问:
How to negate specific word in regex?
I know that I can negate group of chars as in [^bar] but I need a regular expression where negation applies to the specific word - so in my example how do I negate an actual bar, and not "any chars in bar"?

答:
I wish to complement the accepted answer and contribute to the discussion with my late answer.

@ChrisVanOpstal shared this regex tutorial which is a great resource for learning regex.

However, it was really time consuming to read through.

I made a cheatsheet for mnemonic convenience.

This reference is based on the braces [], (), and {} leading each class, and I find it easy to recall.

```<code>Regex = {
 'single_character': ['[]', '.', {'negate':'^'}],
 'capturing_group' : ['()', '|', '\\', 'backreferences and named group'],
 'repetition'      : ['{}', '*', '+', '?', 'greedy v.s. lazy'],
 'anchor'          : ['^', '\b', '$'],
 'non_printable'   : ['\n', '\t', '\r', '\f', '\v'],
 'shorthand'       : ['\d', '\w', '\s'],
 }
</code>```

Title: How to negate specific word in regex?

Body:
I wish to complement the accepted answer and contribute to the discussion with my late answer.

@ChrisVanOpstal shared this regex tutorial which is a great resource for learning regex.

However, it was really time consuming to read through.

I made a cheatsheet for mnemonic convenience.

This reference is based on the braces [], (), and {} leading each class, and I find it easy to recall.

Regex = {
 'single_character': ['[]', '.', {'negate':'^'}],
 'capturing_group' : ['()', '|', '\\', 'backreferences and named group'],
 'repetition'      : ['{}', '*', '+', '?', 'greedy v.s. lazy'],
 'anchor'          : ['^', '\b', '$'],
 'non_printable'   : ['\n', '\t', '\r', '\f', '\v'],
 'shorthand'       : ['\d', '\w', '\s'],
 }


答:
The following will work, making use of collections.Counter and itertools.groupby:

```<code>from itertools import groupby
from collections import Counter

def func(lst, elmnt):
    return Counter(len(list(g)) for k, g in groupby(lst) if k == elmnt)

>>> func(x, 'A')
Counter({2: 1, 3: 1})
</code>```

While this will probably not be bested for single calls, you would be better off building an intermediate data structure that collects counts for groups of all different elements in a single go-around so that subsequent calls for individual elements won't have to iterate the entire list again:

```<code>from collections import defaultdict

def func(lst):
    c = Counter((k, len(list(g))) for k, g in groupby(lst))
    d = defaultdict(dict)
    for (k, length), count in c.items():
        d[k][length] = count
    return d.get

>>> f = func(x)  # builds intermediate structure (O(N)), returns function to query it
>>> f('A')  # these calls are now all O(1)
{2: 1, 3: 1}
>>> f('B')
{1: 1}
</code>```

Title: Get distribution of consecutive occurrences of some target value

Body:
The following will work, making use of collections.Counter and itertools.groupby:

from itertools import groupby
from collections import Counter

def func(lst, elmnt):
    return Counter(len(list(g)) for k, g in groupby(lst) if k == elmnt)

>>> func(x, 'A')
Counter({2: 1, 3: 1})

While this will probably not be bested for single calls, you would be better off building an intermediate data structure that collects counts for groups of all different elements in a single go-around so that subsequent calls for individual elements won't have to iterate the entire list again:

from collections import defaultdict

def func(lst):
    c = Counter((k, len(list(g))) for k, g in groupby(lst))
    d = defaultdict(dict)
    for (k, length), count in c.items():
        d[k][length] = count
    return d.get

>>> f = func(x)  # builds intermediate structure (O(N)), returns function to query it
>>> f('A')  # these calls are now all O(1)
{2: 1, 3: 1}
>>> f('B')
{1: 1}


问:
Can new objects be instantiated without the = new Obj ()?
So String isn't a primitive type but rather a class and objects of classes have to be created in the form Obj x = new Obj (); usually. However, strings can be created by saying String x = "..."; and this is the preferred way rather than String x = new String ("...");.

So I was wondering why this is allowed for strings and would it be possible to create objects of other classes in a similar fashion if the constructor only required a single parameter.

For example, if a class had a constructor that only called one integer, would saying Obj x = 2; be syntactically correct because it has the object name and parameter still included in the same way that Strings are written.

答: It is not possible to do this in Java.  It is only possible with primitive type variables and String.  Since String is used so much, it is special and you do not have to write out the full new String("...").  The String x = "..." is an exception, not the usual for creating objects.


问:
@EJB injection vs lookup - performance issue
I have a question related with possible performance issue while using @EJB annotation. Imagine following scenario

```<code>public class MyBean1 implements MyBean1Remote{
 @EJB
 private MyBean2Remote myBean2;
 @EJB
 private MyBean2Remote myBean3;
 ...
 @EJB
 private MyBean20Remote myBean20;
}
</code>```

There is a bean with many dependencies to other beans. According to EJB spec if I would like to inject MyBean1Remote to some other bean, container would have to take all required dependencies from its pool inject it into MyBean1Remote and then inject reference to MyBean1Remote stub.

so in following scenario container needs to reserved 20 ejbs (myBean1 and its 19 dependencies)

```<code>public class MyAnotherBean implement MyAnotherRemote{
  @EJB
  private MyBean1Remote myBean1
}
</code>```

Let say that in most cases we will use only single dependency per each business method of myBean1. As a result each time  we want to inject that bean we force container to reserves many unnecessery EJBs. Lets also assume that we are operating on remote beans so probably container would also need to perform some load balancing algorithm prior injecting dependent beans.

Questions:

Wouldn't that cause unnecessary resource reservation and more over performance issue while operating in cluster environment?

Maybe good old ServiceLocator could be better solution because with this approach we would ask for specific EJB when we really need it ?

答:
The container does not inject an instance of the EJB; it injects an instance of a lightweight container-generated proxy object that implements the desired interface.

```<code>public class MyBean1 implements MyBean1Remote {
   ...
}

public class MyAnotherBean implement MyAnotherRemote {
   @EJB
   private MyBean1Remote myBean1;
}
</code>```

In your example, MyAnotherBean.myBean1 will be injected with a proxy object that implements the MyBean1Remote interface.

Assuming a stateless session bean (since you mention pooling), the container does not allocate an actual EJB instance from the method-ready pool until a method is called on the proxy, and the instance is returned to the pool before the proxy method call returns.

Body:
I have a question related with possible performance issue while using @EJB annotation. Imagine following scenario

public class MyBean1 implements MyBean1Remote{
 @EJB
 private MyBean2Remote myBean2;
 @EJB
 private MyBean2Remote myBean3;
 ...
 @EJB
 private MyBean20Remote myBean20;
}

There is a bean with many dependencies to other beans. According to EJB spec if I would like to inject MyBean1Remote to some other bean, container would have to take all required dependencies from its pool inject it into MyBean1Remote and then inject reference to MyBean1Remote stub.

so in following scenario container needs to reserved 20 ejbs (myBean1 and its 19 dependencies)

public class MyAnotherBean implement MyAnotherRemote{
  @EJB
  private MyBean1Remote myBean1
}

Let say that in most cases we will use only single dependency per each business method of myBean1. As a result each time  we want to inject that bean we force container to reserves many unnecessery EJBs. Lets also assume that we are operating on remote beans so probably container would also need to perform some load balancing algorithm prior injecting dependent beans.

Questions:

Wouldn't that cause unnecessary resource reservation and more over performance issue while operating in cluster environment?

Maybe good old ServiceLocator could be better solution because with this approach we would ask for specific EJB when we really need it ?

Body:
The container does not inject an instance of the EJB; it injects an instance of a lightweight container-generated proxy object that implements the desired interface.

public class MyBean1 implements MyBean1Remote {
   ...
}

public class MyAnotherBean implement MyAnotherRemote {
   @EJB
   private MyBean1Remote myBean1;
}

In your example, MyAnotherBean.myBean1 will be injected with a proxy object that implements the MyBean1Remote interface.

Assuming a stateless session bean (since you mention pooling), the container does not allocate an actual EJB instance from the method-ready pool until a method is called on the proxy, and the instance is returned to the pool before the proxy method call returns.


问:
how to disable or hide the right and left arrow from keyboard with ViewPager android
I am trying to disable left and right on the keyboard with this code but viewPager on the press of left and right button change the state of the pager.

```<code>edComment.setOnEditorActionListener(
    new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (actionId == EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS
                || actionId == EditorInfo.IME_FLAG_NAVIGATE_NEXT
                || actionId == EditorInfo.IME_ACTION_PREVIOUS
                || actionId == EditorInfo.IME_ACTION_NEXT
                ) {

            return false;

        }
        // Return true if you have consumed the action, else false.
        return false;
    }
});
</code>```

答: The keyboard app can show whatever keys it wants.  There is no way to force it not to show certain buttons, and even if there was another keyboard wouldn't follow the same rules.</p>

Body:
I am trying to disable left and right on the keyboard with this code but viewPager on the press of left and right button change the state of the pager.

edComment.setOnEditorActionListener(
    new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (actionId == EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS
                || actionId == EditorInfo.IME_FLAG_NAVIGATE_NEXT
                || actionId == EditorInfo.IME_ACTION_PREVIOUS
                || actionId == EditorInfo.IME_ACTION_NEXT
                ) {

            return false;

        }
        // Return true if you have consumed the action, else false.
        return false;
    }
});


问:
How to not feed in certain inputs in Tensorflow?
Suppose I have a Fully Connected Neural Network like this in Tensorflow:

```<code>input_1 = tf.placeholder(tf.float32, [batchSize, numInputs])
input_2 = tf.placeholder(tf.float32, [batchSize, numInputs2])
fc_1 = tf.contrib.layers.fully_connected(input_1, num_outputs=128, activation_fn=tf.nn.relu)
fc_2 = tf.contrib.layers.fully_connected(input_2, num_outputs=128, activation_fn=tf.nn.relu)
fc_3 = tf.contrib.layers.fully_connected(fc_1 + fc_2, num_outputs=100, activation_fn=tf.nn.relu)
output = tf.nn.softmax(fc_3)
</code>```

This network takes two inputs, each of which go through a fully connected layer. Then, these are added up, and passed through another fully connected layer, and finally a softmax is computed.

Let's say I train this network on some task, and then for another task, I want to use the same network, but not input_2. Thus, I will not have input_2. I am ok with ignoring fc_2 or not ignoring it, but the rest of the network will be the same as before. Is this possible? If so, how can you do it, and if not why not? I don't want to just save the parameters of this model and load it into the other model.

Thanks

答: For the second network, you can pass a tensor of zeros as the values of input_2. Then your fc_2 will be all zeros and when you sum it with fc_1, it will have no effect.

Body:
Suppose I have a Fully Connected Neural Network like this in Tensorflow:

input_1 = tf.placeholder(tf.float32, [batchSize, numInputs])
input_2 = tf.placeholder(tf.float32, [batchSize, numInputs2])
fc_1 = tf.contrib.layers.fully_connected(input_1, num_outputs=128, activation_fn=tf.nn.relu)
fc_2 = tf.contrib.layers.fully_connected(input_2, num_outputs=128, activation_fn=tf.nn.relu)
fc_3 = tf.contrib.layers.fully_connected(fc_1 + fc_2, num_outputs=100, activation_fn=tf.nn.relu)
output = tf.nn.softmax(fc_3)

This network takes two inputs, each of which go through a fully connected layer. Then, these are added up, and passed through another fully connected layer, and finally a softmax is computed.

Let's say I train this network on some task, and then for another task, I want to use the same network, but not input_2. Thus, I will not have input_2. I am ok with ignoring fc_2 or not ignoring it, but the rest of the network will be the same as before. Is this possible? If so, how can you do it, and if not why not? I don't want to just save the parameters of this model and load it into the other model.

Thanks


问:
Git: See my last commit
I just want to see the files that were committed in the last commit exactly as I saw the list when I did git commit. Unfortunately searching for

```<code>git "last commit" log
</code>```

in Google gets me nowhere. And

```<code>git diff HEAD^..HEAD
</code>```

is not what I need, of course, since it spews the guts of the change too.

答:
After you do several commits or clone/pull a repository, you might want to see what commits have been made. Just check these simple solutions to see your commit history (from last/recent commit to the first one).

For the last commit, just fire this command: git log -1. For more interesting things see below -

To see the commit ID (SHA-1 checksum), Author name <mail ID>, Date along with time, and commit message -

```<code>git log
</code>```

To see some more stats, such as the names of all the files changed during that commit and number of insertions/deletions. This comes in very handy while reviewing the code -

```<code>git log --stat
</code>```

To see commit histories in some pretty formats :) (This is followed by some prebuild options)-

If you have too many commits to review, this command will show them in a neat single line:

```<code>git log --pretty=oneline
</code>```

To see short, medium, full, or even more details of your commit, use following, respectively -

```<code>git log --pretty=short
git log --pretty=medium
git log --pretty=full
git log --pretty=fuller
</code>```

You can even use your own output format using the format option -

```<code>git log --pretty=format:"%an, %ae - %s"
</code>```

where %an - author name, %ae - author email, %s - subject of commit, etc.

This can help you with your commit histories. For more information, click here.

Title: Git: See my last commit

Body:
I just want to see the files that were committed in the last commit exactly as I saw the list when I did git commit. Unfortunately searching for

git "last commit" log

in Google gets me nowhere. And

git diff HEAD^..HEAD

is not what I need, of course, since it spews the guts of the change too.

Body:
After you do several commits or clone/pull a repository, you might want to see what commits have been made. Just check these simple solutions to see your commit history (from last/recent commit to the first one).

For the last commit, just fire this command: git log -1. For more interesting things see below -

To see the commit ID (SHA-1 checksum), Author name <mail ID>, Date along with time, and commit message -

git log

To see some more stats, such as the names of all the files changed during that commit and number of insertions/deletions. This comes in very handy while reviewing the code -

git log --stat

To see commit histories in some pretty formats :) (This is followed by some prebuild options)-

If you have too many commits to review, this command will show them in a neat single line:

git log --pretty=oneline

To see short, medium, full, or even more details of your commit, use following, respectively -

git log --pretty=short
git log --pretty=medium
git log --pretty=full
git log --pretty=fuller

You can even use your own output format using the format option -

git log --pretty=format:"%an, %ae - %s"

where %an - author name, %ae - author email, %s - subject of commit, etc.

This can help you with your commit histories. For more information, click here.


问:
Float left removes the hyperlinks
I know this is popular problem. I tried everything but still I could not make this work.
here is my html and css.

.unodered-item {
  float: left;
  overflow: hidden;
}
.item {
  height: 140px;
  width: 220px;
  margin-left: 10px;
  background: pink;
  //background-image: url("../resourses/tutorial-thumbnails/thumbnail.png");
  -webkit-background-size: cover;
  background-size: cover;
  overflow: hidden;
}

a.item-link {
  height: 140px;
  width: 220px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="recommended-list-items">
    <ul class="unodered unodered-recommended">
      <li class="unodered-item">
        <div class="item item'+ x +'">

        </div>
      </li>
    </ul>
</div></code>```

Help!!!

答:
Get the a tag outside of the div block. Is this what you want?</p>

```<code><div class="recommended-list-items">
        <ul class="unodered unodered-recommended">
          <li class="unodered-item"><a class="item-link" href="tutorial-player.jsp"><div class="item item'+ x +'"></div></a></li>
        </ul>
</div>
</code>```

Title: Float left removes the hyperlinks

Body:
I know this is popular problem. I tried everything but still I could not make this work.
here is my html and css.

.unodered-item {
  float: left;
  overflow: hidden;
}
.item {
  height: 140px;
  width: 220px;
  margin-left: 10px;
  background: pink;
  //background-image: url("../resourses/tutorial-thumbnails/thumbnail.png");
  -webkit-background-size: cover;
  background-size: cover;
  overflow: hidden;
}

a.item-link {
  height: 140px;
  width: 220px;
}

Help!!!

Body:
Get the a tag outside of the div block. Is this what you want?

<div class="recommended-list-items">
        <ul class="unodered unodered-recommended">
          <li class="unodered-item"><a class="item-link" href="tutorial-player.jsp"><div class="item item'+ x +'"></div></a></li>
        </ul>
</div>


问:
How to get response from another site in laravel controller
I want to create API in laravel which gives data return.
I want to get data from this link
into my laravel controller.</p>

答: You need to do a request to that url from your controller. This can be done by pulling in guzzle. Please see the readme of this repository: https://github.com/guzzle/guzzle</p>


问:
Template specialization for enum values
Is it possible to specialize a class method for individual enum values?
Specifically I have an enum and a class as follows:

```<code>#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      static void getSound ( const Animal& arg )
      {
         switch ( arg )
         {
           case Animal::dog:
             // dog specific processing
             break;

           case Animal::cat:
             // cat specific processing
             break;

           case Animal::bird:
             // bird specific processing
             break;

           default:
             return;
         }
      }
};
</code>```

I want to specialize getSound function for each of the enum values to get rid of the switch case. Is such template specialization possible?

答:
Yes, it is possible. Look at the sample below.</p>

```<code>#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      template<Animal animal>
      static void getSound ();
};

template<>
void Sound::getSound<Animal::dog> ()
{
    // dog specific processing
}

template<>
void Sound::getSound<Animal::cat> ()
{
    // cat specific processing
}

template<>
void Sound::getSound<Animal::bird> ()
{
    // bird specific processing
}

int main()
{
    Sound::getSound<Animal::dog>();
}
</code>```

Title: Template specialization for enum values

Body:
Is it possible to specialize a class method for individual enum values?
Specifically I have an enum and a class as follows:

#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      static void getSound ( const Animal& arg )
      {
         switch ( arg )
         {
           case Animal::dog:
             // dog specific processing
             break;

           case Animal::cat:
             // cat specific processing
             break;

           case Animal::bird:
             // bird specific processing
             break;

           default:
             return;
         }
      }
};

I want to specialize getSound function for each of the enum values to get rid of the switch case. Is such template specialization possible?

Body:
Yes, it is possible. Look at the sample below.

#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      template<Animal animal>
      static void getSound ();
};

template<>
void Sound::getSound<Animal::dog> ()
{
    // dog specific processing
}

template<>
void Sound::getSound<Animal::cat> ()
{
    // cat specific processing
}

template<>
void Sound::getSound<Animal::bird> ()
{
    // bird specific processing
}

int main()
{
    Sound::getSound<Animal::dog>();
}


问:
Textfields component number validation React js
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (
      <div className={cr.container}>
        <div className ={cr.boton}>
          <Divider/>
          <br/>
        </div>

        <div className={cr.rows}>
          <div>
            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />
          </div>
        </div>

        <div className={cr.botonSet}>
          <div className={cr.botonMargin}>
            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>
          </div>
          <div>
            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />
          </div>
        </div>
      </div>
    );
  }
}
</code>```

Can someone help me on this please.

Thanks in advance.

答:
You are not initialising error object in state but accessed in TextField as this.state.and_error. Either you should initialise error in constructor like this.state = { and_error: "" } or initialise error object as

```<code>this.state = {
    error: {
       and_error: "",
       buy_error: "",
       save_error: ""
    }
}
</code>```

So in your TextField

```<code><TextField
      onChange={(e) => {
        if(e.target.value === "" || (/\D/.test(e.target.value))) {
           this.setState({and_: e.target.value})}
        }
        else {
          return false;
        }
      }
      value={this.state.and_}
      errorText={this.state.error.and_error} // If initialised error string access as this.state.and_error
      floatingLabelText="And"
/>
</code>```

Your validate function will be like

```<code>validate() {
    let isError = false;
    const errors = this.state.errors;

    if (this.state.buy_.toString().length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }

    if (this.state.and_.toString().length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }

    if (this.state.save_.toString().length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({errors});

    return isError;
}
</code>```

Hope this will heps you!

Body:
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (

          <Divider/>

            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />

            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />

            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />

            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>

            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />

    );
  }
}

Can someone help me on this please.

Thanks in advance.

Body:
You are not initialising error object in state but accessed in TextField as this.state.and_error. Either you should initialise error in constructor like this.state = { and_error: "" } or initialise error object as

this.state = {
    error: {
       and_error: "",
       buy_error: "",
       save_error: ""
    }
}

So in your TextField

<TextField
      onChange={(e) => {
        if(e.target.value === "" || (/\D/.test(e.target.value))) {
           this.setState({and_: e.target.value})}
        }
        else {
          return false;
        }
      }
      value={this.state.and_}
      errorText={this.state.error.and_error} // If initialised error string access as this.state.and_error
      floatingLabelText="And"
/>

Your validate function will be like

validate() {
    let isError = false;
    const errors = this.state.errors;

    if (this.state.buy_.toString().length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }

    if (this.state.and_.toString().length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }

    if (this.state.save_.toString().length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({errors});

    return isError;
}

Hope this will heps you!


问:
Scraping error in R package readHTMLTable: Error in make.names invalid multibyte string
I am trying to get some data from a HTML web by using readHTMLTable.

The web contains some Chinese utf-8 code, so it usually gives me some error.

First try:

```<code>u = "http://app.finance.ifeng.com/hq/stock_daily.php?code=sh600030"
url = htmlParse(u)
tbls = readHTMLTable(u,asText= TRUE)

dat <- data.frame(tbls)
</code>```

ERROR:Error in make.names(vnames, unique = TRUE) : invalid multibyte string 5

答:
The solution is to add the argument encoding = "UTF-8", in my case, to these functions or connections. More generally, providing the default encoding or a hook before parsing might be a more robust solution.

url = htmlParse(baseURL, encoding="GB2312")
table=readHTMLTable(url,header=,which=1,encoding="UTF-8")

Body:
I am trying to get some data from a HTML web by using readHTMLTable.

The web contains some Chinese utf-8 code, so it usually gives me some error.

First try:

u = "http://app.finance.ifeng.com/hq/stock_daily.php?code=sh600030"
url = htmlParse(u)
tbls = readHTMLTable(u,asText= TRUE)

dat <- data.frame(tbls)

ERROR:Error in make.names(vnames, unique = TRUE) : invalid multibyte string 5


问:
queryset.update is not working in for loop
I want to change the name for any database variable if its match abc.

```<code>def icall(modeladmin, request, queryset):
    for pri in queryset:
        print('from test:', pri.name, pri.title) # priting if working fine
        if pri.name == 'abc':        # loop is matching the condition
            pri.update(name='zzz')  ## the value is not getting update in DB
        else:
            print("gg not mached")
</code>```

the pri.update(name='zzz') os not working here.

can someone please help me to know the correct statement to update the database based on the if else condition.

答:
```<code>def icall(modeladmin, request, queryset):
    for pri in queryset:
        print('from test:', pri.name, pri.title)
        if pri.name == 'abc':
            pri.name ='zzz'
            pri.save()
            print("working")
        else:
            print("gg not mached")
</code>```

Body:
I want to change the name for any database variable if its match abc.

def icall(modeladmin, request, queryset):
    for pri in queryset:
        print('from test:', pri.name, pri.title) # priting if working fine
        if pri.name == 'abc':        # loop is matching the condition
            pri.update(name='zzz')  ## the value is not getting update in DB
        else:
            print("gg not mached")

the pri.update(name='zzz') os not working here.

can someone please help me to know the correct statement to update the database based on the if else condition.


问:
No module named (Python)
I created a file called Despike_Goring_Nikora, with contains two functions:

```<code>def ExcludeOutlierEllipsoid3D(xi, yi, zi, theta, universalThreshold):
</code>```

and

```<code>def PhaseSpaceDespike1d(vel):
</code>```

I put this file in Python Scripts folder, and assured to add this one to path.

In another file called ADP_data, which is in a different folder, I'd like to call these functions. So at the beginning I was doing

```<code>import Despike_Goring_Nikora
</code>```

I also tried

```<code>from Despike_Goring_Nikora import PhaseSpaceDespike1d
</code>```

But all I receive is

```<code>ModuleNotFoundError: No module named 'Despike_Goring_Nikora'
</code>```

答:
To make a particular directory to be considered as a module in python you need to create a __init__.py file inside it.

Besides you need to ad .py to your files:

Despike_Goring_Nikora.py,

APP_Data.py.

Also you're naming your functions/modules in a wrong way. Please try to stick to Python naming convention.

Title: No module named (Python)

Body:
I created a file called Despike_Goring_Nikora, with contains two functions:

def ExcludeOutlierEllipsoid3D(xi, yi, zi, theta, universalThreshold):

and

def PhaseSpaceDespike1d(vel):

I put this file in Python Scripts folder, and assured to add this one to path.

In another file called ADP_data, which is in a different folder, I'd like to call these functions. So at the beginning I was doing

import Despike_Goring_Nikora

I also tried

from Despike_Goring_Nikora import PhaseSpaceDespike1d

But all I receive is

ModuleNotFoundError: No module named 'Despike_Goring_Nikora'


问:
What's the simplest way to create a facebook frontend-javascript authentification (for a facebook app)?
In the facebook/connect-js, there are some really neat features like "FB.login" for logging in and FB.logout, for logging out, is there something similair for authentification for example?</p>

答:
You can use FB.login to get the authentication.</p>

```<code>        FB.login(function(response) {
        var access_token = response.session.access_token;
            if (response.session) {
                if (response.perms) {
                  // user is logged in, everithig is ok
                } else {
                  // user is logged in, but did not grant any permissions
        }
              } else {
                // user is not logged in
      }
        }, {perms:'read_stream,publish_stream,offline_access'});
</code>```

Body:
You can use FB.login to get the authentication.

        FB.login(function(response) {
        var access_token = response.session.access_token;
            if (response.session) {
                if (response.perms) {
                  // user is logged in, everithig is ok
                } else {
                  // user is logged in, but did not grant any permissions
        }
              } else {
                // user is not logged in
      }
        }, {perms:'read_stream,publish_stream,offline_access'});


问:
How to prevent selecting date range in which there is a disabled date in between?
I have two Jquery date pickers, in which a range of dates can be selected.

I have implemented certain restrictions like, the date of textbox2 should be always greater than textbox1. In addition I have disabled certain dates.

What I need is, if a user selects from date, and then selects to date, if there exist a disabled date in between, then the user should not be able to select that range.

For example:

I have disabled the dates: "31-5-2014", "1-6-2014", "2-6-2014"

If user selects date1 as 29-5-2014, and tries to select 4-6-2014 as the second date, then he should not be able to do that as disabled dates are in betweeb. The max value for date2 must be 30-5-2014

Adding the fiddle

答:
```<code>    var StartDate = $("#start_date").val();
    var EndDates = $("#end_date").val();
    var selectedDate = $("#selected_date").val();

    //-- Start Date Convert in YMD
    var Sdate = StartDate.split("-");
    var Syear= Sdate[2];
    var Smonth= Sdate[1];
    var Sday= Sdate[0];
    var SYMDDate = Syear + '-' + Smonth + '-' + Sday;
    var newdate= new Date(SYMDDate);
    var StartDateStrToTime=newdate.getTime();

    //-- End Date Convert in YMD
    var Edate = EndDates.split("-");
    var Eyear= Edate[2];
    var Emonth= Edate[1];
    var Eday= Edate[0];
    var EYMDDate = Eyear + '-' + Emonth + '-' + Eday;
    var newdates= new Date(EYMDDate);
    var EndDateStrToTime=newdates.getTime();

    //-- Selected Date Convert in YMD
    var Cdate = selectedDate.split("-");
    var Cyear= Cdate[2];
    var Cmonth= Cdate[1];
    var Cday= Cdate[0];
    var CYMDDate = Cyear + '-' + Cmonth + '-' + Cday;
    var newdateses= new Date(CYMDDate);
    var SelectedDateStrToTime=newdateses.getTime();

    if((SelectedDateStrToTime>=StartDateStrToTime) && (SelectedDateStrToTime<=EndDateStrToTime))
    {}
    else
    {
        alert("Please Select date between "+StartDate+" to " +EndDates+".");
        $("#selected_date").val(EndDates);
    }
</code>```


答:
Update query is done on a queryset. It is not done on a single object like you are trying to do. You can simply do</p>

```<code>queryset.filter(name='abc').update(name='zzz')
</code>```

Title: queryset.update is not working in for loop

Body:
Update query is done on a queryset. It is not done on a single object like you are trying to do. You can simply do

queryset.filter(name='abc').update(name='zzz')


问:
Autofilter then Copy and Paste Range
I wrote a code below.
Intention is to autofilter column K with criteria, copy data and paste it at the bottom of the sheet on the same page, just below the last row.

I am not getting any error, but code is not working as intended.
It works up to autofilter and copy, but it won't paste the data to the last row.
Can I please get some assistance.

```<code>Sub Depreciation_to_Zero()
With Sheets("Restaurant")
.AutoFilterMode = False
With .Range("k1", .Range("k" & .Rows.Count).End(xlUp))
    .AutoFilter Field:=1, Criteria1:="*HotDog*"
    On Error Resume Next
    .Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Copy
    .Cells(.Rows.Count, "A").End(xlUp).Row.Select.PasteSpecial xlPasteValues
    On Error GoTo 0
End With

.AutoFilterMode = False
End With
MsgBox ("Complete")
End Sub
</code>```

答:
Try this version

```<code>Option Explicit

Public Sub DepreciationToZero()

    Const FIND_VAL = "*HotDog*"

    Dim ws As Worksheet, lr As Long, result As String

    Set ws = Worksheets("Restaurant")
    Application.ScreenUpdating = False
    ws.AutoFilterMode = False
    lr = ws.Cells(ws.Rows.Count, "K").End(xlUp).Row
    result = FIND_VAL & " not found"

    With ws.UsedRange
        ws.Range("K1:K" & lr).AutoFilter Field:=1, Criteria1:=FIND_VAL
        If ws.Range("K1:K" & lr).SpecialCells(xlCellTypeVisible).CountLarge > 1 Then
            .Offset(1).Resize(lr - 1).SpecialCells(xlCellTypeVisible).Copy
            .Offset(lr).Cells(1).PasteSpecial xlPasteValues
            .Offset(lr).Cells(1).Select
            Application.CutCopyMode = False
            result = "All " & FIND_VAL & " rows copied"
        End If
    End With

    ws.AutoFilterMode = False
    Application.ScreenUpdating = True
    MsgBox result
End Sub
</code>```

Title: Autofilter then Copy and Paste Range

Body:
I wrote a code below.
Intention is to autofilter column K with criteria, copy data and paste it at the bottom of the sheet on the same page, just below the last row.

I am not getting any error, but code is not working as intended.
It works up to autofilter and copy, but it won't paste the data to the last row.
Can I please get some assistance.

Sub Depreciation_to_Zero()
With Sheets("Restaurant")
.AutoFilterMode = False
With .Range("k1", .Range("k" & .Rows.Count).End(xlUp))
    .AutoFilter Field:=1, Criteria1:="*HotDog*"
    On Error Resume Next
    .Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Copy
    .Cells(.Rows.Count, "A").End(xlUp).Row.Select.PasteSpecial xlPasteValues
    On Error GoTo 0
End With

.AutoFilterMode = False
End With
MsgBox ("Complete")
End Sub

Body:
Try this version

Option Explicit

Public Sub DepreciationToZero()

    Const FIND_VAL = "*HotDog*"

    Dim ws As Worksheet, lr As Long, result As String

    Set ws = Worksheets("Restaurant")
    Application.ScreenUpdating = False
    ws.AutoFilterMode = False
    lr = ws.Cells(ws.Rows.Count, "K").End(xlUp).Row
    result = FIND_VAL & " not found"

    With ws.UsedRange
        ws.Range("K1:K" & lr).AutoFilter Field:=1, Criteria1:=FIND_VAL
        If ws.Range("K1:K" & lr).SpecialCells(xlCellTypeVisible).CountLarge > 1 Then
            .Offset(1).Resize(lr - 1).SpecialCells(xlCellTypeVisible).Copy
            .Offset(lr).Cells(1).PasteSpecial xlPasteValues
            .Offset(lr).Cells(1).Select
            Application.CutCopyMode = False
            result = "All " & FIND_VAL & " rows copied"
        End If
    End With

    ws.AutoFilterMode = False
    Application.ScreenUpdating = True
    MsgBox result
End Sub


问:
Terminal cp won't copy path folders with special characters within for loop?
I'm working on a bash script to recursively copy dated folders from a Time Machine backup, and subsequently deduplicate.  As expected, the cp (copy) command copies the intended 'foldertocopy' correctly when used outside the loop and directly in terminal (-R and -L flags set) - but not when placed within the loop of the script, which only copies contents.  Is this due to a special character in the source path within the loop?  Escaping the ' ’s ' in the source path fails, with terminal indicating there's no source for cp.

The script reads a text file ($source) containing time machine dates into an array (DATES), then copies the intended folder to the new destination.  The new destination path is constructed from user input (i.e. read -p "Destination" dest).

```<code>IFS=$'\n' read -d '' -r -a DATES < $source
for date in "${DATES[@]}"
do
    cp -RL /Volumes/Time\ Machine\ Backups/Backups.backupdb/Stix\'s’s\ MacBook\ Pro/$date/Macintosh\ HD/Users/foldertocopy /$dest/$date/$name
done
</code>```

When cp is in the loop, the foldertocopy contents are copied as though there is no -R flag set.

What do I change to have the directory copied instead of the contents?

Update:
Using the unicode sequence in the path works, although in this case wasn't necessary.

答:
I see these variables used in the cp command's arguments:

$date

$dest

$name

If not enclosed in double-quotes, and if they contain spaces or other special characters, that will break the command.

The cp command will be safer and simpler to write like this:

```<code>cp -RL "/Volumes/Time Machine Backups/Backups.backupdb/Stix's’s MacBook Pro/$date/Macintosh HD/Users/foldertocopy" "/$dest/$date/$name"
</code>```

Also I have a doubt about this folder name:

```<code>/Volumes/Time Machine Backups/Backups.backupdb/Stix's’s MacBook Pro
</code>```

Are you sure you have 's’s in there? Verify the correct name.
(What is the output of ls -d "/Volumes/Time Machine Backups/Backups.backupdb/Stix"*?)

Body:
I'm working on a bash script to recursively copy dated folders from a Time Machine backup, and subsequently deduplicate.  As expected, the cp (copy) command copies the intended 'foldertocopy' correctly when used outside the loop and directly in terminal (-R and -L flags set) - but not when placed within the loop of the script, which only copies contents.  Is this due to a special character in the source path within the loop?  Escaping the ' ’s ' in the source path fails, with terminal indicating there's no source for cp.

The script reads a text file ($source) containing time machine dates into an array (DATES), then copies the intended folder to the new destination.  The new destination path is constructed from user input (i.e. read -p "Destination" dest).

IFS=$'\n' read -d '' -r -a DATES < $source
for date in "${DATES[@]}"
do
    cp -RL /Volumes/Time\ Machine\ Backups/Backups.backupdb/Stix\'s’s\ MacBook\ Pro/$date/Macintosh\ HD/Users/foldertocopy /$dest/$date/$name
done

When cp is in the loop, the foldertocopy contents are copied as though there is no -R flag set.

What do I change to have the directory copied instead of the contents?

Update:
Using the unicode sequence in the path works, although in this case wasn't necessary.

Body:
I see these variables used in the cp command's arguments:

$date

$dest

$name

If not enclosed in double-quotes, and if they contain spaces or other special characters, that will break the command.

The cp command will be safer and simpler to write like this:

cp -RL "/Volumes/Time Machine Backups/Backups.backupdb/Stix's’s MacBook Pro/$date/Macintosh HD/Users/foldertocopy" "/$dest/$date/$name"

Also I have a doubt about this folder name:

/Volumes/Time Machine Backups/Backups.backupdb/Stix's’s MacBook Pro

Are you sure you have 's’s in there? Verify the correct name.
(What is the output of ls -d "/Volumes/Time Machine Backups/Backups.backupdb/Stix"*?)