问:
Internal errors in Coverity when building C++11 code
I'm getting internal errors in Coverity when building a C++11 project. The log shows errors like this:

```<code>Internal error #2688: assertion failed at: "edg/src/lower_name.c", line 4810
internal error #2688: assertion failed at: "edg/src/scope_stk.c", line 10898
</code>```

I'm using Mac OS X (Sierra) and configured the compiler using:

```<code>cov-configure --comptype clangcxx -co /usr/bin/c++
</code>```

Here are all steps to reproduce the issue:

```<code>git clone --recursive -b develop https://github.com/actor-framework/actor-framework.git
cd actor-framework
./configure --build-type=debug --with-runtime-checks --no-opencl --no-python
cov-build --dir "cov-int" make
</code>```

I've uploaded the full build log here (it's huge, you've been warned): https://gist.githubusercontent.com/Neverlord/bb5709452236d584fcaabf56c0ae7295/raw/aad490f79b4fa2fab40dd99ffbe9aa75611b2fff/build-log.txt

Any help is much appreciated.

答:
I took a peek at the build log, and it doesn't seem related to your Clang configuration (which is good, since that should be using Coverity's Clang-based FE, not the EDG-based FE.

One of the offending compilations is:

```<code>/opt/local/bin/g++-mp-4.9 -Dlibcaf_core_shared_EXPORTS -I/opt/local/include -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_opencl -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_core -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_io -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_test -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_core/. -std=c++11 -Wextra -Wall -pedantic -Wno-missing-field-initializers -fPIC -g -fPIC -o CMakeFiles/libcaf_core_shared.dir/src/abstract_coordinator.cpp.o -c /Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_core/src/abstract_coordinator.cpp
</code>```

The internal assertion doesn't appear to be in Coverity's bug database, so this looks to represent a previously unknown issue in the EDG-based FE. If you could create a reproducer and send it to scan-admin@coverity.com, it would be very much appreciated; internal errors such as this defeat Coverity's error recovery and are generally high priority to be fixed.

Once the code construct that's causing the assertion is identified, it may be possible to work around it (e.g. with --ppp_translator).

The following steps may help you create a reproducer:

```<code>$ cov-manage-emit --dir <idir> -tp 'failure()' list
</code>```

(pick one from the list of failures that matches the internal assertion you see in the build log, note the TU number)

```<code>$ cov-manage-emit --dir <idir> --tu <TU> reduce
</code>```

(reduced file will be placed under /output/preprocessed).

Body:
I'm getting internal errors in Coverity when building a C++11 project. The log shows errors like this:

Internal error #2688: assertion failed at: "edg/src/lower_name.c", line 4810
internal error #2688: assertion failed at: "edg/src/scope_stk.c", line 10898

I'm using Mac OS X (Sierra) and configured the compiler using:

cov-configure --comptype clangcxx -co /usr/bin/c++

Here are all steps to reproduce the issue:

git clone --recursive -b develop https://github.com/actor-framework/actor-framework.git
cd actor-framework
./configure --build-type=debug --with-runtime-checks --no-opencl --no-python
cov-build --dir "cov-int" make

I've uploaded the full build log here (it's huge, you've been warned): https://gist.githubusercontent.com/Neverlord/bb5709452236d584fcaabf56c0ae7295/raw/aad490f79b4fa2fab40dd99ffbe9aa75611b2fff/build-log.txt

Any help is much appreciated.

Body:
I took a peek at the build log, and it doesn't seem related to your Clang configuration (which is good, since that should be using Coverity's Clang-based FE, not the EDG-based FE.

One of the offending compilations is:

/opt/local/bin/g++-mp-4.9 -Dlibcaf_core_shared_EXPORTS -I/opt/local/include -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_opencl -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_core -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_io -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_test -I/Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_core/. -std=c++11 -Wextra -Wall -pedantic -Wno-missing-field-initializers -fPIC -g -fPIC -o CMakeFiles/libcaf_core_shared.dir/src/abstract_coordinator.cpp.o -c /Users/jenkins/jenkins_home/workspace/CAF/nightly/actor-framework/libcaf_core/src/abstract_coordinator.cpp

The internal assertion doesn't appear to be in Coverity's bug database, so this looks to represent a previously unknown issue in the EDG-based FE. If you could create a reproducer and send it to scan-admin@coverity.com, it would be very much appreciated; internal errors such as this defeat Coverity's error recovery and are generally high priority to be fixed.

Once the code construct that's causing the assertion is identified, it may be possible to work around it (e.g. with --ppp_translator).

The following steps may help you create a reproducer:

$ cov-manage-emit --dir <idir> -tp 'failure()' list

(pick one from the list of failures that matches the internal assertion you see in the build log, note the TU number)

$ cov-manage-emit --dir <idir> --tu <TU> reduce

(reduced file will be placed under /output/preprocessed).


来源: stackexchange

问:
Cannot Compile .CS code in VS 2010
I want to write quick console apps and compile them with VS 2010, but if I create a .cs file, then open it in VS 2010 (by simply double-clicking on the .cs file as these are registered by VS 2010), it opens, but there is no possible way to compile it.

e.g. here is some simplistic code:

```<code>using System;
public class Hello
{
   public static void Main()
   {
      Console.WriteLine("Hello C# World");
   }
}
</code>```

I can compile this from the command line using    csc.exe hello.cs

But, if I can edit it in VS 2010, I should (sensibly) be able to compile it from the VS 2010 interface (plus debug, step through etc). In fact, although I can open and edit, it seems that Microsoft have made it impossible to compile in this way.

Could someone with knowledge of this please explain how to compile a simple .cs file from within the VS 2010 editor please ?

答:
You need a project and solution to compile code in Visual Studio. Simply create a new C# Console Application, edit it, and run it.

Unless you elect to save the project/solution, VS can discard the entire thing. This is the best way to whip up quick example code.

Updated

I have a number of programs that are single-.cs files myself. When I want to tinker with them I simply create a new C# project and then add the file as a link. When I'm done tinkering, I close VS and choose discard. Because the .cs file was linked and not cloned, all changes are made to the original file. The discard only destroys the [temporary] project and solution files.

When I want to create something new, I create a new C# project and start writing. When I'm done, I use File -> Save As to save just the .cs file to a location where I keep all my single-source projects. I then discard the project/solution. Note that using File -> Save As creates a link so you don't have to wait until your done to do this.

ContentLicense: CC BY-SA 2.5

Title: Cannot Compile .CS code in VS 2010

Body:
I want to write quick console apps and compile them with VS 2010, but if I create a .cs file, then open it in VS 2010 (by simply double-clicking on the .cs file as these are registered by VS 2010), it opens, but there is no possible way to compile it.

e.g. here is some simplistic code:

using System;
public class Hello
{
   public static void Main()
   {
      Console.WriteLine("Hello C# World");
   }
}

I can compile this from the command line using    csc.exe hello.cs

But, if I can edit it in VS 2010, I should (sensibly) be able to compile it from the VS 2010 interface (plus debug, step through etc). In fact, although I can open and edit, it seems that Microsoft have made it impossible to compile in this way.

Could someone with knowledge of this please explain how to compile a simple .cs file from within the VS 2010 editor please ?


问:
Getting the third moving date
I need to get the third moving date based on address for each person. Either status change or address change will make DT change. For example, for PERSON_ID:1, the third moving date should be 07/16/2016. Thanks!
The data is as below:</p>

```<code>PERSON_ID      STATUS      DT        ADDRESS
1                12      5/6/2016      3
1                 6      5/8/2016      3
1                 7      6/5/2016      3
1                 1      6/13/2016     3
1                 12    6/20/2016      1
1                 17    7/8/2016       1
1                  1    7/11/2016      1
1                 12    7/16/2016      2
1                  3    12/6/2016      2
2                  5    3/11/2016      5
2                  1    5/15/2016      4
2                  6    7/18/2016      6
2                 12    7/21/2016      6
</code>```

答:
I'm not sure i understood what you need to get but I think what you're trying to do is something like:</p>

```<code>SELECT * FROM
(
SELECT person_id,adress,[status],DT, rank() over (partition by person_id order by adress,dt)-1 as movement
FROM @t
WHERE person_id=1
) t
WHERE t.movement=3
</code>```

ContentLicense: CC BY-SA 3.0

Title: Getting the third moving date

Body:
I need to get the third moving date based on address for each person. Either status change or address change will make DT change. For example, for PERSON_ID:1, the third moving date should be 07/16/2016. Thanks!
The data is as below:

PERSON_ID      STATUS      DT        ADDRESS
1                12      5/6/2016      3
1                 6      5/8/2016      3
1                 7      6/5/2016      3
1                 1      6/13/2016     3
1                 12    6/20/2016      1
1                 17    7/8/2016       1
1                  1    7/11/2016      1
1                 12    7/16/2016      2
1                  3    12/6/2016      2
2                  5    3/11/2016      5
2                  1    5/15/2016      4
2                  6    7/18/2016      6
2                 12    7/21/2016      6

Body:
I'm not sure i understood what you need to get but I think what you're trying to do is something like:

SELECT * FROM
(
SELECT person_id,adress,[status],DT, rank() over (partition by person_id order by adress,dt)-1 as movement
FROM @t
WHERE person_id=1
) t
WHERE t.movement=3


问:
Invalid argument when converting float to datetime
I have to get a datetime from a float using Python. I am tryint to use the following code:

```<code>import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))
</code>```

But when executing this code, I get an error:

```<code>OSError: [Errno 22] Invalid argument
</code>```

The sys.float_info.max displays 1.7976931348623157e+308.

How do I convert this float number into a datetime?

答:
Try this :</p>

```<code>import datetime
print datetime.datetime.fromtimestamp(63650571169.50261)
#3987-01-03 05:12:49.502609
</code>```

Body:
I have to get a datetime from a float using Python. I am tryint to use the following code:

import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))

But when executing this code, I get an error:

OSError: [Errno 22] Invalid argument

The sys.float_info.max displays 1.7976931348623157e+308.

How do I convert this float number into a datetime?

Body:
Try this :

import datetime
print datetime.datetime.fromtimestamp(63650571169.50261)
#3987-01-03 05:12:49.502609


问:
How can I move the p tag's position up instead of it being at the bottom?
This is the JSFiddle example. I want to move the p tag so that it is displayed inline at the top, not at the bottom.

