问:
How can I test for an expected exception with a specific exception message from a resource file in Visual Studio Test?
Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this:

```<code>[TestMethod]
[ExpectedException(typeof(CriticalException))]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
</code>```

You can also check for the message contained within the ExpectedException like this:

```<code>[TestMethod]
[ExpectedException(typeof(CriticalException), "An error occured")]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
</code>```

But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this:

```<code>[TestMethod]
[ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
</code>```

The compiler will give the following error:

An attribute argument must be a
  constant expression, typeof expression
  or array creation expression of an
  attribute

Does anybody know how to test for an exception that has a message from a resource file?

One option I have considered is using custom exception classes, but based on often heard advice such as:

"Do create and throw custom exceptions
  if you have an error condition that
  can be programmatically handled in a
  different way than any other existing
  exception. Otherwise, throw one of the
  existing exceptions." Source

I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions?

答: The ExpectedException Message argument does not match against the message of the exception. Rather this is the message that is printed in the test results if the expected exception did not in fact occur.</p>

OwnerDisplayName: AlexDuggleby

Body:
Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this:

[TestMethod]
[ExpectedException(typeof(CriticalException))]
public void GetOrganisation_MultipleOrganisations_ThrowsException()

You can also check for the message contained within the ExpectedException like this:

[TestMethod]
[ExpectedException(typeof(CriticalException), "An error occured")]
public void GetOrganisation_MultipleOrganisations_ThrowsException()

But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this:

[TestMethod]
[ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)]
public void GetOrganisation_MultipleOrganisations_ThrowsException()

The compiler will give the following error:

An attribute argument must be a
  constant expression, typeof expression
  or array creation expression of an
  attribute

Does anybody know how to test for an exception that has a message from a resource file?

One option I have considered is using custom exception classes, but based on often heard advice such as:

"Do create and throw custom exceptions
  if you have an error condition that
  can be programmatically handled in a
  different way than any other existing
  exception. Otherwise, throw one of the
  existing exceptions." Source

I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions?

LastEditorDisplayName: AlexDuggleby


来源: stackexchange

问:
System.out.print is overlapping the questions why?
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

```<code>"Enter the second student's name: Enter the student's score: "
</code>```

instead of

```<code>"Enter the second students's name: "

"Enter the student's score: "
</code>```

I also can not input data into the System.out.print method of the second student

My main code where the error is:

```<code>System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}
</code>```

the part that deals with the error from the class is as follows

```<code>public void setName(String nm){
    name = nm;
}
</code>```

答: I believe you are talking about how all the lines are printed on the same line. You need to either use line break characters '\n' in Java, or use System.out.println

ContentLicense: CC BY-SA 2.5

Body:
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

"Enter the second student's name: Enter the student's score: "

instead of

"Enter the second students's name: "

"Enter the student's score: "

I also can not input data into the System.out.print method of the second student

My main code where the error is:

System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}

the part that deals with the error from the class is as follows

public void setName(String nm){
    name = nm;
}


问:
Video source with onclick selector
Hi StackOverflow friends. Sorry for being so noob, but I cannot manage to get this snippet working. All I wanted to do was selecting a number from a , and change the video src of the following player replacing that number inside the url itself. For example if I would choose the number 13 my plan was obtaining a refresh of the player with the new source, in this case "https://hostingsite.com/folder/Episode_13_Cartoon.mp4", but as you can see I'm not used to work in js so any help would be highly appreciated. Thanks in advance, here's the snippet