```<code><!DOCTYPE html>
<html>
<head>
<style>
div {
    display: inline;
}

p {
    border-bottom: 6px solid red;
    background-color: lightgrey;
    padding: 10px;
    max-width: 100px;
    display: inline-block;
    margin-right: 10px;
    max-height: 200px;
    font-family: "Arial";
}

p:hover {
    background-color: #CCCCCC;
    cursor: pointer;
}
</style>
</head>
<body>
<div>
    <p>This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.</p>

    <p>This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.</p>

    <p>This property is a shorthand property for border-bottom-width.</p>
</div>

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

https://jsfiddle.net/om7orw9w/

答:
Looks like you just want to use the vertical-align property, set to top

div {
 display: inline;
}

p {
    border-bottom: 6px solid red;
    background-color: lightgrey;
    padding: 10px;
    max-width: 100px;
    display: inline-block;
    margin-right: 10px;
    max-height: 250px;
    font-family: "Arial";
    vertical-align: top;
}

p:hover {
 background-color: #CCCCCC;
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.</p>

  <p>This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.</p>

  <p>This property is a shorthand property for border-bottom-width.</p>
</div></code>```

Body:
This is the JSFiddle example. I want to move the p tag so that it is displayed inline at the top, not at the bottom.

<!DOCTYPE html>

This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.

This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.

This property is a shorthand property for border-bottom-width.

https://jsfiddle.net/om7orw9w/

Body:
Looks like you just want to use the vertical-align property, set to top

div {
 display: inline;
}

p {
    border-bottom: 6px solid red;
    background-color: lightgrey;
    padding: 10px;
    max-width: 100px;
    display: inline-block;
    margin-right: 10px;
    max-height: 250px;
    font-family: "Arial";
    vertical-align: top;
}

p:hover {
 background-color: #CCCCCC;
    cursor: pointer;
}

<div>
  <p>This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.</p>

  <p>This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.</p>

  <p>This property is a shorthand property for border-bottom-width.</p>
</div>


问:
How display a new image in a div, saved in local storage, each time the user re-visits the page?
Hard to explain in the title, let me explain.

I have 3 images and I would like them to be displayed in a div and rotate everytime a user re-visits the page (They will see one image when they visit, and a different image the next time).

I was thinking of having a variable like 'count' which increments each time the user visits, and the value of count would relate to which image is displayed in this div, however I'm not sure how to save the 3 images in the local storage.

I'm expecting the logic wpould be like

```<code>setItem (Img1)
setItem (Img2)
setItem (Img3)

count = count + 1

if count = 1
    div = getItem(Img1)
if count = 2
 etc etc
</code>```

I guess my question is:

Is there a way to store images in the local storage without first adding them to the page?

EDIT

This is now the code I'm using, however an image is not displayed, the div just displays the image location.

```<code>var counter = localStorage.getItem('counter');
  if(counter == null) {
    localStorage.setItem("counter", 0);
    localStorage.setItem("images",'["assets/advert1.png","assets/advert2.png","assets/advert3.png"]');
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[0]);
  }
  else {
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[counter]);
    counter++;
    if(counter > 2) {
      counter = 0;
    }

    localStorage.setItem("counter", counter);
  }
</code>```

(Note this is inside a document.ready function)

答:
All you have to do is use two variables, one to store an array of images and another to store the currently shown index.