function changeVideo() {
        document.getElementById("player").src = "https://hostingsite.com/folder/Episode_" + episode + "_Cartoon.mp4";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="players">
<div class="container">
   <div class="media-container">
      <span class="title">Episode Selector</span>
      onclick="{ document.getElementById('episode').value='13'; changeVideo();}">
      onclick="{ document.getElementById('episode').value='14'; changeVideo();}">
      onclick="{ document.getElementById('episode').value='15'; changeVideo();}">
      <select name="player1-sources" id="player1-sources">
         <option value="">Select source</option>
         <option value="12">12</option>
         <option value="13">13</option>
         <option value="14">14</option>
      </select>
      <video id="player" width="100%" height="100%" controls preload="auto" src="https://hostingsite.com/folder/Episode_default_Cartoon.mp4" type="video/mp4"></video>
   </div>
</div></code>```

答:
Try

```<code>function changeVideo() {
    document.getElementById("player").src = "https://hostingsite.com/folder/Episode_" + document.getElementById('episode').value + "_Cartoon.mp4";
}
</code>```

I hope helpful. :)

ContentLicense: CC BY-SA 3.0

Title: Video source with onclick selector

Body:
Hi StackOverflow friends. Sorry for being so noob, but I cannot manage to get this snippet working. All I wanted to do was selecting a number from a , and change the video src of the following player replacing that number inside the url itself. For example if I would choose the number 13 my plan was obtaining a refresh of the player with the new source, in this case "https://hostingsite.com/folder/Episode_13_Cartoon.mp4", but as you can see I'm not used to work in js so any help would be highly appreciated. Thanks in advance, here's the snippet

function changeVideo() {
        document.getElementById("player").src = "https://hostingsite.com/folder/Episode_" + episode + "_Cartoon.mp4";
}

      Episode Selector

      <select name="player1-sources" id="player1-sources">
         <option value="">Select source</option>
         <option value="12">12</option>
         <option value="13">13</option>
         <option value="14">14</option>
      </select>
      <video id="player" width="100%" height="100%" controls preload="auto" src="https://hostingsite.com/folder/Episode_default_Cartoon.mp4" type="video/mp4"></video>

Body:
Try

function changeVideo() {
    document.getElementById("player").src = "https://hostingsite.com/folder/Episode_" + document.getElementById('episode').value + "_Cartoon.mp4";
}

I hope helpful. :)


问:
Make audio 'resume' after being stopped?
I'm building a Text-Based RPG, and I've managed to add some .wav files to my program with no issue, I'm also able to play them properly with no issue either.

What happens currently?

I have 2 .wav files, 1 for general background music (newbieMelody.wav), and the other for when you level up (levelUp.wav). So to start off, when I run my game, we begin with the newbieMelody.wav file to play in the background, like so:

```<code>#pragma comment(lib, "winmm.lib")

#include "Quiz.h"
#include <iostream>
#include <windows.h>
#include <mmsystem.h>

int main() {

    PlaySound(TEXT("C:\\Users\\User\\Documents\\GIT\\TextBased\\QuizApplication\\playSound\\newbieMelody.wav"),
                    NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);     // we play the sound here

    // create a game
    Game *game = new Game();
    game->readAreaFromFile();   // calls a file for area location
    game->run();                // loads the game UI

    //destroy gameWorld
    delete game;

    system("PAUSE");
}
</code>```

Then, whenever we level up in my void Game::run() function (in another cpp file), I do a few increments, reset xpCount, and play the levelUp.wav:

```<code>if (xpCount >= xpPeak) { // if current exp is larger or = to xp cap

            combatLevel += 1;   // current combat lvl
            xpCount = 0;    // records total exp
            xpPeak += 4;    // takes longer to level up each level

            setcolor(yellow, black);    // sets location green
            cout << "Congratulations, you just advanced your Combat level!" << endl;
            cout << "Your Combat level is now " << combatLevel << "." << '\n' << endl;

            PlaySound(TEXT("C:\\Users\\User\\Documents\\GIT\\TextBased\\QuizApplication\\playSound\\levelUp.wav"),
                NULL, SND_FILENAME | SND_ASYNC);  // play level up sound

            this_thread::sleep_for(chrono::seconds(5)); // sleeps output to allow level up song to finish

            levelUpDone = true; // leveled up
        }
</code>```

Once this has finished playing, we "resume" with playing the newbieMelody.wav file:

```<code>if (levelUpDone == true) {  // access since player leveled up

            PlaySound(TEXT("C:\\Users\\User\\Documents\\GIT\\TextBased\\QuizApplication\\playSound\\newbieMelody.wav"),
                NULL, SND_FILENAME | SND_ASYNC | SND_LOOP); // resume newbie melody???

            levelUpDone = false;    // back to false to avoid errors
        }
</code>```

What's the issue?

This generally works how I'd like it to, however when my newbieMelody.wav file plays again after the levelUp.wav file, it restarts from the beginning instead of resuming from where it was last played.

My question is, how exactly am I able to alter my code so the background music resumes from where it was last playing from, rather than starting over again? Is there some way I can simply pause the background song whilst the levelUp.wav file plays, then resume once it's finished?

答:
PlaySound was never meant for this type of scenario.  As you have observed, there is no support for progress notifications, pause/resume, or volume. It was really only meant for short notification sounds.

Alternatives for game sounds include XAudio2 and DirectSound.   There's also some open source sound APIs that could work for you too.

At a higher level, you could use legacy Windows Media Player APIs, DirectShow, or Media Foundation.

Body:
I'm building a Text-Based RPG, and I've managed to add some .wav files to my program with no issue, I'm also able to play them properly with no issue either.

What happens currently?

I have 2 .wav files, 1 for general background music (newbieMelody.wav), and the other for when you level up (levelUp.wav). So to start off, when I run my game, we begin with the newbieMelody.wav file to play in the background, like so:

#pragma comment(lib, "winmm.lib")

#include "Quiz.h"
#include <iostream>
#include <windows.h>
#include <mmsystem.h>

int main() {

    PlaySound(TEXT("C:\\Users\\User\\Documents\\GIT\\TextBased\\QuizApplication\\playSound\\newbieMelody.wav"),
                    NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);     // we play the sound here

    // create a game
    Game *game = new Game();
    game->readAreaFromFile();   // calls a file for area location
    game->run();                // loads the game UI

    //destroy gameWorld
    delete game;

    system("PAUSE");
}

Then, whenever we level up in my void Game::run() function (in another cpp file), I do a few increments, reset xpCount, and play the levelUp.wav:

if (xpCount >= xpPeak) { // if current exp is larger or = to xp cap

            combatLevel += 1;   // current combat lvl
            xpCount = 0;    // records total exp
            xpPeak += 4;    // takes longer to level up each level

            setcolor(yellow, black);    // sets location green
            cout << "Congratulations, you just advanced your Combat level!" << endl;
            cout << "Your Combat level is now " << combatLevel << "." << '\n' << endl;

            PlaySound(TEXT("C:\\Users\\User\\Documents\\GIT\\TextBased\\QuizApplication\\playSound\\levelUp.wav"),
                NULL, SND_FILENAME | SND_ASYNC);  // play level up sound

            this_thread::sleep_for(chrono::seconds(5)); // sleeps output to allow level up song to finish

            levelUpDone = true; // leveled up
        }

Once this has finished playing, we "resume" with playing the newbieMelody.wav file:

if (levelUpDone == true) {  // access since player leveled up

            PlaySound(TEXT("C:\\Users\\User\\Documents\\GIT\\TextBased\\QuizApplication\\playSound\\newbieMelody.wav"),
                NULL, SND_FILENAME | SND_ASYNC | SND_LOOP); // resume newbie melody???

            levelUpDone = false;    // back to false to avoid errors
        }

What's the issue?

This generally works how I'd like it to, however when my newbieMelody.wav file plays again after the levelUp.wav file, it restarts from the beginning instead of resuming from where it was last played.

My question is, how exactly am I able to alter my code so the background music resumes from where it was last playing from, rather than starting over again? Is there some way I can simply pause the background song whilst the levelUp.wav file plays, then resume once it's finished?


问:
PHP char coding, #==0, 0==NULL, #!=NULL
I need to use a special character as a stop/break signal for my program. I was trying out '#' '&' '@' and kept on receiving errors.

After some messing around, I discovered that all characters including the ones above all had the numeric value 0! I did so by comparing their values with numerics, because at first I thought it used ASCII codes.

Wait a minute, that's not right, because NULL also equals to 0! But the characters definitely does not equal to NULL!

So, what kind of char coding does PHP use? Is it impossible to compare chars with numbers?

Thanks in advance!

答:
When you compare a string with an integer, the string will be casted to int and give 0.

You might want to use ord:

```<code><?php
$str = "\n";
if (ord($str) == 10) {
    echo "\$str is a line feed.\n";
}
?>
</code>```

Title: PHP char coding, #==0, 0==NULL, #!=NULL

Body:
When you compare a string with an integer, the string will be casted to int and give 0.

You might want to use ord:

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "\$str is a line feed.\n";
}
?>


问:
Resizing SVG in html?
So, I have an SVG file in HTML, and one of the things I've heard about the format is that it doesn't get all pixelated when you zoom in on it.

I know with a jpeg or whatever I could have it stored as a 50 by 50 icon, then actually display it as a (rather pixelated) 100 by 100 thumbnail (or 10 by 10), by manually setting the height and width in the image_src tag.

However, SVG files seem to be used with object/embed tags, and changing the height or width of THOSE just results in more space being allocated for the picture.

IS there any way to specify that you want an SVG image displayed smaller or larger than it actually is stored in the file system?

答:
Here is an example of getting the bounds using svg.getBox():
https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44

At the end you get numbers that you can plug into the svg to set the viewbox properly.  Then use any css on the parent div and you're done.

```<code> // get all SVG objects in the DOM
 var svgs = document.getElementsByTagName("svg");
 var svg = svgs[0],
    box = svg.getBBox(), // <- get the visual boundary required to view all children
    viewBox = [box.x, box.y, box.width, box.height].join(" ");

    // set viewable area based on value above
    svg.setAttribute("viewBox", viewBox);
</code>```

Title: Resizing SVG in html?

Body:
Here is an example of getting the bounds using svg.getBox():
https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44

At the end you get numbers that you can plug into the svg to set the viewbox properly.  Then use any css on the parent div and you're done.

 // get all SVG objects in the DOM
 var svgs = document.getElementsByTagName("svg");
 var svg = svgs[0],
    box = svg.getBBox(), // <- get the visual boundary required to view all children
    viewBox = [box.x, box.y, box.width, box.height].join(" ");

    // set viewable area based on value above
    svg.setAttribute("viewBox", viewBox);


问:
Using mapply() For Column Row Comparison
I am working with two different large data set and trying to make use of mapply() to get iterative functions working.

The goal is to take each data point column wise from Data_1, and compare it against both the data points in column of Data_2. So, Data_1[1,1] will be compared against Data_2[1,1] and Data_2[2,1] only. To be more clear, data1 column in Data_1 will only be compared against dataA elements in Data_2, thus no cross column comparison.

Data_1: NxM

```<code>  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.713972
</code>```

Data_2: PxQ

```<code>  dataA       dataB       dataC      dataD
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644
</code>```

I had earlier written a for() while() loop based algorithm, but the run time was too much as the original data is . Then, I moved to apply() based logic, but still had loops within function I was calling, so that didn't speed up the code. Based on my earlier question, I am figuring out better way to do this with mapply().

The part I am not able to visualize is the column to row comparison and how mapply() will navigate over it recursively. How can I use mapply() or lapply() to get this done efficiently?

Any suggestions will be helpful, thanks.

答:
Consider a nested apply family call:

mapply() - outer: pairwise iteration between corresponding columns of Data_1 and Data_2

sapply - inner: vector iteration of each value in the Data_1 column for element comparison

Below checks if each Data_1 value is between the two values of each column of Data_2:

Data

```<code>txt = '  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.713972'

Data_1 <- read.table(text=txt, header=TRUE)

txt = ' dataA       dataB       dataC      dataD
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644'

Data_2 <- read.table(text=txt, header=TRUE)
</code>```

Code

```<code>check_inbetween <- function(x,y){
  sapply(x, function(i) (i > y[1] & i < y[2]))
}

inbetween_matrix <- mapply(check_inbetween, Data_1, Data_2)

inbetween_matrix
#      data1 data2 data3 data4
# [1,] FALSE FALSE FALSE  TRUE
# [2,]  TRUE FALSE FALSE FALSE
# [3,]  TRUE FALSE FALSE FALSE
# [4,] FALSE FALSE FALSE  TRUE
</code>```

Body:
I am working with two different large data set and trying to make use of mapply() to get iterative functions working.

The goal is to take each data point column wise from Data_1, and compare it against both the data points in column of Data_2. So, Data_1[1,1] will be compared against Data_2[1,1] and Data_2[2,1] only. To be more clear, data1 column in Data_1 will only be compared against dataA elements in Data_2, thus no cross column comparison.

Data_1: NxM

  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.713972

Data_2: PxQ

  dataA       dataB       dataC      dataD
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644

I had earlier written a for() while() loop based algorithm, but the run time was too much as the original data is . Then, I moved to apply() based logic, but still had loops within function I was calling, so that didn't speed up the code. Based on my earlier question, I am figuring out better way to do this with mapply().

The part I am not able to visualize is the column to row comparison and how mapply() will navigate over it recursively. How can I use mapply() or lapply() to get this done efficiently?

Any suggestions will be helpful, thanks.

Body:
Consider a nested apply family call:

mapply() - outer: pairwise iteration between corresponding columns of Data_1 and Data_2

sapply - inner: vector iteration of each value in the Data_1 column for element comparison

Below checks if each Data_1 value is between the two values of each column of Data_2:

Data

txt = '  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.713972'

Data_1 <- read.table(text=txt, header=TRUE)

txt = ' dataA       dataB       dataC      dataD
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644'

Data_2 <- read.table(text=txt, header=TRUE)

Code

check_inbetween <- function(x,y){
  sapply(x, function(i) (i > y[1] & i < y[2]))
}

inbetween_matrix <- mapply(check_inbetween, Data_1, Data_2)

inbetween_matrix
#      data1 data2 data3 data4
# [1,] FALSE FALSE FALSE  TRUE
# [2,]  TRUE FALSE FALSE FALSE
# [3,]  TRUE FALSE FALSE FALSE
# [4,] FALSE FALSE FALSE  TRUE


问:
How to add devices from storyboard View as

This is my storyboard screen.

As you see, There are 4 iPhone type in my Xcode.

I want to add an iPad here. But, I don't know how to add other devices.

答:
I solved.

Go to 'Interface Builder Document' then check the 'Use Trait Variations'


问:
performance issues using UNION , multiple columns
Union in the oracle query is causing a lot of FTS (full table scans) and high row count any better way i can rewrite this query ?

performance issues using UNION

```<code>    SELECT
                    store.store_name name,
                    store.block_id block_id,
                    store.marker flag,
                    substr('A',1,1) store_type,
                    substr(area.area_code,1,5) area_code,
                    substr(area.area_name,1,5) area_name
    FROM  store , area
            where store.store_id = area.store_id
            and store.block_id = area.block_id
    UNION
     SELECT
                    store.store_name name,
                    store.block_id block_id,
                    store.marker flag,
                    substr('A',1,1) store_type,
                    substr(market.market_code,1,5) area_code,
                    substr(market.market_area,1,5) area_name
    FROM  store , market
            where store.store_id = market.store_id
            and store.block_id =market.block_id;

                 | Id  | Operation                     | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
                 ---------------------------------------------------------------------------------------
                 |   0 | SELECT STATEMENT              |  1845K|    61M|       |   120K  (1)| 00:00:05 |
                 |   1 |  UNION-ALL                    |       |       |       |            |          |
                 |   2 |   MERGE JOIN                  |  1719K|    57M|       | 98522   (2)| 00:00:04 |
                 |   3 |    SORT JOIN                  |  1761K|    25M|    94M| 30984   (1)| 00:00:02 |
                 |   4 |     TABLE ACCESS FULL         |  1761K|    25M|       | 21911   (1)| 00:00:01 |
                 |*  5 |    SORT JOIN                  |  1882K|    35M|   115M| 67538   (2)| 00:00:03 |
                 |   6 |     TABLE ACCESS FULL         |  1882K|    35M|       | 56061   (2)| 00:00:03 |
                 |   7 |   NESTED LOOPS                |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   8 |    NESTED LOOPS               |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   9 |     TABLE ACCESS FULL         |   126K|  1726K|       |  3232   (2)| 00:00:01 |
</code>```

Index are on (tab1 (aid,bid), tab2(aid,bid) , tab3(cid,bid))

答:
Generally, UNION will not cause the FTS.  FTS is decided by the optimizer if it thinks it can do better scanning all the rows rather than an indexed access followed by a table access.  So I see a few issues with this problem as posed:

there is no data subsetting, which means you want all the rows
anyway, so if that is the case, then FTS is likely going to be the
lowest cost option.

with no data subsetting, the only possible way for an index to be
used is if the "join columns" are indexes in at least the table that
follows the FTS (in some cases you might look for the smaller table
to be FTS, followed by indexed access to the larger table based on
the join condition column being indexes).

you don't indicate the table sizes or what the indexes are;
knowledge of the cardinality etc. is essential to SQL tuning.

Also, if you have license to Diagnostics+Tuning Pack, you can run the SQL through the SQL Tuning Advisor and see what tuning advice this tool provides.

Body:
Union in the oracle query is causing a lot of FTS (full table scans) and high row count any better way i can rewrite this query ?

performance issues using UNION

    SELECT
                    store.store_name name,
                    store.block_id block_id,
                    store.marker flag,
                    substr('A',1,1) store_type,
                    substr(area.area_code,1,5) area_code,
                    substr(area.area_name,1,5) area_name
    FROM  store , area
            where store.store_id = area.store_id
            and store.block_id = area.block_id
    UNION
     SELECT
                    store.store_name name,
                    store.block_id block_id,
                    store.marker flag,
                    substr('A',1,1) store_type,
                    substr(market.market_code,1,5) area_code,
                    substr(market.market_area,1,5) area_name
    FROM  store , market
            where store.store_id = market.store_id
            and store.block_id =market.block_id;

                 | Id  | Operation                     | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
                 ---------------------------------------------------------------------------------------
                 |   0 | SELECT STATEMENT              |  1845K|    61M|       |   120K  (1)| 00:00:05 |
                 |   1 |  UNION-ALL                    |       |       |       |            |          |
                 |   2 |   MERGE JOIN                  |  1719K|    57M|       | 98522   (2)| 00:00:04 |
                 |   3 |    SORT JOIN                  |  1761K|    25M|    94M| 30984   (1)| 00:00:02 |
                 |   4 |     TABLE ACCESS FULL         |  1761K|    25M|       | 21911   (1)| 00:00:01 |
                 |*  5 |    SORT JOIN                  |  1882K|    35M|   115M| 67538   (2)| 00:00:03 |
                 |   6 |     TABLE ACCESS FULL         |  1882K|    35M|       | 56061   (2)| 00:00:03 |
                 |   7 |   NESTED LOOPS                |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   8 |    NESTED LOOPS               |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   9 |     TABLE ACCESS FULL         |   126K|  1726K|       |  3232   (2)| 00:00:01 |

Index are on (tab1 (aid,bid), tab2(aid,bid) , tab3(cid,bid))


问:
C++ using global variable shows 100% slower than a pointer, when using pthread?
I've got a quite program to show the performance of 2 similar programs, both uses 2 threads to do calculation. The core difference is that one uses a global variable, another uses a "new" object, as below:

```<code>#include<pthread.h>
#include<stdlib.h>
struct M{
    long a;
    long b;
}obj;
size_t count=2000000000;
void* addx(void*args){
    long*pl=(long*)args;
    for(size_t i=0;i<count;++i)
        (*pl)*=i;
    return NULL;
}
int main(int argc,char*argv[]){
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,addx,&obj.a);
    pthread_create(&tid[1],NULL,addx,&obj.b);
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    return 0;
}