$(document).ready(function(){
  var counter = localStorage.getItem('counter');
  if(counter == null)
  {
    localStorage.setItem("counter",0);
    localStorage.setItem("images",'["1.png","2.png","3.png"]');
    $('#displayArea').attr("src",JSON.parse(localStorage.getItem('images'))[0]);
  }
  else
  {
    $('#displayArea').attr("src",JSON.parse(localStorage.getItem('images'))[counter]);
    counter++;
    if(counter > 2)
    {
      counter = 0;
    }
    localStorage.setItem("counter",counter);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img id="displayArea"></img></code>```

UPDATE

This code will produce an error in the stack snippet as it is a sandboxed environment. This snippet runs perfectly on a web page.

Body:
Hard to explain in the title, let me explain.

I have 3 images and I would like them to be displayed in a div and rotate everytime a user re-visits the page (They will see one image when they visit, and a different image the next time).

I was thinking of having a variable like 'count' which increments each time the user visits, and the value of count would relate to which image is displayed in this div, however I'm not sure how to save the 3 images in the local storage.

I'm expecting the logic wpould be like

setItem (Img1)
setItem (Img2)
setItem (Img3)

count = count + 1

if count = 1
    div = getItem(Img1)
if count = 2
 etc etc

I guess my question is:

Is there a way to store images in the local storage without first adding them to the page?

EDIT

This is now the code I'm using, however an image is not displayed, the div just displays the image location.

var counter = localStorage.getItem('counter');
  if(counter == null) {
    localStorage.setItem("counter", 0);
    localStorage.setItem("images",'["assets/advert1.png","assets/advert2.png","assets/advert3.png"]');
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[0]);
  }
  else {
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[counter]);
    counter++;
    if(counter > 2) {
      counter = 0;
    }

    localStorage.setItem("counter", counter);
  }

(Note this is inside a document.ready function)

Body:
All you have to do is use two variables, one to store an array of images and another to store the currently shown index.

$(document).ready(function(){
  var counter = localStorage.getItem('counter');
  if(counter == null)
  {
    localStorage.setItem("counter",0);
    localStorage.setItem("images",'["1.png","2.png","3.png"]');
    $('#displayArea').attr("src",JSON.parse(localStorage.getItem('images'))[0]);
  }
  else
  {
    $('#displayArea').attr("src",JSON.parse(localStorage.getItem('images'))[counter]);
    counter++;
    if(counter > 2)
    {
      counter = 0;
    }
    localStorage.setItem("counter",counter);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img id="displayArea"></img>

UPDATE

This code will produce an error in the stack snippet as it is a sandboxed environment. This snippet runs perfectly on a web page.


问:
Foundation 6 - Rows alignement in flex box
I'm trying to center two div Horizontally, and align one at the Middle of the parent container, and the second one at the Bottom of the parent container. I'm using Foundation 6, with the Flexbox version.

Html

```<code><section id="hero">
    <div class="row align-middle align-center">
        <h1>Welcome</h1>
    </div>
    <div class="row align-bottom align-center">
        <p>Some text</p>
    </div>
</section>
</code>```

Css

```<code>#hero {
    height: 100vh;
    display: flex;
    flex-wrap: wrap;
}
</code>```

The problem is that every div in the flex container (#hero) appear on the same line.

Thank's for helping !

答:
Pretty sure you have to add the class column to the sub element of row like so:

```<code>id="hero">
    <div class="row align-middle align-center">
        <h1 class="column">Welcome</h1>
    </div>
    <div class="row align-bottom align-center">
        <p class="column">Some text</p>
    </div>
</section>
</code>```

Body:
I'm trying to center two div Horizontally, and align one at the Middle of the parent container, and the second one at the Bottom of the parent container. I'm using Foundation 6, with the Flexbox version.

Html

Welcome

Some text

Css

#hero {
    height: 100vh;
    display: flex;
    flex-wrap: wrap;
}

The problem is that every div in the flex container (#hero) appear on the same line.

Thank's for helping !

Body:
Pretty sure you have to add the class column to the sub element of row like so:

id="hero">
    <div class="row align-middle align-center">
        <h1 class="column">Welcome</h1>
    </div>
    <div class="row align-bottom align-center">
        <p class="column">Some text</p>
    </div>
</section>


问:
how to skip blank line while reading CSV file using python
This is my code i am able to print each line but when blank line appears it prints ; because of CSV file format, so i want to skip when blank line appears</p>

```<code>import csv
import time

ifile = open ("C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv", "rb")
for line in csv.reader(ifile):
    if not line:
        empty_lines += 1
        continue
    print line
</code>```

答:
```<code>import csv

with open('userlist.csv') as f:

    reader = csv.reader(f)
    user_header = next(reader)       # Add this line if there the header is

    user_list = []                   # Create a  new user list for input
    for row in reader:
        if any(row):                 # Pick up the non-blank row of list
            print (row)              # Just for verification
            user_list.append(row)    # Compose all the rest data into the list
</code>```

Body:
This is my code i am able to print each line but when blank line appears it prints ; because of CSV file format, so i want to skip when blank line appears

import csv
import time

ifile = open ("C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv", "rb")
for line in csv.reader(ifile):
    if not line:
        empty_lines += 1
        continue
    print line


问:
END LOOP wrong expression PL/SQL
I'm having troubles working with a function in Oracle PL/SQL.

Here is the code:

```<code>create or replace FUNCTION FX_A (IVI NUMBER)
RETURN ListadoStrings
AS
  datos ListadoStrings;
  dato VARCHAR2(4000);
  idx NUMBER;
BEGIN
  datos := ListadoStrings();
    BEGIN
        FOR prog IN (
          SELECT TCPR.DES
          FROM TIVI TVIS
          JOIN TICPR TCPR ON (TCPR.PRO = TVIS.PRO AND TCPR.CAT = TVIS.CAT AND TCPR.TIP = TVIS.TIP)
          WHERE TVIS.IVI = IVI
        ) LOOP
            datos.extend;
            datos( datos.count ) := prog;
        END LOOP;
    END;

    BEGIN
        FOR tarea IN (
          SELECT TTAR.DES
          FROM TIVI TVIS
          JOIN TITAR TBTAR ON TBTAR.IVI = TVIS.IVI
          JOIN TMTAR TTAR ON TTAR.ITAR = TBTAR.ITAR
          WHERE TVIS.IVI = IVI
        ) LOOP
            datos.extend;
            datos( datos.count ) := tarea;
        END LOOP;
    END;

  return datos;
END FX_A;
</code>```

When I run this script, I get the response:

Function FX_DATOSVISITA compiled

Errors: check compiler log

And In the Compiler Log I see:

Error(17,13): PL/SQL: Statement ignored

Error(17,37): PLS-00382: expression is of wrong type

Error(30,13): PL/SQL: Statement ignored

Error(30,37): PLS-00382: expression is of wrong type

The lines affected are both "END LOOP;" lines.

Can you help me?
Thank you!

EDIT 1:

Ok, now I don't have any errors, but function returns NOTHING:

```<code>create or replace FUNCTION FX_A (IVI NUMBER)
RETURN ListadoStrings
AS
  datos ListadoStrings;
  dato VARCHAR2(4000);
  idx NUMBER;
BEGIN
  datos := ListadoStrings();
    BEGIN
        FOR prog IN (
          SELECT TCPR.DES as des
          FROM TIVI TVIS
          JOIN TICPR TCPR ON (TCPR.PRO = TVIS.PRO AND TCPR.CAT = TVIS.CAT AND TCPR.TIP = TVIS.TIP)
          WHERE TVIS.IVI = IVI
        ) LOOP
            DBMS_OUTPUT.PUT_LINE(prog.des );
            datos.extend;
            datos( datos.count ) := prog.des;
        END LOOP;
    END;

    BEGIN
        FOR tarea IN (
          SELECT TTAR.DES as des
          FROM TIVI TVIS
          JOIN TITAR TBTAR ON TBTAR.IVI = TVIS.IVI
          JOIN TMTAR TTAR ON TTAR.ITAR = TBTAR.ITAR
          WHERE TVIS.IVI = IVI
        ) LOOP
            DBMS_OUTPUT.PUT_LINE(tarea.des );
            datos.extend;
            datos( datos.count ) := tarea.des;
        END LOOP;
    END;

  return datos;
END FX_A;
</code>```

I can see the results of DBMS_OUTPUT.PUT_LINE(tarea.des ); in the Console, but the return of the function is only "ART_MOVIL.VISITA_DATOS("

Can you help?

答:
Alternative implementation. Replace the loops with bulk collect into local collects then squoosh them together. Set operations FTW!</p>

```<code>create or replace FUNCTION FX_A (IVI NUMBER)
RETURN ListadoStrings
AS
  datos1 ListadoStrings;
  datos2 ListadoStrings;
  datos ListadoStrings;
BEGIN
  datos := ListadoStrings();

  SELECT TCPR.DES
  bulk collect into datos1
  FROM TIVI TVIS
  JOIN TICPR TCPR ON (TCPR.PRO = TVIS.PRO AND TCPR.CAT = TVIS.CAT AND TCPR.TIP = TVIS.TIP)
  WHERE TVIS.IVI = IVI;

  SELECT TTAR.DES
  bulk collect into datos2
  FROM TIVI TVIS
  JOIN TITAR TBTAR ON TBTAR.IVI = TVIS.IVI
  JOIN TMTAR TTAR ON TTAR.ITAR = TBTAR.ITAR
  WHERE TVIS.IVI = IVI;

  datos := datos1 multiset union all datos2;

  return datos;
END FX_A;
</code>```

Title: END LOOP wrong expression PL/SQL

Body:
I'm having troubles working with a function in Oracle PL/SQL.

Here is the code:

create or replace FUNCTION FX_A (IVI NUMBER)
RETURN ListadoStrings
AS
  datos ListadoStrings;
  dato VARCHAR2(4000);
  idx NUMBER;
BEGIN
  datos := ListadoStrings();
    BEGIN
        FOR prog IN (
          SELECT TCPR.DES
          FROM TIVI TVIS
          JOIN TICPR TCPR ON (TCPR.PRO = TVIS.PRO AND TCPR.CAT = TVIS.CAT AND TCPR.TIP = TVIS.TIP)
          WHERE TVIS.IVI = IVI
        ) LOOP
            datos.extend;
            datos( datos.count ) := prog;
        END LOOP;
    END;

    BEGIN
        FOR tarea IN (
          SELECT TTAR.DES
          FROM TIVI TVIS
          JOIN TITAR TBTAR ON TBTAR.IVI = TVIS.IVI
          JOIN TMTAR TTAR ON TTAR.ITAR = TBTAR.ITAR
          WHERE TVIS.IVI = IVI
        ) LOOP
            datos.extend;
            datos( datos.count ) := tarea;
        END LOOP;
    END;

  return datos;
END FX_A;

When I run this script, I get the response:

Function FX_DATOSVISITA compiled

Errors: check compiler log

And In the Compiler Log I see:

Error(17,13): PL/SQL: Statement ignored

Error(17,37): PLS-00382: expression is of wrong type

Error(30,13): PL/SQL: Statement ignored

Error(30,37): PLS-00382: expression is of wrong type

The lines affected are both "END LOOP;" lines.

Can you help me?
Thank you!

EDIT 1:

Ok, now I don't have any errors, but function returns NOTHING:

create or replace FUNCTION FX_A (IVI NUMBER)
RETURN ListadoStrings
AS
  datos ListadoStrings;
  dato VARCHAR2(4000);
  idx NUMBER;
BEGIN
  datos := ListadoStrings();
    BEGIN
        FOR prog IN (
          SELECT TCPR.DES as des
          FROM TIVI TVIS
          JOIN TICPR TCPR ON (TCPR.PRO = TVIS.PRO AND TCPR.CAT = TVIS.CAT AND TCPR.TIP = TVIS.TIP)
          WHERE TVIS.IVI = IVI
        ) LOOP
            DBMS_OUTPUT.PUT_LINE(prog.des );
            datos.extend;
            datos( datos.count ) := prog.des;
        END LOOP;
    END;

    BEGIN
        FOR tarea IN (
          SELECT TTAR.DES as des
          FROM TIVI TVIS
          JOIN TITAR TBTAR ON TBTAR.IVI = TVIS.IVI
          JOIN TMTAR TTAR ON TTAR.ITAR = TBTAR.ITAR
          WHERE TVIS.IVI = IVI
        ) LOOP
            DBMS_OUTPUT.PUT_LINE(tarea.des );
            datos.extend;
            datos( datos.count ) := tarea.des;
        END LOOP;
    END;

  return datos;
END FX_A;

I can see the results of DBMS_OUTPUT.PUT_LINE(tarea.des ); in the Console, but the return of the function is only "ART_MOVIL.VISITA_DATOS("

Can you help?

Body:
Alternative implementation. Replace the loops with bulk collect into local collects then squoosh them together. Set operations FTW!

create or replace FUNCTION FX_A (IVI NUMBER)
RETURN ListadoStrings
AS
  datos1 ListadoStrings;
  datos2 ListadoStrings;
  datos ListadoStrings;
BEGIN
  datos := ListadoStrings();

  SELECT TCPR.DES
  bulk collect into datos1
  FROM TIVI TVIS
  JOIN TICPR TCPR ON (TCPR.PRO = TVIS.PRO AND TCPR.CAT = TVIS.CAT AND TCPR.TIP = TVIS.TIP)
  WHERE TVIS.IVI = IVI;

  SELECT TTAR.DES
  bulk collect into datos2
  FROM TIVI TVIS
  JOIN TITAR TBTAR ON TBTAR.IVI = TVIS.IVI
  JOIN TMTAR TTAR ON TTAR.ITAR = TBTAR.ITAR
  WHERE TVIS.IVI = IVI;

  datos := datos1 multiset union all datos2;

  return datos;
END FX_A;


问:
Not receiving the JSON object on onClick
I have very small UseCase. The user enters the ISBN of a book and is shown a book with that particular ISBN. However, only half of the functionality is working.

For some reason, I am not able to receive the JSON containing the book in the ejs so I can populate the table with only one book.

Here I am calling the search function and then i populate the table with the book

```<code>function searchISBN() {
        var input = $('#IdSearchISBN').val();
        $(document).ready(function () {
            $.get('/searchISBN/' + input, function (data, status) {
                var trJSON = '';
                $.each(data, function (i, item) {
                    trJSON += '<tbody><tr><td>' +
                        data[i].ISBN +
                        '</td><td>' +
                        data[i].BookTitle +
                        '</td><td>' +
                        data[i].BookAuthors +
                        '</td><td>'
                        + data[i].Publisher +
                        '</td><td>' +
                        data[i].Description +
                        '</td><td>' +
                        data[i].CallNumber +
                        '</td></tr></tbody>';
                });
                $('#booksTable').append(trJSON);
            });
        });
    }
</code>```

This is the function that does the searching and returns backs the book

```<code>app.get('/searchISBN/:searchID', function (req, res) {
    console.log(req.params.searchID);
    if (req.params.searchID != "" && req.params.searchID) {
        BookTable.find({ISBN: req.params.searchID}, function (err, booksList) {
            if (err) {
                res.status(500);
                return console.error(err);
            }
            console.log("I have sent data");
            console.log(booksList);
            res.send(booksList);
        });
    }
});
</code>```

I did put logs to see if the search function was really sending the book or not and yes it does. However, I am not able to receive it
Below are the logs I got.

9780730324218
I have sent data
[ { _id: 58c7d0694172ab199c6de78e,
    ISBN: '9780730324218',
    BookTitle: 'The Barefoot Investor : The Only Money Guide You\'ll Ever Need',
    BookAuthors: 'Scott Pape',
    Publisher: 'John Wiley & Sons Australia Ltd',
    Description: 'This is the only money guide you\'ll ever need That\'s a bold claim, given there are already thousands of finance books on the shelves.',
    CallNumber: ' 0730324214',
    __v: 0 } ]

Any suggestions?

答:
I think there's an issue with the frontend JS and the $(document).ready() being part of the function:

```<code>function searchISBN() {
    $.get('/searchISBN/' + $('#IdSearchISBN').val())
    .done(function(data){
        var trJSON = '';
        $.each(data, function (i, item) {
            trJSON += '<tbody><tr><td>';
            trJSON += [data[i].ISBN,data[i].BookTitle,data[i].BookAuthors,data[i].Publisher,data[i].Description,data[i].CallNumber].join('</td><td>');
            trJSON += '</td></tr></tbody>';
        });
        $('#booksTable').append(trJSON);
    })
    .fail(function(){
        console.log("Error");
    });
};
</code>```

That's returning "error" so the GET request is failing. I think, like the other answer, that the ObjectID is upsetting your browser. Update this in the app and it should work now:

```<code>app.get('/searchISBN/:searchID', function (req, res) {
    if (req.params.searchID != "" && req.params.searchID) {
        BookTable.find({ISBN: req.params.searchID}, function (err, booksList) {
            if (err) {
                res.status(500);
                return console.error(err);
            }
            var response = [];
            booksList.forEach(function(book) {
                var _book = book.toObject;
                delete _book._id;
                response.push(_book);
            })
            res.send(response);
        });
    }
});
</code>```

Body:
I have very small UseCase. The user enters the ISBN of a book and is shown a book with that particular ISBN. However, only half of the functionality is working.

For some reason, I am not able to receive the JSON containing the book in the ejs so I can populate the table with only one book.

Here I am calling the search function and then i populate the table with the book

function searchISBN() {
        var input = $('#IdSearchISBN').val();
        $(document).ready(function () {
            $.get('/searchISBN/' + input, function (data, status) {
                var trJSON = '';
                $.each(data, function (i, item) {
                    trJSON += '

' +
                        data[i].ISBN +
                        '	' +
                        data[i].BookTitle +
                        '	' +
                        data[i].BookAuthors +
                        '	'
                        + data[i].Publisher +
                        '	' +
                        data[i].Description +
                        '	' +
                        data[i].CallNumber +
                        '

';
                });
                $('#booksTable').append(trJSON);
            });
        });
    }

This is the function that does the searching and returns backs the book

app.get('/searchISBN/:searchID', function (req, res) {
    console.log(req.params.searchID);
    if (req.params.searchID != "" && req.params.searchID) {
        BookTable.find({ISBN: req.params.searchID}, function (err, booksList) {
            if (err) {
                res.status(500);
                return console.error(err);
            }
            console.log("I have sent data");
            console.log(booksList);
            res.send(booksList);
        });
    }
});

I did put logs to see if the search function was really sending the book or not and yes it does. However, I am not able to receive it
Below are the logs I got.

9780730324218
I have sent data
[ { _id: 58c7d0694172ab199c6de78e,
    ISBN: '9780730324218',
    BookTitle: 'The Barefoot Investor : The Only Money Guide You\'ll Ever Need',
    BookAuthors: 'Scott Pape',
    Publisher: 'John Wiley & Sons Australia Ltd',
    Description: 'This is the only money guide you\'ll ever need That\'s a bold claim, given there are already thousands of finance books on the shelves.',
    CallNumber: ' 0730324214',
    __v: 0 } ]

Any suggestions?

Body:
I think there's an issue with the frontend JS and the $(document).ready() being part of the function:

function searchISBN() {
    $.get('/searchISBN/' + $('#IdSearchISBN').val())
    .done(function(data){
        var trJSON = '';
        $.each(data, function (i, item) {
            trJSON += '<tbody><tr><td>';
            trJSON += [data[i].ISBN,data[i].BookTitle,data[i].BookAuthors,data[i].Publisher,data[i].Description,data[i].CallNumber].join('</td><td>');
            trJSON += '</td></tr></tbody>';
        });
        $('#booksTable').append(trJSON);
    })
    .fail(function(){
        console.log("Error");
    });
};

That's returning "error" so the GET request is failing. I think, like the other answer, that the ObjectID is upsetting your browser. Update this in the app and it should work now:

app.get('/searchISBN/:searchID', function (req, res) {
    if (req.params.searchID != "" && req.params.searchID) {
        BookTable.find({ISBN: req.params.searchID}, function (err, booksList) {
            if (err) {
                res.status(500);
                return console.error(err);
            }
            var response = [];
            booksList.forEach(function(book) {
                var _book = book.toObject;
                delete _book._id;
                response.push(_book);
            })
            res.send(response);
        });
    }
});


问:
Right align labels and float text to the left to make them appear on the same line in bootstrap

<form  class="form-horizontal" action="addtodatabase.php" class="form-inline" method="post" enctype="multipart/form-data" >

  <fieldset>
  <legend>
Security Department User Registration
</legend>

   First Name

   <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input">

   Second Name

   <input type="text" class="form-control input-sm"  name="secondname" placeholder="Text input">

   Dpt./Location

   <input type="text" class="form-control input-sm"  name="location"  placeholder="Text input">

```

In my form I get label  at the top and next line field .Since I have used row three of them are in the same row but I want label then followed by field .

Right now I am not able to get the field in horizontal line First Name,Second Name,Dpt./Location.

LABEL AT TOP AND FIELD AT THE BOTTOM

I HAVE LABEL OF DIFFERENT LENGTH I WANT IT TO BE ARRANGED PROPERLY.

what changes I need to do

In my form I want both label and text field to be horizontal label to be at right side and followed by  text field
  I have many other fields  but they don`t align properly because of  label being lengthy .

I want all the label both long and short to be aligned properly immediately followed by text field.

I  pic u can see label (name and DOB) is followed by text field   are in the  same line
  This is what I want to do

答:
Do you want something like this.

take a look at the example

label {

    clear:left;
    text-align:right;
    padding-right:10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form action="addtodatabase.php" class="form-inline" method="post" enctype="multipart/form-data" >
 <div class="container-fluid">

  <fieldset>
  <legend><h5>Security Department User Registration</h5></legend>

  <div class="row">
  <div class="col-xs-4 form-group">
   <label class="control-label" for="Firstname">First Name

   <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input"><br/></label>

  </div>

  <div class="col-xs-4 form-group">
   <label class="control-label" for="Secondname">Second Name

   <input type="text" class="form-control input-sm"  name="secondname" placeholder="Text input"><br/></label>
   </div>

  <div class="col-xs-4 form-group">
   <label class="control-label"for="location">Dpt./Location

   <input type="text" class="form-control input-sm"  name="location"  placeholder="Text input"></label>
   </div>
  </div></code>```

Body:
<form  class="form-horizontal" action="addtodatabase.php" class="form-inline" method="post" enctype="multipart/form-data" >

  <fieldset>
  <legend>
Security Department User Registration
</legend>

   First Name

   <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input">

   Second Name

   <input type="text" class="form-control input-sm"  name="secondname" placeholder="Text input">

   Dpt./Location

   <input type="text" class="form-control input-sm"  name="location"  placeholder="Text input">

In my form I get label  at the top and next line field .Since I have used row three of them are in the same row but I want label then followed by field .

Right now I am not able to get the field in horizontal line First Name,Second Name,Dpt./Location.

LABEL AT TOP AND FIELD AT THE BOTTOM

I HAVE LABEL OF DIFFERENT LENGTH I WANT IT TO BE ARRANGED PROPERLY.

what changes I need to do

In my form I want both label and text field to be horizontal label to be at right side and followed by  text field
  I have many other fields  but they don`t align properly because of  label being lengthy .

I want all the label both long and short to be aligned properly immediately followed by text field.

I  pic u can see label (name and DOB) is followed by text field   are in the  same line
  This is what I want to do

Body:
Do you want something like this.

take a look at the example

label {

    clear:left;
    text-align:right;
    padding-right:10px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form action="addtodatabase.php" class="form-inline" method="post" enctype="multipart/form-data" >
 <div class="container-fluid">

  <fieldset>
  <legend><h5>Security Department User Registration</h5></legend>

  <div class="row">
  <div class="col-xs-4 form-group">
   <label class="control-label" for="Firstname">First Name

   <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input"><br/></label>

  </div>

  <div class="col-xs-4 form-group">
   <label class="control-label" for="Secondname">Second Name

   <input type="text" class="form-control input-sm"  name="secondname" placeholder="Text input"><br/></label>
   </div>

  <div class="col-xs-4 form-group">
   <label class="control-label"for="location">Dpt./Location

   <input type="text" class="form-control input-sm"  name="location"  placeholder="Text input"></label>
   </div>
  </div>


问:
How to arrange the Radio Button and the Label in a single line?
enter image description here

i am facing this issue for my web pages that i  am working right now,
can anybody help me with this issue

答:
Label 1
  <input type="radio" name="foo" value="Fooo" />

Label 2
  <input type="radio" name="foo" value="Baar" />
```

Body:
<label>Label 1
  <input type="radio" name="foo" value="Fooo" />
</label>
<br>
<label>Label 2
  <input type="radio" name="foo" value="Baar" />
</label>


问:
identity.launchWebAuthFlow vs windows.create in chrome extension
I'm new to chrome extensions but I can't seem to understand what value the identity.launchWebAuthFlow adds over windows.create. I'm trying to use Oauth from an external provider. There doesn't appear to be any automatic persistence of an identity token as part of that flow. Also other browsers do not (yet?) support the identity.launchWebAuthFlow function. Both of which point to NOT using it vs a normal popup.

What am I overlooking?

答:
chrome.identity.launchWebAuthFlow launches your authentication page in a window until it comes back to https://<app-id>.chromiumapp.org/*, and then the callback fires.

chrome.windows.create launches any URL and then fires the callback with the window object.

There's one significant advantage to chrome.identity.launchWebAuthFlow, from the docs:

Since some auth flows may immediately redirect to a result URL, launchWebAuthFlow hides its web view until the first navigation either redirects to the final URL, or finishes loading a page meant to be displayed.

This means that you can seamlessly sign in (if your auth supports it)


问:
PHP Relative Date Issue
I have an issue with PHP relative dates, I have taken a look already at the aspect of relative dates vs. explicit dates.  This seems to present when the first day in the month (in this case Monday) is the relative date needed. e.g. May 2017 and Jan 2018

I would expect the following to provide me with 1st May 2017, however, I get 8th May 2017 instead.

```<code>$var = new DateTime();
var_dump($var->modify('First Monday May 2017'));

/** Output **/
object(DateTime)#1 (3) {
  ["date"]=>  string(26) "2017-05-08 00:00:00.000000"
  ["timezone_type"]=>  int(3)
  ["timezone"]=> string(3) "UTC"
}
</code>```

Thanks for your help.

答:
You need the of keyword.

```<code>$var = new DateTime();
var_dump($var->modify('first monday of May 2017'));
</code>```

From the PHP documentation for relative formats:

Also observe that the "of" in "ordinal space dayname space 'of' " and "'last' space dayname space 'of' " does something special.

   It sets the day-of-month to 1.
  "ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").

Title: PHP Relative Date Issue

Body:
I have an issue with PHP relative dates, I have taken a look already at the aspect of relative dates vs. explicit dates.  This seems to present when the first day in the month (in this case Monday) is the relative date needed. e.g. May 2017 and Jan 2018

I would expect the following to provide me with 1st May 2017, however, I get 8th May 2017 instead.

$var = new DateTime();
var_dump($var->modify('First Monday May 2017'));

/** Output **/
object(DateTime)#1 (3) {
  ["date"]=>  string(26) "2017-05-08 00:00:00.000000"
  ["timezone_type"]=>  int(3)
  ["timezone"]=> string(3) "UTC"
}