clang++ test03_threads.cpp -o test03_threads -lpthread -O2 && time ./test03_threads

real    0m3.626s
user    0m6.595s
sys 0m0.009s
</code>```

It's quite slow, then I modified obj to be dynamically created(I expected it to be even slower):

```<code>#include<pthread.h>
#include<stdlib.h>
struct M{
    long a;
    long b;
}*obj;//difference 1
size_t count=2000000000;
void* addx(void*args){
    long*pl=(long*)args;
    for(size_t i=0;i<count;++i)
        (*pl)*=i;
    return NULL;
}
int main(int argc,char*argv[]){
    obj=new M;//difference 2
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,addx,&obj->a);//difference 3
    pthread_create(&tid[1],NULL,addx,&obj->b);//difference 4
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    delete obj;//difference 5
    return 0;
}

clang++ test03_threads_new.cpp -o test03_threads_new -lpthread -O2 && time ./test03_threads_new

real    0m1.880s
user    0m3.745s
sys 0m0.007s
</code>```

It's amazingly 100% faster than the previous one. I also tried g++ on linux, same result.
But how to explain this? I know obj is global variable, but *obj is still global variable, just dynamically created. What's the core difference?

答:
I think that this is indeed because of false sharing, as Unimportant suggested.

Why the difference then, you may ask?

Because of the count variable! As this is a variable, and size_t's underlying type happens to be long for you, the compiler cannot optimize it away (because pl could point to count). If count would be an int, because of strict aliasing rules, the compiler can optimize it away (or simply it could be const size_t).

So the generated code has to read count every time in the loop.

In the first example, count and obj both global variables, they are placed near to each other. So, there is a high possibility that the linker put these variables into the same cache line. So writing to obj.a or obj.b will invalidate the cache line of count. So the CPU has to synchronize the reads of count.

In the second example, obj is allocated on the heap, it's address will be far enough from count, so they won't occupy the same cache line. No synchronization needed for count.

Body:
I've got a quite program to show the performance of 2 similar programs, both uses 2 threads to do calculation. The core difference is that one uses a global variable, another uses a "new" object, as below:

#include<pthread.h>
#include<stdlib.h>
struct M{
    long a;
    long b;
}obj;
size_t count=2000000000;
void* addx(void*args){
    long*pl=(long*)args;
    for(size_t i=0;i<count;++i)
        (*pl)*=i;
    return NULL;
}
int main(int argc,char*argv[]){
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,addx,&obj.a);
    pthread_create(&tid[1],NULL,addx,&obj.b);
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    return 0;
}

clang++ test03_threads.cpp -o test03_threads -lpthread -O2 && time ./test03_threads

real    0m3.626s
user    0m6.595s
sys 0m0.009s

It's quite slow, then I modified obj to be dynamically created(I expected it to be even slower):

#include<pthread.h>
#include<stdlib.h>
struct M{
    long a;
    long b;
}*obj;//difference 1
size_t count=2000000000;
void* addx(void*args){
    long*pl=(long*)args;
    for(size_t i=0;i<count;++i)
        (*pl)*=i;
    return NULL;
}
int main(int argc,char*argv[]){
    obj=new M;//difference 2
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,addx,&obj->a);//difference 3
    pthread_create(&tid[1],NULL,addx,&obj->b);//difference 4
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    delete obj;//difference 5
    return 0;
}

clang++ test03_threads_new.cpp -o test03_threads_new -lpthread -O2 && time ./test03_threads_new

real    0m1.880s
user    0m3.745s
sys 0m0.007s

It's amazingly 100% faster than the previous one. I also tried g++ on linux, same result.
But how to explain this? I know obj is global variable, but *obj is still global variable, just dynamically created. What's the core difference?


问:
Connecting phpMyAdmin in XAMPP with Laravel project
i tried to attach phpMyAdmin in my XAMPP server with my Laravel project and i failed , every time i make :

```<code>php artisan migrate
</code>```

This error occurs:

```<code>[PDOException]
SQLSTATE[HY000] [2002] No such file or directory
</code>```

This is my .env file :

```<code>DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=''
</code>```

This is my database.php file :

```<code>'mysql' => [
    'driver' => 'mysql',
    'host' => 'localhost',
    'port' => env('DB_PORT', '3306'),
    'database' => 'laravel',
    'username' => 'root',
    'password' => '',
    'unix_socket' =>  '/opt/lampp/var/mysql/mysql.sock',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,

],
</code>```

答: The error is because you are trying to connect to MYSQL with a socket file which cannot be found given the path provided. Change the path to the mysql.sock file

Body:
i tried to attach phpMyAdmin in my XAMPP server with my Laravel project and i failed , every time i make :

php artisan migrate

This error occurs:

[PDOException]
SQLSTATE[HY000] [2002] No such file or directory

This is my .env file :

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=''

This is my database.php file :

'mysql' => [
    'driver' => 'mysql',
    'host' => 'localhost',
    'port' => env('DB_PORT', '3306'),
    'database' => 'laravel',
    'username' => 'root',
    'password' => '',
    'unix_socket' =>  '/opt/lampp/var/mysql/mysql.sock',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,

],


问:
Using a VBA VLOOKUP with an Intersect in Excel 2010
I have a spreadsheet that is used to enter instrument data and associated readings. There are multiple instruments entered from a validated list into a named range of "All_Inst". When an instrument is changed I need to clear out data in the row associated with that entry that is no longer applicable. At this data differs by instrument, I stored the various combinations in a simple 2 column table named "Delete_Data_TBL". From there I'm trying to use a VLookup to feed a case statement to clear the applicable cells.

I've successfully tested the vlookup outside of the intersect using a hardcoded value for the lookup value. I think the problem is using the c.value in the vlookup, but I can't find anything on what syntax to use. I tried  assigning c.value to a variable and passing the variable to the vlookup, but wasn't able to get that working either, though again I'm unsure of the syntax.

A somewhat simplified version of what I've tried is as follows;

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

Dim c As Range
Dim d As Integer

'***Check if any ALL_Inst cells have been changed
If Not Intersect(Target, Range("All_Inst")) Is Nothing Then

    'Evaluate the cell that has changed to determine what should be set to ""
    For Each c In Intersect(Target, Range("All_Inst")).Cells

        d = Application.WorksheetFunction.VLookup(c.Value, Sheets("Inst_Tables").Range("Delete_Data_TBL"), 2, False)

        Select Case d
            Case 0, 5
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 3
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 4
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
            Case 6, 7
                c.Offset(0, 4).Value = ""
            Case 9
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
            Case Else
                'Do Nothing
        End Select

    Next

End If

End Sub
</code>```