Thanks for your help.

Body:
You need the of keyword.

$var = new DateTime();
var_dump($var->modify('first monday of May 2017'));

From the PHP documentation for relative formats:

Also observe that the "of" in "ordinal space dayname space 'of' " and "'last' space dayname space 'of' " does something special.

   It sets the day-of-month to 1.
  "ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").


问:
Command Line Arguments and Chars
What is the proper way to receive a command line argument from the user and compare it to a single char? For example if the user typed "Y" for yes run some function and "N" for no would run another function.

My main error is "comparison between ptr and integer" & "too few arguments to function call, expected 3 have 1"

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void calculate();
void verify();

int main (int argc, char *argv[]) {
   if(argc < 2){
        printf("Please enter a mode of operation.\n");
        return 0;
    }
    else if(argc > 2){
        printf("Too many arguments supplied. Please try again.\n");
        return 0;
    }
    else if(strncmp(argv[1] == 'c') == 0)
        calculate();

    else if(strncmp(argv[1] == 'v') == 0)
        verify();

return 0;
}

void calculate(){
}

void verify(){
}
</code>```

答:
You're not calling strncmp() correctly. It should be:

```<code>strncmp(argv[1], "c", 1)
</code>```

It takes 3 arguments: two strings and a limit. 'c' is a char, not a string, string literals are put in double quotes.

You can also write simply:

```<code>if (argv[1][0] == 'c')
</code>```

This just checks the first character, so the user can type y or yes and they'll match y. If you want to match the whole argument and require it be just a single character, you should use strcmp() rather than strncmp():

```<code>if (strcmp(argv[1], "c") == 0)
</code>```

Title: Command Line Arguments and Chars

Body:
What is the proper way to receive a command line argument from the user and compare it to a single char? For example if the user typed "Y" for yes run some function and "N" for no would run another function.

My main error is "comparison between ptr and integer" & "too few arguments to function call, expected 3 have 1"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void calculate();
void verify();

int main (int argc, char *argv[]) {
   if(argc < 2){
        printf("Please enter a mode of operation.\n");
        return 0;
    }
    else if(argc > 2){
        printf("Too many arguments supplied. Please try again.\n");
        return 0;
    }
    else if(strncmp(argv[1] == 'c') == 0)
        calculate();

    else if(strncmp(argv[1] == 'v') == 0)
        verify();

return 0;
}

void calculate(){
}

void verify(){
}

Body:
You're not calling strncmp() correctly. It should be:

strncmp(argv[1], "c", 1)

It takes 3 arguments: two strings and a limit. 'c' is a char, not a string, string literals are put in double quotes.

You can also write simply:

if (argv[1][0] == 'c')

This just checks the first character, so the user can type y or yes and they'll match y. If you want to match the whole argument and require it be just a single character, you should use strcmp() rather than strncmp():

if (strcmp(argv[1], "c") == 0)


问:
How can I bind a specific nested list value in a ListView
I have a json that I have deserialized.  I have a listview that is bound to the rootobject class.

```<code>public class Thumbnails
{
    public string mini { get; set; }
    public string webimage { get; set; }

}

public class RootObject
{
    public string userCreated { get; set; }
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public List<string> property_product { get; set; }
    public Thumbnails thumbnails { get; set; }
}
</code>```

I have bound my list to a listview

```<code>private void BindListView()
{
    lstView.DataSource = myList;
    lstView.DataBind();
}
</code>```

But I need to display only the webimage value from Thumbnails.  I'm at a loss on how to do that.  It displays the others just fine until I try to add the webimage.

```<code><ItemTemplate>
    <td>
        <%# Eval("webimage") %>
    </td>
    <td>
        <%# Eval("id") %>
    </td>
    <td>
        <%# Eval("name") %>
    </td>
    <td>
        <%# Eval("property_product") %>
    </td>
</ItemTemplate>
</code>```

答:
You provide the path of the nested class. Checking for null is not needed, as long as you are not going to use .ToString() etc.

```<code><%# Eval("thumbnails.webimage") %>
</code>```

Body:
I have a json that I have deserialized.  I have a listview that is bound to the rootobject class.

public class Thumbnails
{
    public string mini { get; set; }
    public string webimage { get; set; }

}

public class RootObject
{
    public string userCreated { get; set; }
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public List<string> property_product { get; set; }
    public Thumbnails thumbnails { get; set; }
}

I have bound my list to a listview

private void BindListView()
{
    lstView.DataSource = myList;
    lstView.DataBind();
}

But I need to display only the webimage value from Thumbnails.  I'm at a loss on how to do that.  It displays the others just fine until I try to add the webimage.

<ItemTemplate>

        <%# Eval("webimage") %>

        <%# Eval("id") %>

        <%# Eval("name") %>

        <%# Eval("property_product") %>

</ItemTemplate>

Body:
You provide the path of the nested class. Checking for null is not needed, as long as you are not going to use .ToString() etc.

<%# Eval("thumbnails.webimage") %>


答:
You can use localStorage or WebSQL to deal with this problem

Add image as a Base64 then use counter 1,2,3 to choose which image to use

but this will be using JavaScript so it will be loaded in Client-Side

To convert image Base64 you can use this website

You can check this question

Title: How display a new image in a div, saved in local storage, each time the user re-visits the page?

Body:
Hard to explain in the title, let me explain.

I have 3 images and I would like them to be displayed in a div and rotate everytime a user re-visits the page (They will see one image when they visit, and a different image the next time).

I was thinking of having a variable like 'count' which increments each time the user visits, and the value of count would relate to which image is displayed in this div, however I'm not sure how to save the 3 images in the local storage.

I'm expecting the logic wpould be like

setItem (Img1)
setItem (Img2)
setItem (Img3)

count = count + 1

if count = 1
    div = getItem(Img1)
if count = 2
 etc etc

I guess my question is:

Is there a way to store images in the local storage without first adding them to the page?

EDIT

This is now the code I'm using, however an image is not displayed, the div just displays the image location.

var counter = localStorage.getItem('counter');
  if(counter == null) {
    localStorage.setItem("counter", 0);
    localStorage.setItem("images",'["assets/advert1.png","assets/advert2.png","assets/advert3.png"]');
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[0]);
  }
  else {
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[counter]);
    counter++;
    if(counter > 2) {
      counter = 0;
    }

    localStorage.setItem("counter", counter);
  }

(Note this is inside a document.ready function)


答:
Just use vertical-align: top; for this

```<code>p {
    border-bottom: 6px solid red;
    background-color: lightgrey;
    padding: 10px;
    max-width: 100px;
    display: inline-block;
    margin-right: 10px;
    max-height: 250px;
    font-family: "Arial";
    vertical-align: top;
}
</code>```

for updated fiddle demo click here

Title: How can I move the p tag's position up instead of it being at the bottom?

Body:
This is the JSFiddle example. I want to move the p tag so that it is displayed inline at the top, not at the bottom.

<!DOCTYPE html>

This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.

This property is a shorthand property for border-bottom-width, border-bottom-style, and border-bottom-color.

This property is a shorthand property for border-bottom-width.

https://jsfiddle.net/om7orw9w/

Body:
Just use vertical-align: top; for this

p {
    border-bottom: 6px solid red;
    background-color: lightgrey;
    padding: 10px;
    max-width: 100px;
    display: inline-block;
    margin-right: 10px;
    max-height: 250px;
    font-family: "Arial";
    vertical-align: top;
}

for updated fiddle demo click here


问:
Is it better to replace an image src with JS, or to use CSS filters to manipulate it?
I have a button with an icon, whose source is an SVG of ~4kb. When I hover over the button, I want the icon to invert in color, changing from black to white. To achieve this effect, is it better to use CSS like so: </p>

```<code>#btn:hover #icon-img {
    -webkit-filter: invert(1);
    filter: invert(1);
}
</code>```

<p>...or is it better (e.g. faster/best practice/better for memory) to manipulate the image source directly and add a white version of the icon like so?</p>

```<code>document.getElementById('btn').addEventListener('mouseover', (e) => {
    document.getElementById('icon-img').src = 'white-image.svg';
}
</code>```

答: Use css to not make additional network request for image at each mouseover event.

Body:
I have a button with an icon, whose source is an SVG of ~4kb. When I hover over the button, I want the icon to invert in color, changing from black to white. To achieve this effect, is it better to use CSS like so:

#btn:hover #icon-img {
    -webkit-filter: invert(1);
    filter: invert(1);
}

...or is it better (e.g. faster/best practice/better for memory) to manipulate the image source directly and add a white version of the icon like so?

document.getElementById('btn').addEventListener('mouseover', (e) => {
    document.getElementById('icon-img').src = 'white-image.svg';
}


问:
Can I write files with HTML5/JS?
I wonder if there is any way I can write to files from HTML5/JS? In the broswer ...</p>

答:
Yes, using the new FileWriter API.

http://www.w3.org/TR/file-writer-api/

You can see the current browser support here: http://caniuse.com/#feat=filesystem

Title: Can I write files with HTML5/JS?


问:
Spring Data Key Value Implementation for Oracle KV
I would like to use Oracle NoSQL database together with Spring data. The aim is to access the data over spring data repositories and even use spring data rest on top of it.
So I think the spring-data-keyvalue project would help me, to implement an adapter for Oracle NoSQL KV.

I tried to understand the documentation of spring-data-keyvalue (http://docs.spring.io/spring-data/keyvalue/docs/current/reference/html/#key-value.core-concepts), but didn't get the idea.
An example/tutorial about how to implement an adapter from scratch would be very helpful.

What I have is this configuration class where I provide a custom KeyValueAdapter. Now if I use CrudRepository methods it uses my custom adapter.

```<code>@Configuration
@EnableMapRepositories
public class KeyValueConfig {

     @Bean
     public KeyValueOperations keyValueTemplate() {
         return new KeyValueTemplate(new OracleKeyValueAdapter());
    }
}
</code>```

The OracleKeyValueAdapter is an implementation of KeyValueAdapter. I got this from the spring-data-keyvalue-redis project (https://github.com/christophstrobl/spring-data-keyvalue-redis/blob/master/src/main/java/org/springframework/data/keyvalue/redis/RedisKeyValueAdapter.java)

```<code>public class OracleKeyValueAdapter extends AbstractKeyValueAdapter {

private KVStore store;

public OracleKeyValueAdapter() {
    String storeName = "kvstore";
    String hostName = "localhost";
    String hostPort = "5000";

    store = KVStoreFactory.getStore
            (new KVStoreConfig(storeName, hostName + ":" + hostPort));
}

//Custom implementations:

@Override
public Object put(Serializable serializable, Object o, Serializable
serializable1) {
    return null;
}

@Override
public boolean contains(Serializable serializable, Serializable
serializable1) {
    return false;
}

.
.
.
</code>```

Now I'm trying to implement this OracleKeyValueAdapter, but i don't know if that does even make sense.

Can you help me?

答:
You might want to start with how spring-data-keyvalue is implemented over Redis, the link here should be a good starting point - http://docs.spring.io/spring-data/data-keyvalue/docs/1.0.0.BUILD-SNAPSHOT/reference/redis.html

Let me know how that goes, I am interested in what you are trying to accomplish.

Body:
I would like to use Oracle NoSQL database together with Spring data. The aim is to access the data over spring data repositories and even use spring data rest on top of it.
So I think the spring-data-keyvalue project would help me, to implement an adapter for Oracle NoSQL KV.

I tried to understand the documentation of spring-data-keyvalue (http://docs.spring.io/spring-data/keyvalue/docs/current/reference/html/#key-value.core-concepts), but didn't get the idea.
An example/tutorial about how to implement an adapter from scratch would be very helpful.

What I have is this configuration class where I provide a custom KeyValueAdapter. Now if I use CrudRepository methods it uses my custom adapter.

@Configuration
@EnableMapRepositories
public class KeyValueConfig {

     @Bean
     public KeyValueOperations keyValueTemplate() {
         return new KeyValueTemplate(new OracleKeyValueAdapter());
    }
}

The OracleKeyValueAdapter is an implementation of KeyValueAdapter. I got this from the spring-data-keyvalue-redis project (https://github.com/christophstrobl/spring-data-keyvalue-redis/blob/master/src/main/java/org/springframework/data/keyvalue/redis/RedisKeyValueAdapter.java)

public class OracleKeyValueAdapter extends AbstractKeyValueAdapter {

private KVStore store;

public OracleKeyValueAdapter() {
    String storeName = "kvstore";
    String hostName = "localhost";
    String hostPort = "5000";

    store = KVStoreFactory.getStore
            (new KVStoreConfig(storeName, hostName + ":" + hostPort));
}

//Custom implementations:

@Override
public Object put(Serializable serializable, Object o, Serializable
serializable1) {
    return null;
}

@Override
public boolean contains(Serializable serializable, Serializable
serializable1) {
    return false;
}

.
.
.

Now I'm trying to implement this OracleKeyValueAdapter, but i don't know if that does even make sense.

Can you help me?


问:
How to deploy angular2 on tomcat?
First I'd like to describe my set up:

I have a web service, let's call it "Cars", written in Java, that I've tested in eclipse with tomcat v6, working local (it was a requirement, so that once it works locally I can switch to do it with a "real" tomcat server so others can access). It works, it access the database, it offers an answer for certain URIs and so on.

I have coded in Plunker an angular 2 application, "WebCar", and I now want to run that on my computer, with a Tomcat server (unless there is a better way of doing it, I've been told to do it with Tomcat. Since I do not know any better option, that's why I talk about tomcat all of the time). With eclipse, I have already managed to get the app running, using palantir plugin for typescript https://marketplace.eclipse.org/content/typescript , and then running the project with a server-launch.js which contains require('lite-server'); , this allows me to see the same I saw on plunker, so, it works, but before I upload anything to the business servers I wanted to check everything works (hence the set up, which may not be necessary but it's what I come up with).

I now want to go one step further and use, if possible, tomcat v6 to run my angular 2 app, instead of simply using that lite server, so that I can test that it works, and then uploading it to a "real", remote server.

I would like to know what options are there, what would be a better option, and anything that is required to make an angular 2 deployment properly. So far I've found this

https://stackoverflow.com/a/34408495/6028947 " You only have to deploy
.js files, since anyway browser won;t" which I don't fully get,

http://jspm.io/ which is for SystemJS (I have an older version of
Angular 2 and use config.js)

https://stackoverflow.com/a/37568235/6028947 which talks about
angular-cli or webpack, which makes a bundle but if I got that
running, I still don't know what to do with it to upload to Tomcat
and then connect it to my web service.

So maybe the question should be (I don't know for sure): Once you get your angular 2 code bundled, what's next?

Btw there are a few other questions on stackOverflow, similar to this, but as far as I've seen, without any answer at all or with answers only obliquely related to this (and of course, nothing resembling a guide or step by step required)

答:
Thanks to @nuzz for this ..

I'm running a little script to build the project and then copy it to tomcat. I'm telling angular what the base directory is that it will run under in tomcat.

```<code>#!/bin/sh
ng build --base-href /angular/ --prod
mkdir -p /home/xxx/apache-tomcat-8.0.37/webapps/angular
cp -R /home/xxx/angular-clitest/dist/* /home/xxx/apache-tomcat-8.0.37/webapps/angular/
</code>```

Once thats run, start tomcat and you can access it at: http://localhost:8080/angular

Title: How to deploy angular2 on tomcat?

Body:
Thanks to @nuzz for this ..

I'm running a little script to build the project and then copy it to tomcat. I'm telling angular what the base directory is that it will run under in tomcat.

#!/bin/sh
ng build --base-href /angular/ --prod
mkdir -p /home/xxx/apache-tomcat-8.0.37/webapps/angular
cp -R /home/xxx/angular-clitest/dist/* /home/xxx/apache-tomcat-8.0.37/webapps/angular/

Once thats run, start tomcat and you can access it at: http://localhost:8080/angular


问:
Object-oriented programming (python)
```<code>class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity
    def get_quantity(self):
        return self.quantity
    def weapon_type(self):
        return self.weapon
    def remove_all():
        self.quantity=0

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())
</code>```

output of print(arrows.weapon_type()) is supposed to be bow but I got <__main__.Weapon object at 0x10441f0b8> instead. How can I modify my code so that it returns bow?

Below is class Weapon:

```<code>import random
class Weapon(Thing):
    def __init__(self, name, min_dmg, max_dmg):
        self.name=name
        self.min_dmg=min_dmg
        self.max_dmg=max_dmg
    def min_damage(self):
        return self.min_dmg
    def max_damage(self):
        return self.max_dmg
    def damage(self):
        return random.randint(self.min_dmg,self.max_dmg)
</code>```

答:
Add repr to Weapon class:

```<code>def __repr__(self):
    return self.name
</code>```

object.__repr__(self)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines repr() but not str(), then repr() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

object.__str__(self)

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

Reference

Title: Object-oriented programming (python)

Body:
class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity
    def get_quantity(self):
        return self.quantity
    def weapon_type(self):
        return self.weapon
    def remove_all():
        self.quantity=0

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())

output of print(arrows.weapon_type()) is supposed to be bow but I got <__main__.Weapon object at 0x10441f0b8> instead. How can I modify my code so that it returns bow?

Below is class Weapon:

import random
class Weapon(Thing):
    def __init__(self, name, min_dmg, max_dmg):
        self.name=name
        self.min_dmg=min_dmg
        self.max_dmg=max_dmg
    def min_damage(self):
        return self.min_dmg
    def max_damage(self):
        return self.max_dmg
    def damage(self):
        return random.randint(self.min_dmg,self.max_dmg)

Body:
Add repr to Weapon class:

def __repr__(self):
    return self.name

object.__repr__(self)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines repr() but not str(), then repr() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

object.__str__(self)

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

Reference


答:
Use random:</p>

```<code>Math.floor((Math.random() * 3) + 1);
</code>```

Body:
Use random:

Math.floor((Math.random() * 3) + 1);


问:
Plot cylinder along curved axis
I need a little help in the code to plot the cylinder along the given axis. Can you please let me know how to implement this in Matlab.The cylinder should be along the axis.

Let me know incase if you have further questions

%Code for axis

```<code>s=10;
vec=0.6;
i=0; x=0; y=0; z=0; x1=0; y1=0; z1=0;
for i=1:s
     x(i)=0;
     z(i)=i;
     y(i)=0;

end
angle=60;
j=0;
for j=1:s
if j<vec*s
     x1(j)=0;
     z1(j)=j;
     y1(j)=0;
end
end
plot3(x1,y1,z1); xlabel('X axis'); ylabel('Y axis'); zlabel('Z axis');
</code>```

%code for the cylinder

```<code>t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(2+cos(t));
surf(X,Y,Z)
axis square
</code>```

答:
you can download the awesome Tubeplot library and then you easily plot a curved tube like that:

```<code>t=0:0.01:pi;
x=cos(t);
y=sin(t);
z=3*t;
r = sqrt(t)/2;
[X,Y,Z] = tubeplot(x,y,z,r,1,10);
surf(X,Y,Z,'EdgeColor','none')
</code>```

and you'll get:

Title: Plot cylinder along curved axis

Body:
I need a little help in the code to plot the cylinder along the given axis. Can you please let me know how to implement this in Matlab.The cylinder should be along the axis.

Let me know incase if you have further questions

%Code for axis

s=10;
vec=0.6;
i=0; x=0; y=0; z=0; x1=0; y1=0; z1=0;
for i=1:s
     x(i)=0;
     z(i)=i;
     y(i)=0;

end
angle=60;
j=0;
for j=1:s
if j<vec*s
     x1(j)=0;
     z1(j)=j;
     y1(j)=0;
end
end
plot3(x1,y1,z1); xlabel('X axis'); ylabel('Y axis'); zlabel('Z axis');

%code for the cylinder

t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(2+cos(t));
surf(X,Y,Z)
axis square

Body:
you can download the awesome Tubeplot library and then you easily plot a curved tube like that:

t=0:0.01:pi;
x=cos(t);
y=sin(t);
z=3*t;
r = sqrt(t)/2;
[X,Y,Z] = tubeplot(x,y,z,r,1,10);
surf(X,Y,Z,'EdgeColor','none')

and you'll get:


问:
Android loop problem
I am new to android but not to programming. And the code below makes the icon.png that is available by default in android, go across the screen or at least it is supposed to. This doesn't work. Can anyone help?</p>

```<code>> package com.android.test; import
> android.app.Activity; import
> android.content.Context; import
> android.graphics.Bitmap; import
> android.graphics.BitmapFactory; import
> android.graphics.Canvas; import
> android.graphics.Color; import
> android.os.Bundle;
>
>
> import android.view.View; import
> android.view.Window;
>
> public class Android extends Activity
> { int x,y=10;
>
> @Override public void onCreate(Bundle
> savedInstanceState) {
> super.onCreate(savedInstanceState);
> requestWindowFeature(Window.FEATURE_NO_TITLE);
> setContentView(new Panel(this)); }
>
> class Panel extends View { public
> Panel(Context context) {
> super(context); }
>
> @Override public void onDraw(Canvas
> canvas) { Bitmap _scratch =
> BitmapFactory.decodeResource(getResources(),
> R.drawable.icon);
> canvas.drawColor(Color.BLACK); int
> n=1;  while (n==1){ try {
> Thread.sleep(30);  } catch
> (InterruptedException e) { }
> canvas.drawBitmap(_scratch, x, y,
> null);  x+=2; y+=2;
>
> canvas.drawBitmap(_scratch, x, y,
> null);  } } } }
</code>```

答: I'm amateur Android Dev too, and I think I recall reading that its a bad habit to call Thread.Sleep() as a workaround.  But I could be wrong.</p>

Title: Android loop problem

Body:
I am new to android but not to programming. And the code below makes the icon.png that is available by default in android, go across the screen or at least it is supposed to. This doesn't work. Can anyone help?

> package com.android.test; import
> android.app.Activity; import
> android.content.Context; import
> android.graphics.Bitmap; import
> android.graphics.BitmapFactory; import
> android.graphics.Canvas; import
> android.graphics.Color; import
> android.os.Bundle;
>
>
> import android.view.View; import
> android.view.Window;
>
> public class Android extends Activity
> { int x,y=10;
>
> @Override public void onCreate(Bundle
> savedInstanceState) {
> super.onCreate(savedInstanceState);
> requestWindowFeature(Window.FEATURE_NO_TITLE);
> setContentView(new Panel(this)); }
>
> class Panel extends View { public
> Panel(Context context) {
> super(context); }
>
> @Override public void onDraw(Canvas
> canvas) { Bitmap _scratch =
> BitmapFactory.decodeResource(getResources(),
> R.drawable.icon);
> canvas.drawColor(Color.BLACK); int
> n=1;  while (n==1){ try {
> Thread.sleep(30);  } catch
> (InterruptedException e) { }
> canvas.drawBitmap(_scratch, x, y,
> null);  x+=2; y+=2;
>
> canvas.drawBitmap(_scratch, x, y,
> null);  } } } }


问:
Creating a series of pie charts from a dataframe with color linked to indexes's values
This is an example dataframe:

```<code>import pandas as pd
import numpy as np

values = np.array([
        [0, 1, 2, 0, 0, 4],
        [1, 0, 0, 1, 1, 0 ],
        [0, 4, 0, 0, 2, 1],
        [2, 0, 2, 0, 4, 0],
        ])

indexes= 'a','b','c','d'

columns='ab','bc','cd','de','ef','fg'

df = pd.DataFrame(index=indexes,columns=columns, data=values)

print(df)
</code>```

from this dataframe I need to create a series of pie charts, one for every column, shown on the same figure, where the slices dimension is fixed (equal to 100/len(indexes)) and the color of the slices depends on the value of the index, in particular: white if 0, green if 1, yellow if 2, red if 4.

What suggestions can you give me?

I found that:

```<code>df.plot(kind='pie', subplots=True, figsize=(len(columns)*2, 2))
</code>```

it creates a series, but I can't control the input values...

I've created a pie for a column, but then I wasn't able to link the color to the value of index:

```<code>labels = indexes
sizes = np.linspace(100/len(labels),100/len(labels), num=len(labels))

fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=labels)
ax1.axis('equal')

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

ImportanceOfBeingErnest answer has helped me giving to the piechart the wanted look:

```<code>fig1, ax1 = plt.subplots()

labels = indexes
sizes = np.linspace(100/len(labels),100/len(labels), num=len(labels))
coldic = {0 : "w", 1 : "g", 2 : "y", 4 : "r" }
colors = [coldic[v] for v in values[:,0]]

ax1.pie(sizes, labels=labels, colors=colors,counterclock=False, startangle=90)
ax1.axis('equal')

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

Now the colors a linked to the values, and the dimensions of the slices are fixed. I just need to have the same pie chart for all the columns and in the same image.

The importance of these charts is given by the colors, not the dimensions of the slices, which I want to be always equal.

Thanks for your time!

答:
Not relying on pandas internal plotting functions (which are of course limited) one can use matplotlib' pie function to plot the diagrams.

The colors can be set as a list, which is generated from the values according to some mapping dictionary.

```<code>import numpy as np
import matplotlib.pyplot as plt
coldic = {0 : "w", 1 : "g", 2 : "y", 4 : "r" }
values = np.array([
        [0, 1, 2, 0, 0, 4],
        [1, 0, 0, 1, 1, 0 ],
        [0, 4, 0, 0, 2, 1],
        [2, 0, 2, 0, 4, 0],
        ])

labels= ['a','b','c','d']

fig1, axes = plt.subplots(ncols=values.shape[1], )

for i in range(values.shape[1]):
    colors = [coldic[v] for v in values[:,i]]
    labs = [l if values[j,i] > 0 else "" for j, l in enumerate(labels)]
    axes[i].pie(values[:,i], labels=labs, colors=colors)
    axes[i].set_aspect("equal")

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

For fixed wedge sizes you just use a fixed array to supply to pie.

```<code>import numpy as np
import matplotlib.pyplot as plt
coldic = {0 : "w", 1 : "g", 2 : "y", 4 : "r" }
values = np.array([
        [0, 1, 2, 0, 0, 4],
        [1, 0, 0, 1, 1, 0 ],
        [0, 4, 0, 0, 2, 1],
        [2, 0, 2, 0, 4, 0],
        ])

labels= ['a','b','c','d']

fig1, axes = plt.subplots(ncols=values.shape[1], )

for i in range(values.shape[1]):
    colors = [coldic[v] for v in values[:,i]]
    axes[i].pie(np.ones(values.shape[0]), labels=labels, colors=colors,
            wedgeprops=dict(linewidth=1, edgecolor="k"))
    axes[i].set_aspect("equal")
    axes[i].set_title("".join(list(map(str,values[:,i]))))

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

Body:
This is an example dataframe:

import pandas as pd
import numpy as np

values = np.array([
        [0, 1, 2, 0, 0, 4],
        [1, 0, 0, 1, 1, 0 ],
        [0, 4, 0, 0, 2, 1],
        [2, 0, 2, 0, 4, 0],
        ])

indexes= 'a','b','c','d'

columns='ab','bc','cd','de','ef','fg'

df = pd.DataFrame(index=indexes,columns=columns, data=values)

print(df)

from this dataframe I need to create a series of pie charts, one for every column, shown on the same figure, where the slices dimension is fixed (equal to 100/len(indexes)) and the color of the slices depends on the value of the index, in particular: white if 0, green if 1, yellow if 2, red if 4.

What suggestions can you give me?

I found that:

df.plot(kind='pie', subplots=True, figsize=(len(columns)*2, 2))

it creates a series, but I can't control the input values...

I've created a pie for a column, but then I wasn't able to link the color to the value of index:

labels = indexes
sizes = np.linspace(100/len(labels),100/len(labels), num=len(labels))

fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=labels)
ax1.axis('equal')

plt.show()

ImportanceOfBeingErnest answer has helped me giving to the piechart the wanted look:

fig1, ax1 = plt.subplots()

labels = indexes
sizes = np.linspace(100/len(labels),100/len(labels), num=len(labels))
coldic = {0 : "w", 1 : "g", 2 : "y", 4 : "r" }
colors = [coldic[v] for v in values[:,0]]

ax1.pie(sizes, labels=labels, colors=colors,counterclock=False, startangle=90)
ax1.axis('equal')

plt.show()

Now the colors a linked to the values, and the dimensions of the slices are fixed. I just need to have the same pie chart for all the columns and in the same image.

The importance of these charts is given by the colors, not the dimensions of the slices, which I want to be always equal.

Thanks for your time!

Body:
Not relying on pandas internal plotting functions (which are of course limited) one can use matplotlib' pie function to plot the diagrams.

The colors can be set as a list, which is generated from the values according to some mapping dictionary.

import numpy as np
import matplotlib.pyplot as plt
coldic = {0 : "w", 1 : "g", 2 : "y", 4 : "r" }
values = np.array([
        [0, 1, 2, 0, 0, 4],
        [1, 0, 0, 1, 1, 0 ],
        [0, 4, 0, 0, 2, 1],
        [2, 0, 2, 0, 4, 0],
        ])

labels= ['a','b','c','d']

fig1, axes = plt.subplots(ncols=values.shape[1], )

for i in range(values.shape[1]):
    colors = [coldic[v] for v in values[:,i]]
    labs = [l if values[j,i] > 0 else "" for j, l in enumerate(labels)]
    axes[i].pie(values[:,i], labels=labs, colors=colors)
    axes[i].set_aspect("equal")

plt.show()

For fixed wedge sizes you just use a fixed array to supply to pie.

import numpy as np
import matplotlib.pyplot as plt
coldic = {0 : "w", 1 : "g", 2 : "y", 4 : "r" }
values = np.array([
        [0, 1, 2, 0, 0, 4],
        [1, 0, 0, 1, 1, 0 ],
        [0, 4, 0, 0, 2, 1],
        [2, 0, 2, 0, 4, 0],
        ])

labels= ['a','b','c','d']

fig1, axes = plt.subplots(ncols=values.shape[1], )

for i in range(values.shape[1]):
    colors = [coldic[v] for v in values[:,i]]
    axes[i].pie(np.ones(values.shape[0]), labels=labels, colors=colors,
            wedgeprops=dict(linewidth=1, edgecolor="k"))
    axes[i].set_aspect("equal")
    axes[i].set_title("".join(list(map(str,values[:,i]))))

plt.show()


问:
control array in xcode
I am quite new to Xcode and still do not know a lot of things Xcode can do. I wanna ask if Xcode or Objective-C uses Control Arrays like VB6.

edit: posted question on seperate page.
How to detect which label or image is selected when they are created dynamically

答: No, Xcode and Obj-C have nothing like control arrays, even though it would be pretty easy to replicate that behavior if you needed to. If you have a specific task you'd like to accomplish, post a question and we may be able to give you a more specific answer.</p>

Title: control array in xcode


问:
JavaScript Error - Uncaught SyntaxError: Unexpected token {
I am trying to use Chart JS in one of my laravel applications.

I am pushing the data through the route and using json_encode($gross) to echo the gross of each order by day but I am getting the following error in my console log:

Uncaught SyntaxError: Unexpected token {

It references the the line of where I have used json_encode($gross). Anyone have any ideas why this is happening?

```<code>Here is the code coming through the controller:

public function index()
{   $wkRevenue = \App\Order::where('created_at', '>=' , \Carbon\Carbon::now()->startOfMonth())->get();
    // dd($wkRevenue->pluck('created_at','gross'));

    return view('admin.dashboard')
            ->with('created_at', $wkRevenue->pluck('created_at'))
            ->with('grosss', $wkRevenue->pluck('gross'));
}

Here is the code in the js file:

var data = {
    type:'line',
    labels:['Mon','Tues','Wed','Thurs','Fri','Sat','Sun'],
    datasets:[
    {
        data: {!! json_encode($gross) !!},
        backgroundColor:'rgba(137, 200, 85, 0.4)',
    }
]
}
var graph = document.getElementById('myNewChart').getContext('2d');
var myNewChart = new Chart(graph ,{
type: "line",
data: data,
options:{
    title:{
        display:true,
    }
}
});
</code>```

答:
You have a typo in your controller:

```<code>->with('grosss', $wkRevenue->pluck('gross'));
</code>```

needs to be:

```<code>->with('gross', $wkRevenue->pluck('gross'));
</code>```

Laravel changed the pluck() method in 5.2 to return a collection instead of an array.

In your view change your json_encode() to:

```<code>{!! $gross->toJson() !!}
</code>```

Body:
I am trying to use Chart JS in one of my laravel applications.

I am pushing the data through the route and using json_encode($gross) to echo the gross of each order by day but I am getting the following error in my console log:

Uncaught SyntaxError: Unexpected token {

It references the the line of where I have used json_encode($gross). Anyone have any ideas why this is happening?

Here is the code coming through the controller:

public function index()
{   $wkRevenue = \App\Order::where('created_at', '>=' , \Carbon\Carbon::now()->startOfMonth())->get();
    // dd($wkRevenue->pluck('created_at','gross'));

    return view('admin.dashboard')
            ->with('created_at', $wkRevenue->pluck('created_at'))
            ->with('grosss', $wkRevenue->pluck('gross'));
}

Here is the code in the js file:

var data = {
    type:'line',
    labels:['Mon','Tues','Wed','Thurs','Fri','Sat','Sun'],
    datasets:[
    {
        data: {!! json_encode($gross) !!},
        backgroundColor:'rgba(137, 200, 85, 0.4)',
    }
]
}
var graph = document.getElementById('myNewChart').getContext('2d');
var myNewChart = new Chart(graph ,{
type: "line",
data: data,
options:{
    title:{
        display:true,
    }
}
});

Body:
You have a typo in your controller:

->with('grosss', $wkRevenue->pluck('gross'));

needs to be:

->with('gross', $wkRevenue->pluck('gross'));

Laravel changed the pluck() method in 5.2 to return a collection instead of an array.

In your view change your json_encode() to:

{!! $gross->toJson() !!}


问:
WordPress: Why Isn't add_rewrite_rule Working?

Goal

A visible URL of:

```<code>/products/building-automation/details/productSKU
</code>```

Should point to the real WordPress page of:

```<code>/products/details/?SKU=productSKU
</code>```

Code

```<code>public function setup_frontend() {

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        'products/details/?SKU=$matches[2]',
        'top'
    );

    // Other code logic...

}
</code>```

From what I can tell, the $matches points to the portions of the regex that are in (), so in the example, $matches[1] would be building-automation, and $matches[2] would be productSKU.

I have tried the flushing the rules, many times. This is being called from inside a class, but that doesn't appear to be the issue. I'm attaching the function to the init event.

What is Happening

I am getting the 404 template. What am I doing wrong?

Edit

Turns out, the second part of the parameter HAS to be index.php. Since I was trying to point to products/..., it broke. So I've updated to this:

```<code>    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        '?pagename=products/details&SKU=$matches[2]',
        'top'
    );
</code>```

It's not working and point to the right page and template. However, the $matches part is still not coming through. In fact, $_GET['SKU'] is coming through as '$matches[2]'.

答:
It doesn't work in this way... You trying to achive impossible with this code. Rewrites Rules in wordpress work with index.php routing, but not external pathes. So

products/(building-automation|lighting-controls)/details/([^/]*)

should be "translatable" to "wordpress" language (something like)

index.php?post_type=products&category=$matches[1]&scu=$matches[1]

notice, scu should also be defined as extra var.

edit 1:
Thing (I think) you trying to achive is really looks like a htaccess rule pattern, in this case you can use mod_rewrite_rules filter (it filter content that goes to .htaccess) to change it as you like it.

edit 2:
Advertisment - you can also use my debug bar plugin called debug bar rewrite rules to basically debug this data. Notice: (currently it doesn't support rules list via add_rewrite_rule, so you can only visually inspect rule, and see if it matches your expectation).

Body:
Goal

A visible URL of:

/products/building-automation/details/productSKU

Should point to the real WordPress page of:

/products/details/?SKU=productSKU

Code

public function setup_frontend() {

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        'products/details/?SKU=$matches[2]',
        'top'
    );

    // Other code logic...

}

From what I can tell, the $matches points to the portions of the regex that are in (), so in the example, $matches[1] would be building-automation, and $matches[2] would be productSKU.

I have tried the flushing the rules, many times. This is being called from inside a class, but that doesn't appear to be the issue. I'm attaching the function to the init event.

What is Happening

I am getting the 404 template. What am I doing wrong?

Edit

Turns out, the second part of the parameter HAS to be index.php. Since I was trying to point to products/..., it broke. So I've updated to this:

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        '?pagename=products/details&SKU=$matches[2]',
        'top'
    );

It's not working and point to the right page and template. However, the $matches part is still not coming through. In fact, $_GET['SKU'] is coming through as '$matches[2]'.


问:
Angular Material with Angular 4
Are there any options to use Angular Material with new Angular 4?

Official material.angularjs.org says:

Angular Material recently released Version 1 which we consider to be stable and ready for production use. Developers should note that Angular Material v1 works only with Angular 1.x.

And with regard to Angular 2:

Angular Material v2 development is also in progress at the angular/material2 GitHub repository

What about Angular 4? Do you think we can bind somehow Angular 1.x and Angular 4 in one project to bring Angular 4 new features and keep using the awesome Angular Material framework?

答:
In December 2016, when the Angular team was running around telling everyone to stop saying "Angular 2" and just say "Angular", I kind of thought it was silly marketing stuff.

In reading through questions on this site, however, I am beginning to see the rational for their plea. Angular 1.x to Angular 2 represented a complete rewrite, an entirely re-architected framework that broke just about everything. Adding to this is the switch to semver, which meant that new major versions numbers would be coming more rapidly.

In short, what I think they were trying to head off was the line of thinking that "Angular 4 is to Angular 2 as Angular 2 was to Angular 1", which is definitely not true.

This perception problem is also what led them to code name 4.0 "invisible makeover".

So, when you see packages that are designed for Angular2, most of them will probably work also with Angular 4. And if there are ng4 changes that break those packages, you will either quickly see releases to address those... or you'll have your answer about whether that package is well-maintained enough to use in your project.

Title: Angular Material with Angular 4


问:
How to get Chirpy working with JS and mash.config
I just downloaded and installed the most recent version of Chirpy [Nude Chirpy v1.0.0.5.3]
I created a "mash.less.chirp.config" file in my CSS directory, and it's compressing/minifying very spectacularly!!!

```<code><root>
    <FileGroup Name="site.css">
        <File Path="elements.css" />
        <File Path="jquery-ui-1.8.4.custom.css" />
        <File Path="site.less" />
        <File Path="wmd.css" />
    </FileGroup>
</root>
</code>```

I also created a "mash.chirp.config" file in my Script directory, unfortunately it's not doing anything at all.

```<code><root>
    <FileGroup Name="site.js">
        <File path="jquery-ui-1.8.4.custom.min.js" Minify="false" />
        <File path="un-master.js" />
        <File path="jquery-ui-timepicker-addon.min.js" Minify="false" />
        <File path="jquery-nmcFormHelper.js" />
        <File path="jquery.textarearesizer.min.js" Minify="false" />
        <File path="jquery-openid.js" />
        <File path="jquery.timeago.js" />
    </FileGroup>
</root>
</code>```

any help/direction on this will be greatly appreciated.

[ADDED INFO]

I'm using Visual Studio 2010 Professional

I've got an ASP.NET MVC3 Project

Folder Structure...

ROOT/Assets/Scripts/mash.chirp.config

     ROOT/Assets/Scripts/[all_my_js_files].js

答: Capitalize the p in path, brah!</p>

Body:
I just downloaded and installed the most recent version of Chirpy [Nude Chirpy v1.0.0.5.3]
I created a "mash.less.chirp.config" file in my CSS directory, and it's compressing/minifying very spectacularly!!!

<root>
    <FileGroup Name="site.css">
        <File Path="elements.css" />
        <File Path="jquery-ui-1.8.4.custom.css" />
        <File Path="site.less" />
        <File Path="wmd.css" />
    </FileGroup>
</root>

I also created a "mash.chirp.config" file in my Script directory, unfortunately it's not doing anything at all.

<root>
    <FileGroup Name="site.js">
        <File path="jquery-ui-1.8.4.custom.min.js" Minify="false" />
        <File path="un-master.js" />
        <File path="jquery-ui-timepicker-addon.min.js" Minify="false" />
        <File path="jquery-nmcFormHelper.js" />
        <File path="jquery.textarearesizer.min.js" Minify="false" />
        <File path="jquery-openid.js" />
        <File path="jquery.timeago.js" />
    </FileGroup>
</root>

any help/direction on this will be greatly appreciated.

[ADDED INFO]

I'm using Visual Studio 2010 Professional

I've got an ASP.NET MVC3 Project

Folder Structure...

ROOT/Assets/Scripts/mash.chirp.config

     ROOT/Assets/Scripts/[all_my_js_files].js

Body: Capitalize the p in path, brah!


问:
Why Calendar.getActualMaximum does not work
I want to get the max date of one month, that it's does't work in some day like the code, it's appear by condition as below
February has problem 2017 Feb Max is 28，If your computer's date is larger than 28, like 2017-03-29 or 2017-04-30</p>

```<code>Date date = PrimeUtil.formatStringToTime("2017-02","yyyy-MM");
System.out.println(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,date.getYear());
c.set(Calendar.MONTH,date.getMonth());
c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(c.getTime());
</code>```

答:
Your case: the value of date is "2017-02", the value of c is: "2017-03-30"

```<code>date: 2017-02
c: 2017-03-30

c.set(Calendar.YEAR, date.getYear());
c.set(Calendar.MONTH, date.getMonth());
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
</code>```

=>

```<code>c.set(Calendar.YEAR, 2017);
c.set(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 31);
</code>```

Here set 31 to DAY_OF_MONTH, Which could not get what you expected!

Another case:
the value of date is "2017-04", the value of c is: "2017-03-31"

```<code>date: 2017-04
c: 2017-05-31
</code>```

When we set 31 to DAY_OF_MONTH, we will not get what we expected.

Body:
I want to get the max date of one month, that it's does't work in some day like the code, it's appear by condition as below
February has problem 2017 Feb Max is 28，If your computer's date is larger than 28, like 2017-03-29 or 2017-04-30

Date date = PrimeUtil.formatStringToTime("2017-02","yyyy-MM");
System.out.println(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,date.getYear());
c.set(Calendar.MONTH,date.getMonth());
c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(c.getTime());

Body:
Your case: the value of date is "2017-02", the value of c is: "2017-03-30"

date: 2017-02
c: 2017-03-30

c.set(Calendar.YEAR, date.getYear());
c.set(Calendar.MONTH, date.getMonth());
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

=>

c.set(Calendar.YEAR, 2017);
c.set(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 31);

Here set 31 to DAY_OF_MONTH, Which could not get what you expected!

Another case:
the value of date is "2017-04", the value of c is: "2017-03-31"

date: 2017-04
c: 2017-05-31

When we set 31 to DAY_OF_MONTH, we will not get what we expected.


问:
How to find the number of digits of an integer if the input is 0000? (The output must be 4 and not 1)
When calculating the number of digits, the compiler takes 0000 as a single 0 and the answer is 1. But the number of zeroes in each place must be calculated. For example : 0000 - 4
00 - 2</p>

```<code>int n,c=0;
scanf("%d",&n);
do{
   n=n/10;
   c++;
}while(n!=0);
printf("%d",c);
</code>```

答:
The answer is in the comment above, but lets make this a full official answer :

If you talk about integers, 000 and 0 are the exact same.
So if you want to distinguish the two, you must treat the entry as a string instead, and completely forget there are numbers inside.
And for a string, it is easy to count how many characters there are.

Body:
When calculating the number of digits, the compiler takes 0000 as a single 0 and the answer is 1. But the number of zeroes in each place must be calculated. For example : 0000 - 4
00 - 2

int n,c=0;
scanf("%d",&n);
do{
   n=n/10;
   c++;
}while(n!=0);
printf("%d",c);