答:
I apologize to stackexchange, i don't have enough reputation to make a comment but I think your problem is when cl.value is not found in the range. you can add in some error handling as follows:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

Dim c As Range
Dim d As Integer`

'***Check if any ALL_Inst cells have been changed
If Not Intersect(Target, Range("All_Inst")) Is Nothing Then

'Evaluate the cell that has changed to determine what should be set to ""
For Each c In Intersect(Target, Range("All_Inst")).Cells

    on error resume next
    d = Application.WorksheetFunction.VLookup(c.Value,Sheets("Inst_Tables").Range("Delete_Data_TBL"), 2, False)

    if isempty(d) = false then
        Select Case d
            Case 0, 5
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 3
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 4
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
            Case 6, 7
                c.Offset(0, 4).Value = ""
            Case 9
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
            Case Else
                'Do Nothing
        End Select
    end if
Next

End Sub
</code>```

Body:
I have a spreadsheet that is used to enter instrument data and associated readings. There are multiple instruments entered from a validated list into a named range of "All_Inst". When an instrument is changed I need to clear out data in the row associated with that entry that is no longer applicable. At this data differs by instrument, I stored the various combinations in a simple 2 column table named "Delete_Data_TBL". From there I'm trying to use a VLookup to feed a case statement to clear the applicable cells.

I've successfully tested the vlookup outside of the intersect using a hardcoded value for the lookup value. I think the problem is using the c.value in the vlookup, but I can't find anything on what syntax to use. I tried  assigning c.value to a variable and passing the variable to the vlookup, but wasn't able to get that working either, though again I'm unsure of the syntax.

A somewhat simplified version of what I've tried is as follows;

Private Sub Worksheet_Change(ByVal Target As Range)

Dim c As Range
Dim d As Integer

'***Check if any ALL_Inst cells have been changed
If Not Intersect(Target, Range("All_Inst")) Is Nothing Then

    'Evaluate the cell that has changed to determine what should be set to ""
    For Each c In Intersect(Target, Range("All_Inst")).Cells

        d = Application.WorksheetFunction.VLookup(c.Value, Sheets("Inst_Tables").Range("Delete_Data_TBL"), 2, False)

        Select Case d
            Case 0, 5
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 3
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 4
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
            Case 6, 7
                c.Offset(0, 4).Value = ""
            Case 9
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
            Case Else
                'Do Nothing
        End Select

    Next

End If

End Sub

Body:
I apologize to stackexchange, i don't have enough reputation to make a comment but I think your problem is when cl.value is not found in the range. you can add in some error handling as follows:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim c As Range
Dim d As Integer`

'***Check if any ALL_Inst cells have been changed
If Not Intersect(Target, Range("All_Inst")) Is Nothing Then

'Evaluate the cell that has changed to determine what should be set to ""
For Each c In Intersect(Target, Range("All_Inst")).Cells

    on error resume next
    d = Application.WorksheetFunction.VLookup(c.Value,Sheets("Inst_Tables").Range("Delete_Data_TBL"), 2, False)

    if isempty(d) = false then
        Select Case d
            Case 0, 5
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 3
                c.Offset(0, 15).Value = ""
                c.Offset(0, 17).Value = ""
            Case 4
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
                c.Offset(0, 11).Value = ""
                c.Offset(0, 13).Value = ""
            Case 6, 7
                c.Offset(0, 4).Value = ""
            Case 9
                c.Offset(0, 1).Value = ""
                c.Offset(0, 4).Value = ""
                c.Offset(0, 7).Value = ""
            Case Else
                'Do Nothing
        End Select
    end if
Next

End Sub


问:
How to add Jsoup to my Android Studio project?
I am trying to use jsoup in my android studio project but i keep getting this error: Error:(10, 16) Gradle: error: package org.jsoup does not exist.

Could you guys tell me the steps on how to add jsoup library to my project? Thanks in advance.

Edit: For learning purpuse i am running the java code alone without main activity!

code:

```<code>package com.jsoupTest.jsoupTest;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class JsoupGetRequest {

    public static void main(String[] args) throws IOException {

        String dc=Jsoup.connect("http://somelink.com").timeout(6000).get();
        System.out.println(dc);
    }

}
</code>```

答:
Gradle (build.gradle) in your app folder. put under dependencies section. clean and rebuild project </p>

```<code>// jsoup HTML parser library @ https://jsoup.org/
implementation 'org.jsoup:jsoup:1.10.3'
</code>```

Body:
I am trying to use jsoup in my android studio project but i keep getting this error: Error:(10, 16) Gradle: error: package org.jsoup does not exist.

Could you guys tell me the steps on how to add jsoup library to my project? Thanks in advance.

Edit: For learning purpuse i am running the java code alone without main activity!

code:

package com.jsoupTest.jsoupTest;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class JsoupGetRequest {

    public static void main(String[] args) throws IOException {

        String dc=Jsoup.connect("http://somelink.com").timeout(6000).get();
        System.out.println(dc);
    }

}

Body:
Gradle (build.gradle) in your app folder. put under dependencies section. clean and rebuild project

// jsoup HTML parser library @ https://jsoup.org/
implementation 'org.jsoup:jsoup:1.10.3'

ContentLicense: CC BY-SA 4.0


问:
Python regex pull first capitalized word or first and second words if both are capitalized
The current regex formula I have implemented is only able to extract the first two capitalized words for a given string. I want to be able to extract just the first word in a string if the second word is not capitalized.

Here are some examples:

```<code>s = 'Smith John went to ss for Jones.'
s = 'Jones, Greg went to 2b for Smith.'
s = 'Doe went to ss for Jones.'
</code>```

Essentially, I just want regex to output the following:

```<code>'Smith John'
'Jones, Greg'
'Doe'
</code>```

The current regex formula I have is as follows, except it will not capture the Doe example:

```<code>new = re.findall(r'([A-Z][\w-]*(?:\s+[A-Z][\w-]*)+)', s)
</code>```

答:
Regex is overkill. str.isupper() works quite well:

```<code>In [11]: def getName(s):
    ...:     first, second = s.split()[:2]
    ...:     if first[0].isupper():
    ...:         if second[0].isupper():
    ...:             return ' '.join([first, second])
    ...:         return first
    ...:
</code>```

This gives:

```<code>In [12]: getName('Smith John went to ss for Jones.')
Out[12]: 'Smith John'

In [13]: getName('Jones, Greg went to 2b for Smith.')
Out[13]: 'Jones, Greg'

In [14]: getName('Doe went to ss for Jones.')
Out[14]: 'Doe'
</code>```

Add in a couple of checks so that it doesn't error out when your string only has a single word, and you're good to go.

If you're bent on using regex, you can use a pattern like this:

```<code>In [36]: pattern = re.compile(r'([A-Z].*? ){1,2}')

In [37]: pattern.match('Smith John went to ss for Jones.').group(0).rstrip()
Out[37]: 'Smith John'

In [38]: pattern.match('Doe went to ss for Jones.').group(0).rstrip()
Out[38]: 'Doe'
</code>```

r'([A-Z].*? ){1,2}' will match the first, optionally the second, if they're capitalised.

Body:
The current regex formula I have implemented is only able to extract the first two capitalized words for a given string. I want to be able to extract just the first word in a string if the second word is not capitalized.

Here are some examples:

s = 'Smith John went to ss for Jones.'
s = 'Jones, Greg went to 2b for Smith.'
s = 'Doe went to ss for Jones.'

Essentially, I just want regex to output the following:

'Smith John'
'Jones, Greg'
'Doe'

The current regex formula I have is as follows, except it will not capture the Doe example:

new = re.findall(r'([A-Z][\w-]*(?:\s+[A-Z][\w-]*)+)', s)

Body:
Regex is overkill. str.isupper() works quite well:

In [11]: def getName(s):
    ...:     first, second = s.split()[:2]
    ...:     if first[0].isupper():
    ...:         if second[0].isupper():
    ...:             return ' '.join([first, second])
    ...:         return first
    ...:

This gives:

In [12]: getName('Smith John went to ss for Jones.')
Out[12]: 'Smith John'

In [13]: getName('Jones, Greg went to 2b for Smith.')
Out[13]: 'Jones, Greg'

In [14]: getName('Doe went to ss for Jones.')
Out[14]: 'Doe'

Add in a couple of checks so that it doesn't error out when your string only has a single word, and you're good to go.

If you're bent on using regex, you can use a pattern like this:

In [36]: pattern = re.compile(r'([A-Z].*? ){1,2}')

In [37]: pattern.match('Smith John went to ss for Jones.').group(0).rstrip()
Out[37]: 'Smith John'

In [38]: pattern.match('Doe went to ss for Jones.').group(0).rstrip()
Out[38]: 'Doe'

r'([A-Z].*? ){1,2}' will match the first, optionally the second, if they're capitalised.


答:
I'm just assuming you're doing something like:

```<code>var_dump("#" == 0);
// bool(true)
</code>```

When comparing to numbers, strings are cast into numbers to deal with situations like '123' == 123. The string '#', or in fact pretty much every non-numeric string, casts to 0.

That's why there's the === operator:

```<code>var_dump("#" === 0);
// bool(false)
</code>```

Welcome to weakly typed languages.

http://www.php.net/manual/en/language.types.type-juggling.php

Title: PHP char coding, #==0, 0==NULL, #!=NULL

Body:
I need to use a special character as a stop/break signal for my program. I was trying out '#' '&' '@' and kept on receiving errors.

After some messing around, I discovered that all characters including the ones above all had the numeric value 0! I did so by comparing their values with numerics, because at first I thought it used ASCII codes.

Wait a minute, that's not right, because NULL also equals to 0! But the characters definitely does not equal to NULL!

So, what kind of char coding does PHP use? Is it impossible to compare chars with numbers?

Thanks in advance!

Body:
I'm just assuming you're doing something like:

var_dump("#" == 0);
// bool(true)

When comparing to numbers, strings are cast into numbers to deal with situations like '123' == 123. The string '#', or in fact pretty much every non-numeric string, casts to 0.

That's why there's the === operator:

var_dump("#" === 0);
// bool(false)

Welcome to weakly typed languages.

http://www.php.net/manual/en/language.types.type-juggling.php


问:
Merge two lists and apply custom function while merging
So I have two lists which has similar properties for each item in the list. Each item is of the format -

```<code>public class ZoneOccupancy
{
    public virtual string ZoneId { get; set; }
    public virtual int CurrentOccupancy { get; set; }
}

ZoneId | CurrentOccupancy
</code>```

One list would be like -

```<code>ZoneId | CurrentOccupancy

110      2
111      1
115      3
</code>```

Another list would be like -

```<code>ZoneId | CurrentOccupancy

110      1
111      1
116      3
</code>```

After merging what I want is something like -

```<code>ZoneId | CurrentOccupancy

110      3
111      2
115      3
116      3
</code>```

So i want the duplicate items from the list to merge into one but in the process, the count to be added.

Edit:

```<code>list.Union(ParkingTagTicketQueryResult, ZoneComparer.Instance)
                         .GroupBy(z => z.ZoneId)
                         .Select(z => new ZoneOccupancy
                                        {
                                            ZoneId = z.First().ZoneId,
                                            CurrentOccupancy = z.Sum(row => row.CurrentOccupancy)

public class ZoneComparer : IEqualityComparer<ZoneOccupancy>
{
     public static readonly ZoneComparer Instance = new ZoneComparer();

     // We don't need any more instances
     private ZoneComparer() { }

     public int GetHashCode(ZoneOccupancy z)
     {
          return z.ZoneId.GetHashCode();
     }

     public bool Equals(ZoneOccupancy z1, ZoneOccupancy z2)
     {
          if (Object.ReferenceEquals(z1, z2))
          {
              return true;
          }

          if (Object.ReferenceEquals(z1, null) ||
              Object.ReferenceEquals(z2, null))
          {
              return false;
          }

          return z1.ZoneId.Equals(z2.ZoneId);
      }
</code>```

}

答:
One way to do it would be to simply start with one of the lists, and then, for each item in the other list either add the item if there's no match, or update the existing item if there is a match:

```<code>var list1 = new List<ZoneOccupancy>
{
    new ZoneOccupancy {ZoneId = 110, CurrentOccupancy = 2},
    new ZoneOccupancy {ZoneId = 111, CurrentOccupancy = 1},
    new ZoneOccupancy {ZoneId = 115, CurrentOccupancy = 3},
};

var list2 = new List<ZoneOccupancy>
{
    new ZoneOccupancy {ZoneId = 110, CurrentOccupancy = 1},
    new ZoneOccupancy {ZoneId = 111, CurrentOccupancy = 1},
    new ZoneOccupancy {ZoneId = 116, CurrentOccupancy = 3},
};

var mergedList = list1.ToList();

foreach (var item in list2)
{
    var match = mergedList.FirstOrDefault(i => i.ZoneId == item.ZoneId);
    if (match == null)
    {
        mergedList.Add(item);
    }
    else
    {
        match.CurrentOccupancy += item.CurrentOccupancy;
    }
}

// Output results
mergedList.ForEach(i =>
    Console.WriteLine($"Zone Id: {i.ZoneId}, Current Occupancy: {i.CurrentOccupancy}"));
</code>```

Output

Body:
So I have two lists which has similar properties for each item in the list. Each item is of the format -

public class ZoneOccupancy
{
    public virtual string ZoneId { get; set; }
    public virtual int CurrentOccupancy { get; set; }
}

ZoneId | CurrentOccupancy

One list would be like -

ZoneId | CurrentOccupancy

110      2
111      1
115      3

Another list would be like -

ZoneId | CurrentOccupancy

110      1
111      1
116      3

After merging what I want is something like -

ZoneId | CurrentOccupancy

110      3
111      2
115      3
116      3

So i want the duplicate items from the list to merge into one but in the process, the count to be added.

Edit:

list.Union(ParkingTagTicketQueryResult, ZoneComparer.Instance)
                         .GroupBy(z => z.ZoneId)
                         .Select(z => new ZoneOccupancy
                                        {
                                            ZoneId = z.First().ZoneId,
                                            CurrentOccupancy = z.Sum(row => row.CurrentOccupancy)

public class ZoneComparer : IEqualityComparer<ZoneOccupancy>
{
     public static readonly ZoneComparer Instance = new ZoneComparer();

     // We don't need any more instances
     private ZoneComparer() { }

     public int GetHashCode(ZoneOccupancy z)
     {
          return z.ZoneId.GetHashCode();
     }

     public bool Equals(ZoneOccupancy z1, ZoneOccupancy z2)
     {
          if (Object.ReferenceEquals(z1, z2))
          {
              return true;
          }

          if (Object.ReferenceEquals(z1, null) ||
              Object.ReferenceEquals(z2, null))
          {
              return false;
          }

          return z1.ZoneId.Equals(z2.ZoneId);
      }

}

Body:
One way to do it would be to simply start with one of the lists, and then, for each item in the other list either add the item if there's no match, or update the existing item if there is a match:

var list1 = new List<ZoneOccupancy>
{
    new ZoneOccupancy {ZoneId = 110, CurrentOccupancy = 2},
    new ZoneOccupancy {ZoneId = 111, CurrentOccupancy = 1},
    new ZoneOccupancy {ZoneId = 115, CurrentOccupancy = 3},
};

var list2 = new List<ZoneOccupancy>
{
    new ZoneOccupancy {ZoneId = 110, CurrentOccupancy = 1},
    new ZoneOccupancy {ZoneId = 111, CurrentOccupancy = 1},
    new ZoneOccupancy {ZoneId = 116, CurrentOccupancy = 3},
};

var mergedList = list1.ToList();

foreach (var item in list2)
{
    var match = mergedList.FirstOrDefault(i => i.ZoneId == item.ZoneId);
    if (match == null)
    {
        mergedList.Add(item);
    }
    else
    {
        match.CurrentOccupancy += item.CurrentOccupancy;
    }
}

// Output results
mergedList.ForEach(i =>
    Console.WriteLine($"Zone Id: {i.ZoneId}, Current Occupancy: {i.CurrentOccupancy}"));

Output


问:
Spring 4 MVC mechanism to connect to OAuth2 Provider's URL via HTTP Post
Am using Spring 4 MVC to create RESTful Web Services.

Need to use an HTTP Post to obtain an access token (by passing in an id and secret given from an OAuth provider):

curl command:

```<code>curl -X POST \
https://api.app.com/v1/oauth/token \
-H 'content-type: application/x-www-form-urlencoded' \
-d 'cliend_id=12354aaa&secret=423aaBCd’
</code>```

MyController:

```<code>@RestController
public class MyController {

    private static String url = "https://api.app.com/v1/oauth/token";
    private HttpHeaders headers = null;

    @Autowired
    public MyController() {
        headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
    }

    @RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, produces="application/json")
    public AccessToken getAccessToken(@RequestParam(value="client_id", required=true) String client_id, @RequestParam(value="secret", required=true) String secret) {
        AccessToken token = // How to get token from the response?
        return token;
    }
</code>```

}

Tried using this:

```<code>ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setAccessTokenUri("https://api.app.com/v1/oauth/token");
resourceDetails.setClientId("12354aaa");
resourceDetails.setClientSecret("423aaBCd");
resourceDetails.setGrantType("client_credentials");
resourceDetails.setScope(OAuthUtils.getScopesList("read", "write"));

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

oauth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);

OAuth2AccessToken token = oauth2RestTemplate.getAccessToken();
System.out.println(token);
</code>```

This returns:

```<code>Exception in thread "main" error="access_denied", error_description="Unable to obtain a new access token for resource 'null'. The provider manager is not configured to support it."
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:153)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:121)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
</code>```

(1) How can I get the accessToken from the OAuth Provider's URL from inside MyController's method?

(2) Is there a better way (Spring library or mechanism) which I can obtain the access token for each subsequent call (for example HTTP GET) like an automatic mechanism?

(3) Should I be using something else like RestTemplate to make these calls?

答:
you can try using RestTemplate
something like that</p>

```<code>private OAuth2RestTemplate template;

ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setAccessTokenUri("https://api.app.com/v1/oauth/token");
resourceDetails.setClientId(client_id);
resourceDetails.setClientSecret(secret);

resourceDetails.setGrantType("password");
resourceDetails.setUsername("**USERNAME**");
resourceDetails.setPassword("**PASSWORD**");

resourceDetails.setScope(asList("read", "write"));

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

template = new OAuth2RestTemplate(resourceDetails, clientContext);

token = template.getAccessToken();
</code>```

Body:
Am using Spring 4 MVC to create RESTful Web Services.

Need to use an HTTP Post to obtain an access token (by passing in an id and secret given from an OAuth provider):

curl command:

curl -X POST \
https://api.app.com/v1/oauth/token \
-H 'content-type: application/x-www-form-urlencoded' \
-d 'cliend_id=12354aaa&secret=423aaBCd’

MyController:

@RestController
public class MyController {

    private static String url = "https://api.app.com/v1/oauth/token";
    private HttpHeaders headers = null;

    @Autowired
    public MyController() {
        headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
    }

    @RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, produces="application/json")
    public AccessToken getAccessToken(@RequestParam(value="client_id", required=true) String client_id, @RequestParam(value="secret", required=true) String secret) {
        AccessToken token = // How to get token from the response?
        return token;
    }

}

Tried using this:

ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setAccessTokenUri("https://api.app.com/v1/oauth/token");
resourceDetails.setClientId("12354aaa");
resourceDetails.setClientSecret("423aaBCd");
resourceDetails.setGrantType("client_credentials");
resourceDetails.setScope(OAuthUtils.getScopesList("read", "write"));

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

oauth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);

OAuth2AccessToken token = oauth2RestTemplate.getAccessToken();
System.out.println(token);

This returns:

Exception in thread "main" error="access_denied", error_description="Unable to obtain a new access token for resource 'null'. The provider manager is not configured to support it."
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:153)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:121)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)

(1) How can I get the accessToken from the OAuth Provider's URL from inside MyController's method?

(2) Is there a better way (Spring library or mechanism) which I can obtain the access token for each subsequent call (for example HTTP GET) like an automatic mechanism?

(3) Should I be using something else like RestTemplate to make these calls?

Body:
you can try using RestTemplate
something like that

private OAuth2RestTemplate template;

ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setAccessTokenUri("https://api.app.com/v1/oauth/token");
resourceDetails.setClientId(client_id);
resourceDetails.setClientSecret(secret);

resourceDetails.setGrantType("password");
resourceDetails.setUsername("**USERNAME**");
resourceDetails.setPassword("**PASSWORD**");

resourceDetails.setScope(asList("read", "write"));

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

template = new OAuth2RestTemplate(resourceDetails, clientContext);

token = template.getAccessToken();


问:
Pygal render SVG in Jupyter Notebooks
Im currently using Jupyter Notebooks and I would like to render SVG's via HTML without saving them as a local SVG and display them afterwards.

Im using this code:

```<code>%matplotlib inline
from IPython.display import SVG, HTML
html_pygal = """
<!DOCTYPE html>
<html>
  <head>
  <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/svg.jquery.js"></script>
  <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/pygal-tooltips.js"></script>
    <!-- ... -->
  </head>
  <body>
    <figure>
      {pygal_render}
    </figure>
  </body>
</html>
"""

import pygal
line_chart = pygal.Line()
line_chart.title = 'Browser usage evolution (in %)'
line_chart.x_labels = map(str, range(2002, 2013))
line_chart.add('Firefox', [None, None,    0, 16.6,   25,   31, 36.4, 45.5, 46.3, 42.8, 37.1])
line_chart.add('Chrome',  [None, None, None, None, None, None,    0,  3.9, 10.8, 23.8, 35.3])
line_chart.add('IE',      [85.8, 84.6, 84.7, 74.5,   66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])
line_chart.add('Others',  [14.2, 15.4, 15.3,  8.9,    9, 10.4,  8.9,  5.8,  6.7,  6.8,  7.5])
HTML(html_pygal.format(pygal_render=line_chart.render()))
</code>```

Here is the problem: While Jupyter manages to render the SVG file it also displays a Javascript error which looks like follows:

b'\n

*SVG picture comes here

'
Javascript error adding output!
SyntaxError: illegal character
See your browser Javascript console for more details.

When checking the browser console this is the error message:

```<code>loaded custom.js  2017-04-20_analytics.ipynb:121:15
Default extension for cell metadata editing loaded.  main.min.js:24261:9
Raw Cell Format toolbar preset loaded.  main.min.js:24347:5
Slideshow extension for metadata editing loaded.  main.min.js:24395:9
actions jupyter-notebook:find-and-replace does not exist, still binding it in case it will be defined later...  main.min.js:29204:17
load_extensions Arguments { 0: "jupyter-js-widgets/extension", 2 weitere… }  main.min.js:12231:9
Session: kernel_created (b51341fe-f4d8-42be-a9b8-46ac47476a99)  main.min.js:23547:13
Starting WebSockets: ws://localhost:8888/api/kernels/1852f19e-52f2-4ce2-91d8-f6276ea95b40  main.min.js:22833:9
Loading extension: jupyter-js-widgets/extension  main.min.js:12208:21
Kernel: kernel_connected (1852f19e-52f2-4ce2-91d8-f6276ea95b40)  main.min.js:22480:13
Kernel: kernel_ready (1852f19e-52f2-4ce2-91d8-f6276ea95b40)  main.min.js:22480:13
loaded widgets  extension.js:134:14
Widget backend and frontend versions are compatible  extension.js:32280:22
SyntaxError: illegal character
Stack-Trace:
globalEval@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:4231
domManip@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:21389
append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:18980
OutputArea.prototype._safe_append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20345:13
OutputArea.prototype.append_execute_result@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20372:9
OutputArea.prototype.append_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20218:17
OutputArea.prototype.handle_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20165:9
output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:21820:21
Kernel.prototype._handle_output_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23440:13
i@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:5486
Kernel.prototype._handle_iopub_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23467:20
Kernel.prototype._finish_ws_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23304:24
Kernel.prototype._handle_ws_message/this._msg_queue<@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23295:39
  main.min.js:20347:13
SyntaxError: illegal character
Stack-Trace:
globalEval@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:4231
domManip@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:21389
append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:18980
OutputArea.prototype._safe_append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20345:13
OutputArea.prototype.append_execute_result@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20372:9
OutputArea.prototype.append_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20218:17
OutputArea.prototype.handle_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20165:9
output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:21820:21
Kernel.prototype._handle_output_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23440:13
i@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:5486
Kernel.prototype._handle_iopub_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23467:20
Kernel.prototype._finish_ws_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23304:24
Kernel.prototype._handle_ws_message/this._msg_queue<@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23295:39
</code>```

My Python Version:
3.6.0
OS: Windows 7 64 Bit
Pygal Version: 2.3.1

Note: my current workaround which works but is not the solution which I'm looking for is to create a local SVG and then display it with the library import: from IPython.display import display

答:
Try to use "is_unicode=True" inside render, like this:</p>

```<code>HTML(html_pygal.format(pygal_render=line_chart.render(is_unicode=True)))
</code>```

Title: Pygal render SVG in Jupyter Notebooks

Body:
Im currently using Jupyter Notebooks and I would like to render SVG's via HTML without saving them as a local SVG and display them afterwards.

Im using this code:

%matplotlib inline
from IPython.display import SVG, HTML
html_pygal = """
<!DOCTYPE html>

      {pygal_render}

"""

import pygal
line_chart = pygal.Line()
line_chart.title = 'Browser usage evolution (in %)'
line_chart.x_labels = map(str, range(2002, 2013))
line_chart.add('Firefox', [None, None,    0, 16.6,   25,   31, 36.4, 45.5, 46.3, 42.8, 37.1])
line_chart.add('Chrome',  [None, None, None, None, None, None,    0,  3.9, 10.8, 23.8, 35.3])
line_chart.add('IE',      [85.8, 84.6, 84.7, 74.5,   66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])
line_chart.add('Others',  [14.2, 15.4, 15.3,  8.9,    9, 10.4,  8.9,  5.8,  6.7,  6.8,  7.5])
HTML(html_pygal.format(pygal_render=line_chart.render()))

Here is the problem: While Jupyter manages to render the SVG file it also displays a Javascript error which looks like follows:

b'\n

*SVG picture comes here

'
Javascript error adding output!
SyntaxError: illegal character
See your browser Javascript console for more details.

When checking the browser console this is the error message:

loaded custom.js  2017-04-20_analytics.ipynb:121:15
Default extension for cell metadata editing loaded.  main.min.js:24261:9
Raw Cell Format toolbar preset loaded.  main.min.js:24347:5
Slideshow extension for metadata editing loaded.  main.min.js:24395:9
actions jupyter-notebook:find-and-replace does not exist, still binding it in case it will be defined later...  main.min.js:29204:17
load_extensions Arguments { 0: "jupyter-js-widgets/extension", 2 weitere… }  main.min.js:12231:9
Session: kernel_created (b51341fe-f4d8-42be-a9b8-46ac47476a99)  main.min.js:23547:13
Starting WebSockets: ws://localhost:8888/api/kernels/1852f19e-52f2-4ce2-91d8-f6276ea95b40  main.min.js:22833:9
Loading extension: jupyter-js-widgets/extension  main.min.js:12208:21
Kernel: kernel_connected (1852f19e-52f2-4ce2-91d8-f6276ea95b40)  main.min.js:22480:13
Kernel: kernel_ready (1852f19e-52f2-4ce2-91d8-f6276ea95b40)  main.min.js:22480:13
loaded widgets  extension.js:134:14
Widget backend and frontend versions are compatible  extension.js:32280:22
SyntaxError: illegal character
Stack-Trace:
globalEval@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:4231
domManip@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:21389
append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:18980
OutputArea.prototype._safe_append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20345:13
OutputArea.prototype.append_execute_result@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20372:9
OutputArea.prototype.append_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20218:17
OutputArea.prototype.handle_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20165:9
output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:21820:21
Kernel.prototype._handle_output_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23440:13
i@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:5486
Kernel.prototype._handle_iopub_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23467:20
Kernel.prototype._finish_ws_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23304:24
Kernel.prototype._handle_ws_message/this._msg_queue<@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23295:39
  main.min.js:20347:13
SyntaxError: illegal character
Stack-Trace:
globalEval@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:4231
domManip@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:21389
append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:88:18980
OutputArea.prototype._safe_append@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20345:13
OutputArea.prototype.append_execute_result@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20372:9
OutputArea.prototype.append_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20218:17
OutputArea.prototype.handle_output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:20165:9
output@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:21820:21
Kernel.prototype._handle_output_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23440:13
i@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:87:5486
Kernel.prototype._handle_iopub_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23467:20
Kernel.prototype._finish_ws_message@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23304:24
Kernel.prototype._handle_ws_message/this._msg_queue<@http://localhost:8888/static/notebook/js/main.min.js?v=edbc43d9bb99b1be2585a121ed720314:23295:39

My Python Version:
3.6.0
OS: Windows 7 64 Bit
Pygal Version: 2.3.1

Note: my current workaround which works but is not the solution which I'm looking for is to create a local SVG and then display it with the library import: from IPython.display import display

Body:
Try to use "is_unicode=True" inside render, like this:

HTML(html_pygal.format(pygal_render=line_chart.render(is_unicode=True)))


问:
SPARQL query for some kind of START WITH and CONNECT BY (Oracle)
I'm busy with a proof of concept working with a triple store. I have the following structure:

There are 2 relation types defined (triples). Top-down relation where the child is part of ("isPartOf" its parent and left-right where there are childs that CAN (optional) be replaced ("replaces") by another version of the child.

Also every child have a "isValidStart" triple with a date as object. This means that this child is valid since that date.
The last child in a horizontal childgroup can have a relation "isInvalidEnd" that means that after this date this group is invalid.

What I want to do is to build a SPARQL query where I can get the childs of a parent on a specific date. Is that possible with SPARQL and how can I do that?

I know that there is in Oracle any kind of START WITH / CONNECT BY function that do some kind of this stuff...but how do I this in SPARQL world.

Thanks

</metadata/puid/test2> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test1" .
</metadata/puid/test2> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test3> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test2" .
</metadata/puid/test3> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test4> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test3" .
</metadata/puid/test4> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test5> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test4" .
</metadata/puid/test5> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test6> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test4" .
</metadata/puid/test6> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test7> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test4" .
</metadata/puid/test7> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test8> <http://purl.org/dc/terms/replaces> "/metadata/puid/test7" .
</metadata/puid/test8> <http://purl.org/dc/terms/isValidStart> "2015-07-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test9> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test5" .
</metadata/puid/test9> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test10> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test5" .
</metadata/puid/test10> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test11> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test5" .
</metadata/puid/test11> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test12> <http://purl.org/dc/terms/replaces> "/metadata/puid/test9" .
</metadata/puid/test12> <http://purl.org/dc/terms/isValidStart> "2015-07-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test13> <http://purl.org/dc/terms/replaces> "/metadata/puid/test10" .
</metadata/puid/test13> <http://purl.org/dc/terms/isValidStart> "2015-05-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test14> <http://purl.org/dc/terms/replaces> "/metadata/puid/test13" .
</metadata/puid/test14> <http://purl.org/dc/terms/isValidStart> "2015-08-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test14> <http://purl.org/dc/terms/isValidEnd> "2015-12-01"^^<http://www.w3.org/2001/XMLSchema#date> .
```

// disclaimer: I'm new in SPARQL world

答:
Not totally sure if this is what you're asking for but comments inline:

Given date: "2015-04-01"^^xsd:date

PREFIX : <http://purl.org/dc/terms/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

SELECT  ?child
WHERE
  {
   # we have two options to check
   # 1. all children that have not been replaced
      {
        # get the valid start values
        ?child  :isValidStart  ?start
        # where the start was before the given date
        FILTER ( ?start < "2015-04-01"^^xsd:date )
        # and there was no other replacing child
        FILTER NOT EXISTS { ?otherChild  :replaces  ?child }
      }
    UNION
   # 2. children that haven been replaced
      {
        # start date of children that replace others
        ?child  :isValidStart  ?start ;
                :replaces      ?someChild
        # but haven not been replaced themselves
        FILTER NOT EXISTS { ?otherChild  :replaces  ?child }
        # where the start was before the given date
        FILTER(?start < "2015-04-01"^^xsd:date)
        # and there isn't an end date before the given date
        FILTER NOT EXISTS { ?child  :isValidEnd  ?end
                            FILTER ( ?end < "2015-04-01"^^xsd:date )
                          }
      }
  }
```

Body:
I'm busy with a proof of concept working with a triple store. I have the following structure:

There are 2 relation types defined (triples). Top-down relation where the child is part of ("isPartOf" its parent and left-right where there are childs that CAN (optional) be replaced ("replaces") by another version of the child.

Also every child have a "isValidStart" triple with a date as object. This means that this child is valid since that date.
The last child in a horizontal childgroup can have a relation "isInvalidEnd" that means that after this date this group is invalid.

What I want to do is to build a SPARQL query where I can get the childs of a parent on a specific date. Is that possible with SPARQL and how can I do that?

I know that there is in Oracle any kind of START WITH / CONNECT BY function that do some kind of this stuff...but how do I this in SPARQL world.

Thanks

</metadata/puid/test2> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test1" .
</metadata/puid/test2> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test3> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test2" .
</metadata/puid/test3> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test4> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test3" .
</metadata/puid/test4> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test5> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test4" .
</metadata/puid/test5> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test6> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test4" .
</metadata/puid/test6> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test7> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test4" .
</metadata/puid/test7> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test8> <http://purl.org/dc/terms/replaces> "/metadata/puid/test7" .
</metadata/puid/test8> <http://purl.org/dc/terms/isValidStart> "2015-07-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test9> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test5" .
</metadata/puid/test9> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test10> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test5" .
</metadata/puid/test10> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test11> <http://purl.org/dc/terms/isPartOf> "/metadata/puid/test5" .
</metadata/puid/test11> <http://purl.org/dc/terms/isValidStart> "2015-04-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test12> <http://purl.org/dc/terms/replaces> "/metadata/puid/test9" .
</metadata/puid/test12> <http://purl.org/dc/terms/isValidStart> "2015-07-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test13> <http://purl.org/dc/terms/replaces> "/metadata/puid/test10" .
</metadata/puid/test13> <http://purl.org/dc/terms/isValidStart> "2015-05-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test14> <http://purl.org/dc/terms/replaces> "/metadata/puid/test13" .
</metadata/puid/test14> <http://purl.org/dc/terms/isValidStart> "2015-08-01"^^<http://www.w3.org/2001/XMLSchema#date> .
</metadata/puid/test14> <http://purl.org/dc/terms/isValidEnd> "2015-12-01"^^<http://www.w3.org/2001/XMLSchema#date> .

// disclaimer: I'm new in SPARQL world


问:
inject programming code into iphone app
I saw in this article you can run some javascript in a UIWebView:
http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview

It would be great if I could inject some business logic into my app based on a few parameters I have or be able to customize it on the fly via the web by downloading updated code that would become part of the app.

has anyone done this or is this even a possibility?

答:
I would advise you to avoid doing it. Any app that downloads code will get rejected on the App Store.

From the App Store Review Guidelines:

2.7 Apps that download code in any way or form will be rejected

Title: inject programming code into iphone app


问:
Complex branching and merging in history TFS
It is possible to create a branch from a historic changeset. The situation that I have now is that I have created a branch of a repository from a (for example) 3 months ago. After that I have created the branch, I want to  and I want to merge only specific changesets from 1 month ago, and want to keep the rest of the branch the same.

When I try to tell visual studio (source control explorer) that I want to merge specific changesets to that new branch, the changeset of the previous months are not shown. Is there any other way than manual work to merge the changes of the specific changeset on the historic branch that I have created?

答: Using Source Control Explorer (View->Other windows-> source control explorer) right click on your repository, select "Branching and merging", then "Merge", once the Source Control Merge Wizard windows show you should see two options: "All changes up to a specific version" and "Selected Changeset", select "selected changeset" and choose your source and target branches. This window will give you a list that contains specific changesets that have been checked in to the source branch but not merge into the target branch, keep in mind that you can select contiguous set of changes to move in this merge operation, I hope this helps</p>


问:
Test scenarios for tip webhook test
I am developing a new feature, which will listen to tip notifications on venues, and I am having trouble to test it.
As far as I could check, to create a venue, and subscribe it on my foursquare app, I need to pay.

Is there any alternative to simulate or test, tip notifications?
On the app there is a test button, that only send checkin notifications.
I need to test it on dev environment before sending an untested code to production.

答:
After exchanging several emails with api@foursquare.com, they set me as a manager of a venue I created on http://foursquare.com/add-place, and finally I could move on with my tests.

I strongly recommend to Foursquare to create some kind of test for all possible Real Time API notifications, or create some kind of sandbox.

Thanks.

Title: Test scenarios for tip webhook test


问:
using .reduce() on an a list of objects
I have this sample data set:

```<code>let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]
</code>```

I am trying to end up with this:

```<code>[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
</code>```

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

```<code>let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])
</code>```

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

```<code>let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])
</code>```

答:
Just in case you're also looking for a non reduce solution.

Here is one. It is a bit long winded but that is because I'm trying to decompose the problem into a few parts.

I first go through the list and sort the elements into their respective Id.

Then For each id in the sorted object. I loop through it again by first instantiating an outer element first.

Pushed the id key into the element first.

Loop through all the associated element and extract their first property and add it into the nested element.

Once the nesting element is been built. I just merge them up into the parent element and attach it into the result array.

Hopfully it is not too complicated for you but I suspect it will be easier to see the code in action through an IDE.

var list = [
    {'first': 'morgan', 'id': 1},
    {'first': 'eric', 'id': 1},
    {'first': 'brian', 'id': 2 },
    {'first': 'derek', 'id' : 2},
    {'first': 'courtney', 'id': 3},
    {'first': 'eric', 'id': 4},
    {'first': 'jon', 'id':4},
]

var result = [];
var keyById = {};

// Sort the list of items to be keyed by: Id => [ item, item ]
list.forEach(function(item) {
    if (!keyById.hasOwnProperty(item.id)) {
        keyById[item.id] = [];
    }
    keyById[item.id].push(item);
});

// Build the data structure
for (var id in keyById) {
    var item = []; // The outer element
    var nestedItem = []; // The nested element belonging to the outer
    item.push(id);
    keyById[id].forEach(function(element) {
        nestedItem.push(element.first);
    });
    item.push(nestedItem);
    result.push(item);
}

console.log(JSON.stringify(result, '', 2));```

Title: using .reduce() on an a list of objects

Body:
I have this sample data set:

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

I am trying to end up with this:

[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])