问:
Bluring the Image which is under specific Heading using Python docx
I am planning to search the specific heading in the document, and then i have to strike out all the contents in that heading. The document has many headings, each heading may have paragraph, tables, images altogether or in any combinations.

I have installed docx, i was able to search the specific heading, strike out paragraph, tables.

Now i am not able to access the images under that Heading. To indicate that, the image is strikeout, we are trying to blur the image

Problem 1: I am able to get the Image ID (Resource ID), Image Name for all the images in the document. But i don't know how to get the resource id for the images which is under Specific Heading, and then i have to blur it.

Problem 2: I have enabled Track Changes option using VBMacro from python code. But whatever changes i did using docx (strikeout) is not highlighted for Tracking.

答:
These are two separate questions (or three, depending on how you count). I'll address the first one here, you can post the other question as a separate new question. (Maybe: "How use python-pptx to track changes in Word document").

Regarding blurring the image, you have two challenges:

Identify images associated with a particular area in the document.

Blur the image.

There is no direct API support for either of these operations in python-docx. However, you can use python-docx to access the underlying XML and make the changes using lxml calls (which python-docx uses internally). Such efforts are commonly called "workaround functions", so if you search Google on 'python-docx OR python-pptx workaround function' you will find examples.

An in-line image is stored at the Run level. So you can iterate over all the runs in the section of interest and see if any of them have images. This analysis page from the python-docx project has some of the details you'll need: http://python-docx.readthedocs.io/en/latest/dev/analysis/features/shapes/shapes-inline.html

Basically you'd do something like this:

```<code>for run in runs:  # however you decide to get the runs
    r = run._element  # this is the `<w:r>` XML element for the run
    pics = r.xpath('.//w:drawing/wp:inline/a:graphic/a:graphicData/pic:pic')
    if not pics:
        break
    print(r.xml)  # if you want to see the XML for this run
</code>```

This will print the XML for run elements containing a picture.

Regarding the actual blurring, there are two approaches I can think of:

Replace the current picture with a "blurred" version.

Change the transparency of the image in Word to make it look much lighter. This does not remove detail from the image and the actual image is still "behind", unchanged, if for example the user wanted to right click and pick "Save image...".

The second approach is much easier. You'll have to decide whether it meets your requirements.

Once you decide which way you want to go you can search for solutions to that problem or submit a new question focused on that topic.

Body:
These are two separate questions (or three, depending on how you count). I'll address the first one here, you can post the other question as a separate new question. (Maybe: "How use python-pptx to track changes in Word document").

Regarding blurring the image, you have two challenges:

Identify images associated with a particular area in the document.

Blur the image.

There is no direct API support for either of these operations in python-docx. However, you can use python-docx to access the underlying XML and make the changes using lxml calls (which python-docx uses internally). Such efforts are commonly called "workaround functions", so if you search Google on 'python-docx OR python-pptx workaround function' you will find examples.

An in-line image is stored at the Run level. So you can iterate over all the runs in the section of interest and see if any of them have images. This analysis page from the python-docx project has some of the details you'll need: http://python-docx.readthedocs.io/en/latest/dev/analysis/features/shapes/shapes-inline.html

Basically you'd do something like this:

for run in runs:  # however you decide to get the runs
    r = run._element  # this is the `<w:r>` XML element for the run
    pics = r.xpath('.//w:drawing/wp:inline/a:graphic/a:graphicData/pic:pic')
    if not pics:
        break
    print(r.xml)  # if you want to see the XML for this run

This will print the XML for run elements containing a picture.

Regarding the actual blurring, there are two approaches I can think of:

Replace the current picture with a "blurred" version.

Change the transparency of the image in Word to make it look much lighter. This does not remove detail from the image and the actual image is still "behind", unchanged, if for example the user wanted to right click and pick "Save image...".

The second approach is much easier. You'll have to decide whether it meets your requirements.

Once you decide which way you want to go you can search for solutions to that problem or submit a new question focused on that topic.


来源: stackexchange

问:
Laravel composer and package discover
In a new project after cloned it and run composer install I have:

```<code>Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cryptoreview.out
going_links' doesn't exist (SQL: select * from `outgoing_links`)

[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cryptoreview.out
going_links' doesn't exist

[PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cryptoreview.out
going_links' doesn't exist
</code>```

what exactly is trying to do package:discover?

I tried to fix running php artisan migrate but:

```<code>  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cryptoreview.outgoing_links' doesn't exist (SQL: select * from `outgoing_links`)
</code>```

It is a complete blocked situation. No way to proceed further

答: Try running composer global update in your terminal to update your composer. And for base table not found, make sure your table migration is Schema::create not Schema::table. Don't forget function up and down with the same name of table.

ContentLicense: CC BY-SA 3.0

Title: Laravel composer and package discover

Body:
In a new project after cloned it and run composer install I have:

Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cryptoreview.out
going_links' doesn't exist (SQL: select * from `outgoing_links`)

[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cryptoreview.out
going_links' doesn't exist

[PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cryptoreview.out
going_links' doesn't exist

what exactly is trying to do package:discover?

I tried to fix running php artisan migrate but:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cryptoreview.outgoing_links' doesn't exist (SQL: select * from `outgoing_links`)

It is a complete blocked situation. No way to proceed further


问:
waiting for a PathTransition to finish until returning from a function in JavaFX
I'm trying to implement a program like this using JavaFX:

We have a number of objects of Type Foo on the scene (which are shown by circles).

Each one of them has a method called move() which would move the object to another location on the scene. Then it finds another object (by calling another method) and calls the move method on the found object. It's something like this:

```<code>class Foo {
    Circle circle;
    void move() {
        // change circle location
        // HERE, I WANT TO WAIT UNTIL CIRCLE HAS MOVED ON THE SCENE
        Foo f = findNextFoo();
        foo.move();
    }
}
</code>```

I want the circles' movements to be visible and sequential to the user, but when I use PathTransition regularly, all of the objects move at (almost) the same time, since each PathTransition is running on a new thread and after its play(), function will continue and calls findNextFoo() method.

I have tried to use setOnFinished for PathTransition to change a flag when it has finished, and then using a while(true) to wait until the flag has been set to true and then called foo.move() method. This also doesn't work and makes my program crash.

Thread.sleep() also doesn't work the way I want (all the movements are done after a delay but at the same time).

Any help would be appreciated, thanks.

答:
You must not block the application thread like you do if you use while(true) or Thread.sleep.

You could use SequentialTransition if you're able to determine all transitions in advance.

However using the onFinished event would probably require less modification of the code. Simply start the next transition from the event handler instead of using a flag+infinite loop:

```<code>void move() {
    PathTransition transition = ...

    transition.setOnFinished(event -> {
        // after transition is finished continue with next one
        Foo f = findNextFoo();
        foo.move();
    });
    transition.play();
}
</code>```

Body:
I'm trying to implement a program like this using JavaFX:

We have a number of objects of Type Foo on the scene (which are shown by circles).

Each one of them has a method called move() which would move the object to another location on the scene. Then it finds another object (by calling another method) and calls the move method on the found object. It's something like this:

class Foo {
    Circle circle;
    void move() {
        // change circle location
        // HERE, I WANT TO WAIT UNTIL CIRCLE HAS MOVED ON THE SCENE
        Foo f = findNextFoo();
        foo.move();
    }
}

I want the circles' movements to be visible and sequential to the user, but when I use PathTransition regularly, all of the objects move at (almost) the same time, since each PathTransition is running on a new thread and after its play(), function will continue and calls findNextFoo() method.

I have tried to use setOnFinished for PathTransition to change a flag when it has finished, and then using a while(true) to wait until the flag has been set to true and then called foo.move() method. This also doesn't work and makes my program crash.

Thread.sleep() also doesn't work the way I want (all the movements are done after a delay but at the same time).

Any help would be appreciated, thanks.

Body:
You must not block the application thread like you do if you use while(true) or Thread.sleep.

You could use SequentialTransition if you're able to determine all transitions in advance.

However using the onFinished event would probably require less modification of the code. Simply start the next transition from the event handler instead of using a flag+infinite loop:

void move() {
    PathTransition transition = ...

    transition.setOnFinished(event -> {
        // after transition is finished continue with next one
        Foo f = findNextFoo();
        foo.move();
    });
    transition.play();
}


问:
powershell how to remove `{}@` from output. Is there a special command to do it?
I entered gwmi win32_product | select -property name | select -first 1 and output to a file. My result was @{name=Google Talk Plugin}.

How can I get rid of @{}, and name. I only want it to show Google Talk Plugin?

答:
```<code>I ran into a problem similar with
$drive = Get-WmiObject Win32_LogicalDisk -ComputerName $servername | Select-Object DeviceID
$drive comes up as @{DeviceID=C:}, @{DeviceID=D:}, ...
Here is my brute force hack at it.
The second Trim statement was because for some reason if I put it in the first Trim it starts to Trim the letters in the Drive  =D: becomes :

enter code here
$Asdrive = @()   #declared before to get rid of null pointer issue, also to tell PS this is an array not a string

    #Write-Host "Trimming for Get-WmiObject"
for($i=0;$i -lt $drive.length; $i++) {
 [string]$sdrive = $drive[$i]
 [string]$sdrive1 = $sdrive.Trim("@","{","}","D","e","v","i","c","e","I","D")
 [string]$sdrive2 = $sdrive1.Trim("=")
 $Asdrive += $sdrive2
 }
</code>```


问:
Need a Regex to Parse This Line 58.21 -13.73 57 -1
Need help parsing the numbers from this line in Lua.

```<code>58.21 -13.73 57 -1
</code>```

I currently am at this: [1-9][0-9] which I know is not correct as it does not return the minus and does not handle the decimal.

Thanks,

Dave

答:
I'm assuming by "parse" you mean, you want a Regular Expression that will match a number. In the string you provided, you would want the matches to be:

58.21

-13.73

57

-1

The pattern I would probably use is ([^ ]+). It will find anything except for space, which, in your string, would be numbers with (potentially) decimal points and signs.

ContentLicense: CC BY-SA 2.5

Body:
Need help parsing the numbers from this line in Lua.

58.21 -13.73 57 -1

I currently am at this: [1-9][0-9] which I know is not correct as it does not return the minus and does not handle the decimal.

Thanks,

Dave


问:
VS Ordered Tests with Selenium WebDriver won't continue after first test due to ChomeDriver closing
So I have setup an automation framework and for each test that I want to run, I have created their own Unit Test. During our smoke test, we run through several of the Unit Tests that I've built in order. Therefor, I figured it would be a good idea to create an Ordered Test. When running each test individually, they work just fine. However, once I start running the Ordered Tests, the first test in the list will run, but then I get this error:

OpenQA.Selenium.WebDriverException: Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it

I have tracked this problem to be caused because the ChromeDriver is closing at the end of the first test. However, even if I tell it not to close the driver, it seems to close it. If I tell the [SetUp] of each Unit Test to create a new driver, it doesn't seem to work either.

I have setup the code like this for now:

```<code>public static IWebDriver getWebDriver()
{
    IWebDriver newDriver = new ChromeDriver(@"..\..\..\packages\Selenium.Chrome.WebDriver.2.33\driver");

    return newDriver;
}

public static IWebDriver webDriver;
</code>```

Then from the Unit Tests I'm setting the webDriver = getWebDriver() which should cause it to create a new one. I have also tried creating multiple [TestMethod] in a single Unit Test, but it still ends up giving me the same error. I'm really at a loss about what I should be doing at this point and am fairly new with no peers to guide me at work. Any direction would be greatly appreciated!

答:
I have had similar errors. At first I believed that the error was with the chromedriver but after many hours of investigation I discovered that when I saw this error is was one of 2 things:

Chrome version vs chromedriver version vs selenium version.
So the first thing (which you've probably already done) is to make sure you have the latest and greatest versions of the nuget packages. (Chrome of course takes care of it's own updates--which is usually what causes the problem).

Carefully look at your code and make sure you have an application level "Try Catch". This article from Microsoft should help.

What I found in my own code was what looked like a chromedriver issue was really an issue with timing when moving from one page to another. Now I have methods to verify I'm on the right page and have methods that verify page elements exist before I attempt to use them. I end up writing a lot of:

```<code> if (driver.PageSource.Contains("Some text that means the page is loaded"))
</code>```

I also add a small amount of wait time behind each interaction of the page which can take time. You'll want to make sure every element you use exists before you attempt to use it. I do that like this:

```<code> if (IsElementDisplayed(driver, By.XPath(Settings.Default.X_GenerateButton)))
 {
      //click the generate button
      driver.FindElement(By.XPath(Settings.Default.X_GenerateButton)).Click();

      //wait for a couple of seconds
      Thread.Sleep(2000);

 }
</code>```

Here's what my IsElementDisplayed method looks like:

```<code> public bool IsElementDisplayed(IWebDriver driver, By element)
 {

        for (int i = 1; i <= 5; i++)
        {
            try
            {
                IReadOnlyCollection<IWebElement> elements = driver.FindElements(element);
                if (elements.Count > 0)
                {
                    return elements.ElementAt(0).Displayed;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception was raised on locating element: " + e.Message);
                Thread.Sleep(1000);
            }
        }
        return false;
 }
</code>```

Hope this helps, good luck tracking down the issue.

Body:
So I have setup an automation framework and for each test that I want to run, I have created their own Unit Test. During our smoke test, we run through several of the Unit Tests that I've built in order. Therefor, I figured it would be a good idea to create an Ordered Test. When running each test individually, they work just fine. However, once I start running the Ordered Tests, the first test in the list will run, but then I get this error:

OpenQA.Selenium.WebDriverException: Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it

I have tracked this problem to be caused because the ChromeDriver is closing at the end of the first test. However, even if I tell it not to close the driver, it seems to close it. If I tell the [SetUp] of each Unit Test to create a new driver, it doesn't seem to work either.

I have setup the code like this for now:

public static IWebDriver getWebDriver()
{
    IWebDriver newDriver = new ChromeDriver(@"..\..\..\packages\Selenium.Chrome.WebDriver.2.33\driver");

    return newDriver;
}

public static IWebDriver webDriver;

Then from the Unit Tests I'm setting the webDriver = getWebDriver() which should cause it to create a new one. I have also tried creating multiple [TestMethod] in a single Unit Test, but it still ends up giving me the same error. I'm really at a loss about what I should be doing at this point and am fairly new with no peers to guide me at work. Any direction would be greatly appreciated!

Body:
I have had similar errors. At first I believed that the error was with the chromedriver but after many hours of investigation I discovered that when I saw this error is was one of 2 things:

Chrome version vs chromedriver version vs selenium version.
So the first thing (which you've probably already done) is to make sure you have the latest and greatest versions of the nuget packages. (Chrome of course takes care of it's own updates--which is usually what causes the problem).

Carefully look at your code and make sure you have an application level "Try Catch". This article from Microsoft should help.

What I found in my own code was what looked like a chromedriver issue was really an issue with timing when moving from one page to another. Now I have methods to verify I'm on the right page and have methods that verify page elements exist before I attempt to use them. I end up writing a lot of:

 if (driver.PageSource.Contains("Some text that means the page is loaded"))

I also add a small amount of wait time behind each interaction of the page which can take time. You'll want to make sure every element you use exists before you attempt to use it. I do that like this:

 if (IsElementDisplayed(driver, By.XPath(Settings.Default.X_GenerateButton)))
 {
      //click the generate button
      driver.FindElement(By.XPath(Settings.Default.X_GenerateButton)).Click();

      //wait for a couple of seconds
      Thread.Sleep(2000);

 }

Here's what my IsElementDisplayed method looks like:

 public bool IsElementDisplayed(IWebDriver driver, By element)
 {

        for (int i = 1; i <= 5; i++)
        {
            try
            {
                IReadOnlyCollection<IWebElement> elements = driver.FindElements(element);
                if (elements.Count > 0)
                {
                    return elements.ElementAt(0).Displayed;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception was raised on locating element: " + e.Message);
                Thread.Sleep(1000);
            }
        }
        return false;
 }

Hope this helps, good luck tracking down the issue.


问:
Can I use other python implementation via virtualenv/virtualenvwrapper?
After a while of searching (maybe it's not enough, but I don't think I'm making progress doing that), I haven't been able to find information about compatibility of other Python implementations in virtualenv/virtualenvwrapper.
By "other implementation" I mean things like PyPy, IronPython, Cython, Jython...

for example, I can create a virtualenv for a different python version using the following code .

mkvirtualenv -p /usr/bin/python2.6 new_venv

but when I tried to create a virtualenv for PyPy by:

mkvirtualenv -p /usr/bin/pypy new_venv

system throws some error.

EDIT:
I'm using virtualenvwrapper-win. it throws

```<code>Running virtualenv with interpreter C:\pypy2-v5.8.0-win32\pypy.exe
New pypy executable in C:\Users\fangming.zfm\Envs\test-123\bin\pypy.exe
Installing setuptools, pip, wheel...done.
system cannot find the path specified.
system cannot find the path specified.
system cannot find the path specified.
</code>```

why we can't do this? is it because of lack of interest, or is it technically infeasible?

答:
The problem is due to pypy.exe being located under the /bin/ directory -- and not the Scripts directory (like virtualenvwrapper-win expects).

There's an issue for it (https://github.com/davidmarble/virtualenvwrapper-win/issues/30) and it should be relatively simple to fix.

Body:
After a while of searching (maybe it's not enough, but I don't think I'm making progress doing that), I haven't been able to find information about compatibility of other Python implementations in virtualenv/virtualenvwrapper.
By "other implementation" I mean things like PyPy, IronPython, Cython, Jython...

for example, I can create a virtualenv for a different python version using the following code .

mkvirtualenv -p /usr/bin/python2.6 new_venv

but when I tried to create a virtualenv for PyPy by:

mkvirtualenv -p /usr/bin/pypy new_venv

system throws some error.

EDIT:
I'm using virtualenvwrapper-win. it throws

Running virtualenv with interpreter C:\pypy2-v5.8.0-win32\pypy.exe
New pypy executable in C:\Users\fangming.zfm\Envs\test-123\bin\pypy.exe
Installing setuptools, pip, wheel...done.
system cannot find the path specified.
system cannot find the path specified.
system cannot find the path specified.

why we can't do this? is it because of lack of interest, or is it technically infeasible?


问:
How to create my own strcpy function?
I am trying to design a program in which I will create a 3 functions that resemble functions in the c-standard library (strlen,strcmp,strcpy). The first two I have gotten close to finishing, only the last one is the main problem. I am trying to create a function that will have the same functionality as the standard function strcpy. Here is what I have so far.

```<code>void myStrncpy(char destination[], const char source[], int count) {

    for (int i = 0 ; source[i] != '\0' ; i++) {

    count++;
    }
}
</code>```

So far I have gotten the length of "source" and stored it in "count". What is the next step I need to take? I would prefer to use another for loop and if statements if possible. Thanks!

****EDIT****

This is what I have now...

```<code>void myStrncpy(char destination[], const char source[], int count) {

    for (int i = 0 ; source[i] != '\0' && destination[i] != '\0' ; i++) {
    destination[i] = source[i];
    count++;
    }
</code>```

}

OUTPUT:

```<code>str1 before: stringone
str2 before: stringtwo

str1 after : stringtwo
str2 after : string two
</code>```

2ND RUN (WHERE I'M GETTING MY PROBLEM):

```<code>str1 before: stringthree
str2 before: stringfour

str1 after: stringfoure
str2 after: stringfour
</code>```

What else do I need to put in my code so that it copies every letter until it runs out of room, or it copies every letter until it runs out of letters to copy?

答:
```<code>/* body of the function*/
/*Mahmoud Mohamed Younis*/
int i;
int j = 0;
for(i=0;i<10;i++)
{
    if(s1[i] == '\0')
    {
      int  index = i;
        while(s2[j]!='\0')
        {
            if(index>10)
               break;
            s1[index] = s2[j];
            j++;
            index++;
        }
        s1[index] = '\0';
        break;
    }
}
</code>```

Title: How to create my own strcpy function?

Body:
I am trying to design a program in which I will create a 3 functions that resemble functions in the c-standard library (strlen,strcmp,strcpy). The first two I have gotten close to finishing, only the last one is the main problem. I am trying to create a function that will have the same functionality as the standard function strcpy. Here is what I have so far.

void myStrncpy(char destination[], const char source[], int count) {

    for (int i = 0 ; source[i] != '\0' ; i++) {

    count++;
    }
}

So far I have gotten the length of "source" and stored it in "count". What is the next step I need to take? I would prefer to use another for loop and if statements if possible. Thanks!

****EDIT****

This is what I have now...

void myStrncpy(char destination[], const char source[], int count) {

    for (int i = 0 ; source[i] != '\0' && destination[i] != '\0' ; i++) {
    destination[i] = source[i];
    count++;
    }

}

OUTPUT:

str1 before: stringone
str2 before: stringtwo

str1 after : stringtwo
str2 after : string two

2ND RUN (WHERE I'M GETTING MY PROBLEM):

str1 before: stringthree
str2 before: stringfour

str1 after: stringfoure
str2 after: stringfour

What else do I need to put in my code so that it copies every letter until it runs out of room, or it copies every letter until it runs out of letters to copy?


问:
Css scroll snap will not work with apple mobile web capable
Css snap points are a nice alternative to javascript bases solutions. I realize that it is not a final spec, but webkit has adopted css snap points.

However, if you enable mobile web app capable meta then it fails

An example: http://jsfiddle.net/hpjtqewn/2/

Works perfect if you open it in safari on for example an ipad. Ignore the button, just scroll. Now pin this jsfiddle to your home screen and open it using the newly created shortcut. Mobile web app capable is loaded for jsfiddle and breaks the snap point functionality: you now have smooth scrolling instead of the snaps.

Using a polyfill as fallback does not fix the problem. Any suggestions without falling back to a full javascript solution?

```<code><html>
<style type="text/css">
* {
    box-sizing: border-box;
}

ol {
    list-style-type: none;
    padding: 0px;
    margin: 0px;
    height: 100px;
    width: 500px;
    white-space: nowrap;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;

    -webkit-scroll-snap-type: mandatory;

    -ms-scroll-snap-type: mandatory;

    scroll-snap-type: mandatory;
    -webkit-scroll-snap-points-x: repeat(100%);
    -ms-scroll-snap-points-x: repeat(100%);
    scroll-snap-points-x: repeat(100%);
    //scroll-snap-destination: 50% 50%;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
}

li {
    display: inline-block;
    border: 2px solid #000;
    height: 100px;
    width: 100%;
}

.a {
    background-color: green;
}
.b {
    background-color: yellow;
}
.c {
    background-color: gray;
}
</style>
<body>
<ol>
            <li class="a"></il>
            <li class="b"></il>
            <li class="c"></il>
            <li class="d"></il>
            <li class="e"></il>
            <li class="f"></il>
            <li class="g"></il>
            <li class="h"></il>
</ol>
<button id="scroll-to-c">Scroll to C</button>
</body>
</html>
</code>```

答: There's a new addition to the draft specification that iOS 11 requires for scroll snapping to work. Add scroll-snap-align: start; to your scrolling items. [source: https://www.filamentgroup.com/lab/keep-snap-points-snapping.html]

Body:
Css snap points are a nice alternative to javascript bases solutions. I realize that it is not a final spec, but webkit has adopted css snap points.

However, if you enable mobile web app capable meta then it fails

An example: http://jsfiddle.net/hpjtqewn/2/

Works perfect if you open it in safari on for example an ipad. Ignore the button, just scroll. Now pin this jsfiddle to your home screen and open it using the newly created shortcut. Mobile web app capable is loaded for jsfiddle and breaks the snap point functionality: you now have smooth scrolling instead of the snaps.

Using a polyfill as fallback does not fix the problem. Any suggestions without falling back to a full javascript solution?

</il>

</il>

</il>

</il>

</il>

</il>

</il>

</il>

<button id="scroll-to-c">Scroll to C</button>


问:
Python - Pandas - Key Error during dropna call for specific subsets
My goal: I wish to drop rows who have NaN in specific columns. I will allow NaN to exist on some columns but not others.
English Example: If value of 'detail_age' in a row is NaN, I want to remove that row.

Here is a view of my data:

```<code>import pandas as pd
df = pd.read_csv('allDeaths.csv', index_col=0, nrows=3, engine='python')
print(df.shape)
print(list(df))
</code>```

Which outputs:

```<code>(3,15)
['education_1989_revision', 'education_2003_revision',
'education_reporting_flag', 'sex', 'detail_age', 'marital_status',
'current_data_year', 'injury_at_work', 'manner_of_death', 'activity_code',
'place_of_injury_for_causes_w00_y34_except_y06_and_y07_', '358_cause_recode',
'113_cause_recode', '39_cause_recode', 'race']
</code>```

When I attempt to remove rows who's columns value is NaN with the following:

```<code>df.dropna(subset=[2,3,4,5,6,7,8,9,11,12,13,14], axis=1, inplace=True, how='any')
</code>```

I get the following error:

```<code>Traceback (most recent call last):
  File "clean.py", line 10, in <module>
    df.dropna(subset=[2,3,4,5,6,7,8,9,11,12,13,14], axis=1, inplace=True, how='any')
  File "/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py", line 3052, in dropna
    raise KeyError(list(np.compress(check, subset)))
KeyError: [3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]
</code>```

Which is weird because this works:

```<code>df.dropna(subset=[2], axis=1, inplace=True, how='any')
</code>```

But not this:

```<code>df.dropna(subset=[5], axis=1, inplace=True, how='any')
</code>```

So there must be something wrong with certain columns or the values in those columns. Here is a peek at my data with df.head(3):

Body:
My goal: I wish to drop rows who have NaN in specific columns. I will allow NaN to exist on some columns but not others.
English Example: If value of 'detail_age' in a row is NaN, I want to remove that row.

Here is a view of my data:

import pandas as pd
df = pd.read_csv('allDeaths.csv', index_col=0, nrows=3, engine='python')
print(df.shape)
print(list(df))

Which outputs:

(3,15)
['education_1989_revision', 'education_2003_revision',
'education_reporting_flag', 'sex', 'detail_age', 'marital_status',
'current_data_year', 'injury_at_work', 'manner_of_death', 'activity_code',
'place_of_injury_for_causes_w00_y34_except_y06_and_y07_', '358_cause_recode',
'113_cause_recode', '39_cause_recode', 'race']

When I attempt to remove rows who's columns value is NaN with the following:

df.dropna(subset=[2,3,4,5,6,7,8,9,11,12,13,14], axis=1, inplace=True, how='any')

I get the following error:

Traceback (most recent call last):
  File "clean.py", line 10, in <module>
    df.dropna(subset=[2,3,4,5,6,7,8,9,11,12,13,14], axis=1, inplace=True, how='any')
  File "/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py", line 3052, in dropna
    raise KeyError(list(np.compress(check, subset)))
KeyError: [3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]

Which is weird because this works:

df.dropna(subset=[2], axis=1, inplace=True, how='any')

But not this:

df.dropna(subset=[5], axis=1, inplace=True, how='any')

So there must be something wrong with certain columns or the values in those columns. Here is a peek at my data with df.head(3):

Body:
Demo:

In [360]: df
Out[360]:
      A     B     C   D
0   1.0   2.0   NaN   4
1   5.0   NaN   7.0   8
2   NaN  10.0  11.0  12
3  13.0  14.0  15.0  16

In [362]: df = df.dropna(subset=df.columns[[1,2]], how='any')

In [363]: df
Out[363]:
      A     B     C   D
2   NaN  10.0  11.0  12
3  13.0  14.0  15.0  16

PS of course you can specify column names instead:

In [370]: df.dropna(subset=['B','C'], how='any')
Out[370]:
      A     B     C   D
2   NaN  10.0  11.0  12
3  13.0  14.0  15.0  16


问:
I can't deploy to the device in Xcode
Xcode doesn't let me choose "Device". I only deploy to simulator, to iPad 3.2. Organizer tells me: "XCode cannot find the software image to install this version" when I connect an iPhone 3.1.3 firmware.

I have Xcode 3.2.5 with iOS 4.2. What can I do to solve this?

答:
Problem is XCode has no idea about version of iOS that you have running on your device. You need to do following:

In Organizer see what exact version of iOS is on your device (say it's '3.1.3 ABC')

Open terminal and go to /Developer/Platforms/iPhoneOS.platform/DeviceSupport/

There you will see list of OS images that XCode has. You need to pick on that is 'closer' to one that you have on the device (say you have directory there called 3.1) and create a symbolic link like:
ln -s 3.1 3.1.3\ ABC.

This way you fool XCode to think that it knows exact version of your device.

Title: I can't deploy to the device in Xcode


问:
Javascript: function not defined with button onclick event?
Learning JS, trying to get this little survey to work, but I get a "function not defined" error at HTML element onclick.  Can't figure out why, it seems like the function is defined and I can't find any syntax errors.  I also get an error saying that "soda is not defined," but it seems like that variable is defined as an object in the array.

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

<h3>What cats are in the room?</h3>

Sophie: <input type="checkbox" id="sophieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>

<button onclick="catsInTheRoom()">Try it</button>
<br></br>

<p id="cats"></p>

<script>
function catsInTheRoom() {

    var myCats = [ soda, mr, sophie ];

    if (getElementById("sodaCheck").checked) {
        myCats[0] = 1;
    } else {
        myCats[0] = 0;
    }
    if (getElementById("sophieCheck").checked) {
        myCats[2] = 10;
    } else {
        myCats[2] = 0;
    }
    if (getElementById("mrCheck").checked) {
        myCats[1] = 20;
    } else {
        myCats[1] = 0;
    }

    getElementById("cats").innerHTML = myCats[0] + myCats[1]  + myCats[2];
}

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

I created the array so I can use the numerical values for a switch statement to produce different text based on which checkboxes are checked.

This simpler version worked:

```<code>Sophie: <input type="checkbox" id="sohpieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>

<button onclick="myFunction()">Try it</button>

<p id="cats"></p>

<script>

function myFunction() {
    var soda = document.getElementById("sodaCheck").checked;

    if (soda) {
        catBehavior = "Cats are being rascals.";
    } else {
        catBehavior = "Cats are behaving nicely.";
    }

    document.getElementById("cats").innerHTML = catBehavior;
}

</script>
</code>```

Why does the second example work, but not the first one?

答:
the line 'var myCats = [ soda, mr, sophie ];' is the cause of the error. You are using strings as variables. If you must use those strings, then create an object with those properties and initialize the values as follows;</p>

```<code>  var myCats ={soda=0, mr=0, sophie=0};
if (getElementById("sodaCheck").checked) {
  myCats.soda = 1;
 } else {
  myCats.soda = 0;
 }
if (getElementById("sophieCheck").checked) {
    myCats.sophie= 10;
} else {
    myCats.sophie = 0;
}
if (getElementById("mrCheck").checked) {
   myCats.mr = 20;
} else {
    myCats.mr = 0;
}

getElementById("cats").innerHTML = myCats.soda  + myCats.mr  + myCats.sophie;
}
</code>```

Body:
Learning JS, trying to get this little survey to work, but I get a "function not defined" error at HTML element onclick.  Can't figure out why, it seems like the function is defined and I can't find any syntax errors.  I also get an error saying that "soda is not defined," but it seems like that variable is defined as an object in the array.

What cats are in the room?

Sophie: <input type="checkbox" id="sophieCheck">

Soda: <input type="checkbox" id="sodaCheck">

Mr.: <input type="checkbox" id="mrCheck">

<button onclick="catsInTheRoom()">Try it</button>

I created the array so I can use the numerical values for a switch statement to produce different text based on which checkboxes are checked.

This simpler version worked:

Sophie: <input type="checkbox" id="sohpieCheck">

Soda: <input type="checkbox" id="sodaCheck">

Mr.: <input type="checkbox" id="mrCheck">

<button onclick="myFunction()">Try it</button>

Why does the second example work, but not the first one?

Body:
the line 'var myCats = [ soda, mr, sophie ];' is the cause of the error. You are using strings as variables. If you must use those strings, then create an object with those properties and initialize the values as follows;

  var myCats ={soda=0, mr=0, sophie=0};
if (getElementById("sodaCheck").checked) {
  myCats.soda = 1;
 } else {
  myCats.soda = 0;
 }
if (getElementById("sophieCheck").checked) {
    myCats.sophie= 10;
} else {
    myCats.sophie = 0;
}
if (getElementById("mrCheck").checked) {
   myCats.mr = 20;
} else {
    myCats.mr = 0;
}

getElementById("cats").innerHTML = myCats.soda  + myCats.mr  + myCats.sophie;
}


问:
How to pass data between two components in Angular 2
I am looking for solution to pass data to another component and similarly access methods of another component in other (both are parallel components).

For example i have two components home.ts and map.ts.
I get some data into map.ts and need to pass that in home.ts and vice versa.

答:
You can transfer data using service.

Make a service that holds the data while you switch components. Below is an example.

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class TransfereService {

  constructor(
    private router:Router,
    private companyServiceService:CompanyServiceService
  ) { }

  private data;

  setData(data){
    this.data = data;
  }

  getData(){
    let temp = this.data;
    this.clearData();
    return temp;
  }

  clearData(){
    this.data = undefined;
  }

}
</code>```

Now Consider 2 components Sender and Reciever.

Senders code: This code sets the data to the service and navigates to the receiver.

```<code>import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class SenderComponent implements OnInit {
  constructor(
    private transfereService:TransfereService,
    private router:Router) {}

  somefunction(data){
   this.transfereService.setData(data);
   this.router.navigateByUrl('/reciever');//as per router
 }
}
</code>```

Reciever's Code: This code fetches the data from service and clears the data as well.

```<code>import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class RecieverComponent implements OnInit {
 data = this.transfereService.getData();
 constructor(
   private transfereService:TransfereService,
   private router:Router) {
      if(this.data){
        // do whatever needed
      }
      else{
        this.router.navigateByUrl('/sender');
      }
   }
}
</code>```

You should check out Fireship Demo for the same. It's helpful.

Body:
You can transfer data using service.

Make a service that holds the data while you switch components. Below is an example.

import { Injectable } from '@angular/core';

@Injectable()
export class TransfereService {

  constructor(
    private router:Router,
    private companyServiceService:CompanyServiceService
  ) { }

  private data;

  setData(data){
    this.data = data;
  }

  getData(){
    let temp = this.data;
    this.clearData();
    return temp;
  }

  clearData(){
    this.data = undefined;
  }

}

Now Consider 2 components Sender and Reciever.

Senders code: This code sets the data to the service and navigates to the receiver.

import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class SenderComponent implements OnInit {
  constructor(
    private transfereService:TransfereService,
    private router:Router) {}

  somefunction(data){
   this.transfereService.setData(data);
   this.router.navigateByUrl('/reciever');//as per router
 }
}

Reciever's Code: This code fetches the data from service and clears the data as well.

import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class RecieverComponent implements OnInit {
 data = this.transfereService.getData();
 constructor(
   private transfereService:TransfereService,
   private router:Router) {
      if(this.data){
        // do whatever needed
      }
      else{
        this.router.navigateByUrl('/sender');
      }
   }
}

You should check out Fireship Demo for the same. It's helpful.

ContentLicense: CC BY-SA 4.0


问:
About the meaning of perl \w
according to the doc

\w        [3]  Match a "word" character (alphanumeric plus "_", plus
  other connector punctuation chars plus Unicode marks)

I don't understand what is "plus other connector punctuation chars plus Unicode marks", the doc seems doesn't say. What is \w really?

答:
Your quote is from perldoc perlre. The corresponding footnote says:

[3]

  See Backslash sequences in perlrecharclass for details.

Which says:

A \w matches a single alphanumeric character (an alphabetic character, or a decimal digit); or a connecting punctuation character, such as an underscore ("_"); or a "mark" character (like some sort of accent) that attaches to one of those. It does not match a whole word. To match a whole word, use \w+. This isn't the same thing as matching an English word, but in the ASCII range it is the same as a string of Perl-identifier characters.

It also says that (if Unicode rules are in effect), \w is equivalent to \p{Word}. perldoc perluniprops:

```<code>\p{Word}                \p{XPosixWord}
</code>```

I.e. \p{Word} is an alias for \p{XPosixWord}.

```<code>\p{XPosixWord}          \w, including beyond ASCII; = \p{Alnum} + \pM + \p{Pc} (Short: \p{Word})
</code>```

I.e. \p{XPosixWord} is the union of \p{Alnum}, \pM, and \p{Pc}.

Here \p{Alnum} matches any "Alphabetic and (decimal) Numeric" character, \pM matches any character whose general category is "Mark", and \p{Pc} matches any character whose general category is "Connector Punctuation".

For a complete list of characters in those categories I'll have to defer to Unicode.

Title: About the meaning of perl \w

Body:
Your quote is from perldoc perlre. The corresponding footnote says:

[3]

  See Backslash sequences in perlrecharclass for details.

Which says:

A \w matches a single alphanumeric character (an alphabetic character, or a decimal digit); or a connecting punctuation character, such as an underscore ("_"); or a "mark" character (like some sort of accent) that attaches to one of those. It does not match a whole word. To match a whole word, use \w+. This isn't the same thing as matching an English word, but in the ASCII range it is the same as a string of Perl-identifier characters.

It also says that (if Unicode rules are in effect), \w is equivalent to \p{Word}. perldoc perluniprops:

\p{Word}                \p{XPosixWord}

I.e. \p{Word} is an alias for \p{XPosixWord}.

\p{XPosixWord}          \w, including beyond ASCII; = \p{Alnum} + \pM + \p{Pc} (Short: \p{Word})

I.e. \p{XPosixWord} is the union of \p{Alnum}, \pM, and \p{Pc}.

Here \p{Alnum} matches any "Alphabetic and (decimal) Numeric" character, \pM matches any character whose general category is "Mark", and \p{Pc} matches any character whose general category is "Connector Punctuation".

For a complete list of characters in those categories I'll have to defer to Unicode.


问:
SQL Statement not working in php while trying to fetch information from mysql database
I tried everything and I'm losing my mind

    function submitItem(){
        textarea = $("#textarea").val();
        status = $("#status").val();
        category = $("#categories").val();
        date = $("#date").val();

        var ajaxReq = new XMLHttpRequest();
        ajaxReq.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("message").innerHTML = this.responseText;
            }
        }
        ajaxReq.open("POST","../php/addItem.php",true);
        ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxReq.send("textarea="+textarea+"&category="+category+"&status="+status+"&date="+date);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>AJAX REQUEST
<?php
session_start();
require("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);

$category = $_POST["category"];
$item = $_POST["textarea"];
$date = $_POST["date"];
$status = $_POST["status"];
$userID = $_SESSION["userID"];

$searchForCategory = "SELECT * FROM categories where categoryname = \"".$category."\"";
$result = $cnx->query($searchForStatus);
$row = $result->num_rows;

echo $row;

?></code>```

And I tried everything, when I put and actual name it's working fine. I echo-ed the $category to see if it's working and it's working fine. I have no idea what the error might be

答:
The textarea probably contains some special characters, which you aren't encoding properly. Use $.post, which will encode the data properly.

```<code>function submitItem() {
    $.post("../php/addItem.php", {
        textarea: $("#textarea").val(),
        category: $("#categories").val(),
        status: $("#status").val(),
        date: $("#date").val()
    }, function(response) {
        $("#message").html(response);
    });
}
</code>```

If there's some reason you don't want to do this, use the encodeURIComponent() function around each parameter, e.g.

```<code>"textarea=" + encodeURIComponent(textarea) + "&category=" + encodeURIComponent(category) + ...
</code>```

Body:
I tried everything and I'm losing my mind

    function submitItem(){
        textarea = $("#textarea").val();
        status = $("#status").val();
        category = $("#categories").val();
        date = $("#date").val();

        var ajaxReq = new XMLHttpRequest();
        ajaxReq.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("message").innerHTML = this.responseText;
            }
        }
        ajaxReq.open("POST","../php/addItem.php",true);
        ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxReq.send("textarea="+textarea+"&category="+category+"&status="+status+"&date="+date);
    }

AJAX REQUEST
<?php
session_start();
require("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);

$category = $_POST["category"];
$item = $_POST["textarea"];
$date = $_POST["date"];
$status = $_POST["status"];
$userID = $_SESSION["userID"];

$searchForCategory = "SELECT * FROM categories where categoryname = \"".$category."\"";
$result = $cnx->query($searchForStatus);
$row = $result->num_rows;

echo $row;

?>

And I tried everything, when I put and actual name it's working fine. I echo-ed the $category to see if it's working and it's working fine. I have no idea what the error might be

Body:
The textarea probably contains some special characters, which you aren't encoding properly. Use $.post, which will encode the data properly.

function submitItem() {
    $.post("../php/addItem.php", {
        textarea: $("#textarea").val(),
        category: $("#categories").val(),
        status: $("#status").val(),
        date: $("#date").val()
    }, function(response) {
        $("#message").html(response);
    });
}

If there's some reason you don't want to do this, use the encodeURIComponent() function around each parameter, e.g.

"textarea=" + encodeURIComponent(textarea) + "&category=" + encodeURIComponent(category) + ...


问:
StructureMap register generic types against all possible concrete implementations
I have the following:

```<code>public interface ICommand { }
public class AddUser : ICommand
{
    public string Name { get; set; }
    public string Password { get; set; }
}

public interface ICommandHandler<T> : IHandler<T> where T : ICommand
{
    void Execute(T command);
}

public class AddUserHandler : ICommandHandler<AddUser>
{
    public void Execute(AddUser command)
    {
        Console.WriteLine("{0}: User added: {1}", GetType().Name, command.Name);
    }
}

public class AuditTrailHandler : ICommandHandler<ICommand>
{
    public void Execute(ICommand command)
    {
        Console.WriteLine("{0}: Have seen a command of type {1}", GetType().Name, command.GetType().Name);
    }
}
</code>```

I would like to use scanning to register the ICommandHandler<> so that I get the following types in the container:

ICommandHandler<AddUser> with concrete type AddUserHandler

ICommandHandler<AddUser> with concrete type AuditTrailHandler

I have tried this with an implementation of IRegistrationConvention and at one point I had it working but I just cannot get my head around how I did it.

The goal is to be able to execute several handlers for a specific ICommand implementation like so:

```<code>// A method in CommandDispatcher
public void SendCommand<T>(T command) where T : ICommand {
   var commandHandlers = container.GetAllInstances<ICommandHandler<T>>();
   foreach (var commandHandler in commandHandlers) {
       commandHandler.Execute(command);
   }
}
</code>```

I want the AuditTrailHandler<ICommand> to execute for all concrete implementations of ICommand, hence the need to register them for all types of ICommand.

Secondary objective would be if I could inject a collection of ICommandHandlers<ICommand> into my CommandDispatcher instead of the container, but I think that's impossible with the structure I have now. Prove me wrong if you have any ideas.

EDIT - solved

I added a non generic interface that my generic interface implements and then I also added an Abstract CommandHandler<T> so I don't have to implement the CanHandle or Execute(object) methods in all my handlers.

This is the working structure:

```<code>public interface ICommandHandler
{
    void Execute(object command);
    bool CanHandle(ICommand command);
}

public interface ICommandHandler<T> : ICommandHandler, IHandler<T> where T : ICommand
{
    void Execute(T command);
}

public abstract class AbstractCommandHandler<T> : ICommandHandler<T> where T : ICommand
{
    public abstract void Execute(T command);
    public void Execute(object command)
    {
        Execute((T)command);
    }

    public virtual bool CanHandle(ICommand command)
    {
        return command is T;
    }
}
</code>```

And since this originally was a StructureMap question, here is the Scan to add this:

```<code>Scan(x =>
        {
            x.AssemblyContainingType<MyConcreteHandler>();
            x.IncludeNamespaceContainingType<MyConcreteHandler>();
            x.AddAllTypesOf<ICommandHandler>();
            x.WithDefaultConventions();
        });
</code>```

This makes me able to inject an IEnumerable in my CommandDispatcher and execute like so:

```<code>public void SendCommand<T>(T command) where T : ICommand
    {
        var commandHandlersThatCanHandle = commandHandlers.Where(c => c.CanHandle(command));
        foreach (var commandHandler in commandHandlersThatCanHandle)
        {
            commandHandler.Execute(command);
        }
    }
</code>```

This makes me able to execute CommandHandlers that support AddUser (like the AddUserHandler), but I'm also able to execute a handler that support ICommand (like the AuditTrailHandler).

This is sweet!

答:
To have all of the command handlers injected into the command dispatcher, create a new, non-generic ICommandHandler interface which ICommandHandler<T> derives from. It has an Execute method which takes an object. The downside is that each of your command handlers has to implement that method to call the typed overload:

```<code>public class AddUserHandler : ICommandHandler<AddUser>
{
    public void Execute(object command)
    {
        Execute((AddUser)command);
    }
    public void Execute(AddUser command)
    {
        Console.WriteLine("{0}: User added: {1}", GetType().Name, command.Name);
    }
}
</code>```

This will enable your command dispatcher to have a constructor dependency on IEnumerable<ICommandHandler>, which StructureMap will automatically populate.

In SendCommand you have 2 ways of getting the appropriate set of handlers. A simple filter based on type:

```<code>commandHandlers.OfType<ICommandHandler<T>>
</code>```

or add a CanHandle(object command) to the ICommandHandler interface:

```<code>commandHandlers.Where(x => x.CanHandle(command))
</code>```

The second approach requires more code, but gives you a little more flexibility by allowing you to attach handler by more than just type. This may make solving your first problem easier, by making your AuditTrailHandler always return true from CanHandle.

Body:
I have the following:

public interface ICommand { }
public class AddUser : ICommand
{
    public string Name { get; set; }
    public string Password { get; set; }
}

public interface ICommandHandler<T> : IHandler<T> where T : ICommand
{
    void Execute(T command);
}

public class AddUserHandler : ICommandHandler<AddUser>
{
    public void Execute(AddUser command)
    {
        Console.WriteLine("{0}: User added: {1}", GetType().Name, command.Name);
    }
}

public class AuditTrailHandler : ICommandHandler<ICommand>
{
    public void Execute(ICommand command)
    {
        Console.WriteLine("{0}: Have seen a command of type {1}", GetType().Name, command.GetType().Name);
    }
}

I would like to use scanning to register the ICommandHandler<> so that I get the following types in the container:

ICommandHandler<AddUser> with concrete type AddUserHandler

ICommandHandler<AddUser> with concrete type AuditTrailHandler

I have tried this with an implementation of IRegistrationConvention and at one point I had it working but I just cannot get my head around how I did it.

The goal is to be able to execute several handlers for a specific ICommand implementation like so:

// A method in CommandDispatcher
public void SendCommand<T>(T command) where T : ICommand {
   var commandHandlers = container.GetAllInstances<ICommandHandler<T>>();
   foreach (var commandHandler in commandHandlers) {
       commandHandler.Execute(command);
   }
}

I want the AuditTrailHandler<ICommand> to execute for all concrete implementations of ICommand, hence the need to register them for all types of ICommand.

Secondary objective would be if I could inject a collection of ICommandHandlers<ICommand> into my CommandDispatcher instead of the container, but I think that's impossible with the structure I have now. Prove me wrong if you have any ideas.

EDIT - solved

I added a non generic interface that my generic interface implements and then I also added an Abstract CommandHandler<T> so I don't have to implement the CanHandle or Execute(object) methods in all my handlers.

This is the working structure:

public interface ICommandHandler
{
    void Execute(object command);
    bool CanHandle(ICommand command);
}

public interface ICommandHandler<T> : ICommandHandler, IHandler<T> where T : ICommand
{
    void Execute(T command);
}

public abstract class AbstractCommandHandler<T> : ICommandHandler<T> where T : ICommand
{
    public abstract void Execute(T command);
    public void Execute(object command)
    {
        Execute((T)command);
    }

    public virtual bool CanHandle(ICommand command)
    {
        return command is T;
    }
}

And since this originally was a StructureMap question, here is the Scan to add this:

Scan(x =>
        {
            x.AssemblyContainingType<MyConcreteHandler>();
            x.IncludeNamespaceContainingType<MyConcreteHandler>();
            x.AddAllTypesOf<ICommandHandler>();
            x.WithDefaultConventions();
        });

This makes me able to inject an IEnumerable in my CommandDispatcher and execute like so:

public void SendCommand<T>(T command) where T : ICommand
    {
        var commandHandlersThatCanHandle = commandHandlers.Where(c => c.CanHandle(command));
        foreach (var commandHandler in commandHandlersThatCanHandle)
        {
            commandHandler.Execute(command);
        }
    }

This makes me able to execute CommandHandlers that support AddUser (like the AddUserHandler), but I'm also able to execute a handler that support ICommand (like the AuditTrailHandler).

This is sweet!

Body:
To have all of the command handlers injected into the command dispatcher, create a new, non-generic ICommandHandler interface which ICommandHandler<T> derives from. It has an Execute method which takes an object. The downside is that each of your command handlers has to implement that method to call the typed overload:

public class AddUserHandler : ICommandHandler<AddUser>
{
    public void Execute(object command)
    {
        Execute((AddUser)command);
    }
    public void Execute(AddUser command)
    {
        Console.WriteLine("{0}: User added: {1}", GetType().Name, command.Name);
    }
}

This will enable your command dispatcher to have a constructor dependency on IEnumerable<ICommandHandler>, which StructureMap will automatically populate.

In SendCommand you have 2 ways of getting the appropriate set of handlers. A simple filter based on type:

commandHandlers.OfType<ICommandHandler<T>>

or add a CanHandle(object command) to the ICommandHandler interface:

commandHandlers.Where(x => x.CanHandle(command))

The second approach requires more code, but gives you a little more flexibility by allowing you to attach handler by more than just type. This may make solving your first problem easier, by making your AuditTrailHandler always return true from CanHandle.


问:
Branch.io - How to setup universal links/App links in Ionic app
My app is built on ionic 1 and I have followed this guide to get things working. https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking When you click on the branch url, the app opens up fine.

Now I want to setup android app links. When I receive an email with my web app url, eg: https://app.example.com, this should open up the app if mobile app is installed. If not user should be taken to play store/App store.

Also if the link has query params (the query params will be dynamic), this should be passed to the mobile app. eg: https://app.example.com/mypath?query_params=1234567890

Based on the path in the url, the user will be redirected to the respective page on the ionic app.

I have setup the branch sdk bower install branch-sdk. When I click on the url (https://app.example.com) this still opens up on browser. This is how my index.html in ionic app looks like.

```<code><script src="lib/branch-sdk/dist/build.min.js"></script>

<script type="text/javascript">
  console.log("Branch SDK Loading");

  branch.init('key_test_ikEKvQjiZRwV1LXZ2hUlamfewwhVQ5rw', function(err, data) {
    console.log("Branch SDK Loaded");
    console.log("Branch SDK Err and Data ", err, data);
  });
</script>
</code>```

Any idea how to set these things up?

答:
Alex from Branch.io here:

Everything you've described should generally be working once you've done the initial integration process. If you haven't already, I'd suggest reviewing our main integration guide to make sure all the steps were completed.

If you're still having difficulty, get in touch with our Integrations team. They're fantastic!

EDIT: this is due to using Postmark for email sending. To understand why this is a problem, take a read through this blog post. It's primarily about iOS Universal Links, but App Links work almost exactly the same way.

To get this working, you'll need to turn off link tracking on Postmark.

Body:
My app is built on ionic 1 and I have followed this guide to get things working. https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking When you click on the branch url, the app opens up fine.

Now I want to setup android app links. When I receive an email with my web app url, eg: https://app.example.com, this should open up the app if mobile app is installed. If not user should be taken to play store/App store.

Also if the link has query params (the query params will be dynamic), this should be passed to the mobile app. eg: https://app.example.com/mypath?query_params=1234567890

Based on the path in the url, the user will be redirected to the respective page on the ionic app.

I have setup the branch sdk bower install branch-sdk. When I click on the url (https://app.example.com) this still opens up on browser. This is how my index.html in ionic app looks like.

Any idea how to set these things up?


问:
How can i use Symfony or Zend Components inside Code Igniter?
I would like if there is a simple and clean way to use ZF´s (or Symfony´s) component library in a CodeIgniter application, because there is a lot of good and useful stuff there that CI don´t have.</p>

答:
You can use components symfony by installing them via composer.

For example, you can install the varDumper component which provides a better dump() function that you can use instead of var_dump.

```<code>composer require symfony/var-dumper
</code>```

the composer will install the dumper component with all his dependecy

then include the autoload and use the dump function

```<code>require __DIR__.'/vendor/autoload.php';

// create a variable, which could be anything!
$someVar = ...;

dump($someVar);
</code>```

Body:
You can use components symfony by installing them via composer.

For example, you can install the varDumper component which provides a better dump() function that you can use instead of var_dump.

composer require symfony/var-dumper

the composer will install the dumper component with all his dependecy

then include the autoload and use the dump function

require __DIR__.'/vendor/autoload.php';

// create a variable, which could be anything!
$someVar = ...;

dump($someVar);


问:
Data loss when draining Dataflow job that reads from PubSub and writes to Google Cloud Storage
When putting a fixed number of strings (800,000 1KB used to test) into a PubSub topic and running the following Apache Beam (2.1.0) job in Dataflow, exactly once semantics are preserved as expected.

import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.windowing.FixedWindows;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.joda.time.Duration;

public class PubSubToGsSimpleJob {

    public static void main(String[] args) {
        PubSubToGsPipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
                .as(PubSubToGsPipelineOptions.class);
        Pipeline p = Pipeline.create(options);

        p.apply(PubsubIO.readStrings().fromSubscription(options.getInput()))
                .apply(Window.into(FixedWindows.of(Duration.standardMinutes(1))))
                .apply(TextIO.write().withWindowedWrites().withNumShards(1).to(options.getOutput()));
        p.run();
    }

}
```

<p><code>PipelineOptions</code> implementation below</p>

<pre class="lang-java prettyprint-override"><code>import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;

public interface PubSubToGsPipelineOptions extends PipelineOptions {
    @Description("PubSub subscription")
    String getInput();
    void setInput(String input);

    @Description("Google Cloud Storage output path")
    String getOutput();
    void setOutput(String output);
}
</code>```

However, if the same job is run, drained before all the elements are read (as shown in the Dataflow console), and kicked off again, the output files have fewer records than the original data set that was published in to the PubSub topic. This is suggesting that draining and replacing a job can cause data loss which seems odd since this google cloud blog post mentions that Drain and replace should have at least once semantics. How should this pipeline be designed to achieve at least once semantics (or better yet exactly once semantics) when draining and replacing the job?

答:
My guess is that a window might be partially written before drain and replacement job overwrites it with the remaining window. You can check the worker logs from drained job and replacement job for this log line in WriteFiles. If you use Beam HEAD it also logs when it the final destination is overwritten.

Conceptually drained job and replacement jobs are entirely different pipelines. Using same output location is not different from using same output location for two other unrelated jobs. Another thing you could try is to use different output path for second job and verify that all the records exist across both directories.

Body:
When putting a fixed number of strings (800,000 1KB used to test) into a PubSub topic and running the following Apache Beam (2.1.0) job in Dataflow, exactly once semantics are preserved as expected.

import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.windowing.FixedWindows;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.joda.time.Duration;

public class PubSubToGsSimpleJob {

    public static void main(String[] args) {
        PubSubToGsPipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
                .as(PubSubToGsPipelineOptions.class);
        Pipeline p = Pipeline.create(options);

        p.apply(PubsubIO.readStrings().fromSubscription(options.getInput()))
                .apply(Window.into(FixedWindows.of(Duration.standardMinutes(1))))
                .apply(TextIO.write().withWindowedWrites().withNumShards(1).to(options.getOutput()));
        p.run();
    }

}

PipelineOptions implementation below

import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;

public interface PubSubToGsPipelineOptions extends PipelineOptions {
    @Description("PubSub subscription")
    String getInput();
    void setInput(String input);

    @Description("Google Cloud Storage output path")
    String getOutput();
    void setOutput(String output);
}

However, if the same job is run, drained before all the elements are read (as shown in the Dataflow console), and kicked off again, the output files have fewer records than the original data set that was published in to the PubSub topic. This is suggesting that draining and replacing a job can cause data loss which seems odd since this google cloud blog post mentions that Drain and replace should have at least once semantics. How should this pipeline be designed to achieve at least once semantics (or better yet exactly once semantics) when draining and replacing the job?


问:
"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"
I'm Windows 7 64-bit user and I got Android Studio problem after I update the latest version of Android Studio and SDK components..

```<code>The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22
</code>```

Please help me to resolve this problem. Thank you.

答: I was getting an "out of space" error, which left me scratching my head as I had plenty of disk space, until I realized that it ran out of space on /tmp, which on Arch Linux is mounted on a tmpfs with a size limit.

Body:
I'm Windows 7 64-bit user and I got Android Studio problem after I update the latest version of Android Studio and SDK components..

The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22

Please help me to resolve this problem. Thank you.


问:
Interview Question: Replacing two arrays's place in memory
Given two consecutive arrays, A and B. They look something like

```<code>int AandB[] = {a1,a2,...,am,b1,b2,...,bn};
</code>```

You need to write a program that would switch the order of arrays A and B in the memory, so that B would appear before A. In our example, AandB should become

```<code>int AandB[] = {b1,b2,...,bn,a1,...,am};
</code>```

What's the most efficient way to do that?

答:
My answer:

First, I'm assuming wlog that m<n.

Since every permutation can be decomposed into disjoint cycles, so can the permutation which takes a1,...,am,b1,..,bn to b1,..,bn,a1,...,am. And since given an index i, it is easy to calculate p(i) (assume wlog that m<n, then if i<=m, we have p(i)=n+i, if i>m we have p(i)=i-m).

We can start with AandB[i] and move its value to p(i)=j, then, take the value in AandB[j] and move it to p(j), etc. Since permutations can be decompose into disjoint cycles, we'll end up in i.

We only need to keep track of which elements did we already move. It is possible to prove that in our case, no cycle in the permutation will contain two consecutive elements of A, so I think it is enough to keep track of how many elements of A have we ordered.

Another simple option which is not as efficient is to note that
given {a1,...,am,b1,...bn}, it is possible to replace a1..am with b(n-m)..b(n), getting {b(n-m)...b(n),b(1)..b(m),a1..am}. And now by recursion, solve the same problem for the first n elements of your array. But this is probably not so efficient.

There are some more details which I omitted, but anyhow the interviewer told me that it's not the way to go, and there's some very clever solution that is also very simple.

Body:
Given two consecutive arrays, A and B. They look something like

int AandB[] = {a1,a2,...,am,b1,b2,...,bn};

You need to write a program that would switch the order of arrays A and B in the memory, so that B would appear before A. In our example, AandB should become

int AandB[] = {b1,b2,...,bn,a1,...,am};

What's the most efficient way to do that?


问:
How to do case insensitive search in Vim
I'd like to search for an upper case word, for example COPYRIGHT in a file. I tried performing a search like:

```<code>/copyright/i    # Doesn't work
</code>```

but it doesn't work.  I know that in Perl, if I give the i flag into a regex it will turn the regex into a case-insensitive regex. It seems that Vim  has its own way to indicate a case-insensitive regex.

答:
The good old vim[grep] command..

```<code>:vimgrep /example\c/ &
</code>```

\c for case insensitive

\C for case sensitive

% is to search in the current buffer

Body:
I'd like to search for an upper case word, for example COPYRIGHT in a file. I tried performing a search like:

/copyright/i    # Doesn't work

but it doesn't work.  I know that in Perl, if I give the i flag into a regex it will turn the regex into a case-insensitive regex. It seems that Vim  has its own way to indicate a case-insensitive regex.

Body:
The good old vim[grep] command..

:vimgrep /example\c/ &

\c for case insensitive

\C for case sensitive

% is to search in the current buffer


问:
ffplay - change playback speed without re-encoding
I have some .264 video files that I would like to view at half playback speed, without encoding them into a new file. I remember using ffplay to do this in the past, but it was some time ago, and I can't seem to be able to do it now. From lots of searching, this is what is supposed to work:

```<code>ffplay -f h264 -vf "setpts=2.0*PTS" filename.264
</code>```

However this does not seem to change the playback speed at all. If I try:

```<code>ffplay -f h264 -filter:v "setpts=2.0*PTS" filename.264
</code>```

I get an error message saying 'Failed to set value 'setpts=2.0*PTS' for option 'filter:v': Option not found'.

I specifically remember being able to do this before but cannot find any information about this now. Converting the videos is not really an option because the files are finicky and often cause an error halfway through converting, corrupting the whole file.

Is there a simple solution to this problem? Am I typing one of the commands wrongly?

答:
Just managed to do this with the not-very-well-documented -framerate option for an MJPEG stream, for anyone else who finds this post but isn't necessarily using H264.

```<code>ffplay udp://224.0.1.2:5004 -f mjpeg -framerate 30
</code>```

Body:
I have some .264 video files that I would like to view at half playback speed, without encoding them into a new file. I remember using ffplay to do this in the past, but it was some time ago, and I can't seem to be able to do it now. From lots of searching, this is what is supposed to work:

ffplay -f h264 -vf "setpts=2.0*PTS" filename.264

However this does not seem to change the playback speed at all. If I try:

ffplay -f h264 -filter:v "setpts=2.0*PTS" filename.264

I get an error message saying 'Failed to set value 'setpts=2.0*PTS' for option 'filter:v': Option not found'.

I specifically remember being able to do this before but cannot find any information about this now. Converting the videos is not really an option because the files are finicky and often cause an error halfway through converting, corrupting the whole file.

Is there a simple solution to this problem? Am I typing one of the commands wrongly?

Body:
Just managed to do this with the not-very-well-documented -framerate option for an MJPEG stream, for anyone else who finds this post but isn't necessarily using H264.

ffplay udp://224.0.1.2:5004 -f mjpeg -framerate 30


问:
laying out divs horizontally with content within it
I am trying to layout my div holding three divs within it. The application uses Bootstrap. They don't seem to be laying out properly with all text or buttons in the center. I am using a separator between the second and third boxes. The application also uses another class content-header which is from the proui library used elsewhere in the application and borrowed here for maintaining the same look and feel across the application.

This is the simplified HTML

```<code><!--FIXED PANEL-->
<div class="content-header fd">

    <!-- first box-->
    <div class="col-md-6 fdc" style="display:block; visibility:visible">
        first box
    </div>

   <!--second box-->
   <div class="col-md-2  fdc" >
        second box
    <span class="pipe_separator">|</span>
    </div>

    <!--third box-->
    <div class="col-md-4 fdc text-left">
        third box
    </div>

</div>
</code>```

Here is the CSS

```<code>    .fd{
        position: fixed;
        top: 70px;
        width:100%;
        background-color: #141313ad;
        z-index: 1
    }

    .fdc{
        display: inline-block;
        *display: inline; zoom: 1;
        vertical-align:middle;
        background-color: #141313e5;
        height: 75px;
        border-color: black;

    }

    .pipe_separator{
        font-size: 40px;
    }

}
</style>
</code>```

here is what it looks like

As you can see the content of the boxes are not aligned. I want the third div and its contents to be where I have drawn it out with the number 3 within. The separator just about to its left where I have drawn the green line and the second div to the left of the separator and the first div to the left of the second div. The main div holding these three layers acts as a fixed panel below the page header. How do I make them align together and sit as I have described.

答:
Simplest hack is to put them in a table with no borders. It will work as follows:</p>

```<code><div class="content-header fd">

<table borders="0">
<tr><td>
<!-- first box-->
<div class="col-md-6 fdc" style="display:block; visibility:visible">
    first box
</div>
</td>
<td>
<!--second box-->
<div class="col-md-2  fdc" >
    second box
<span class="pipe_separator">|</span>
</div>
</td>
<td>
<!--third box-->
<div class="col-md-4 fdc text-left">
    third box
</div>
</td>
</tr>
</table>
</div>
</code>```

Body:
I am trying to layout my div holding three divs within it. The application uses Bootstrap. They don't seem to be laying out properly with all text or buttons in the center. I am using a separator between the second and third boxes. The application also uses another class content-header which is from the proui library used elsewhere in the application and borrowed here for maintaining the same look and feel across the application.

This is the simplified HTML

        first box

        second box
    |

        third box

Here is the CSS

    .fd{
        position: fixed;
        top: 70px;
        width:100%;
        background-color: #141313ad;
        z-index: 1
    }

    .fdc{
        display: inline-block;
        *display: inline; zoom: 1;
        vertical-align:middle;
        background-color: #141313e5;
        height: 75px;
        border-color: black;

    }

    .pipe_separator{
        font-size: 40px;
    }

}
</style>

here is what it looks like

As you can see the content of the boxes are not aligned. I want the third div and its contents to be where I have drawn it out with the number 3 within. The separator just about to its left where I have drawn the green line and the second div to the left of the separator and the first div to the left of the second div. The main div holding these three layers acts as a fixed panel below the page header. How do I make them align together and sit as I have described.

Body:
Simplest hack is to put them in a table with no borders. It will work as follows:

<div class="content-header fd">

<table borders="0">
<tr><td>
<!-- first box-->
<div class="col-md-6 fdc" style="display:block; visibility:visible">
    first box
</div>
</td>
<td>
<!--second box-->
<div class="col-md-2  fdc" >
    second box
<span class="pipe_separator">|</span>
</div>
</td>
<td>
<!--third box-->
<div class="col-md-4 fdc text-left">
    third box
</div>
</td>
</tr>
</table>
</div>


问:
Excel function to insert few letters into every blank cell in entire column
I've been trying to understand how to make a function like that but couldn't figure it out. I have a column (I2:I48) with some values but also empty cells and I want to put let's say "123" in every empty cell and do nothing if cell has values already.

```<code>=IF(I2:II48 = "","123","")
</code>```

This one isn't working for me. Thanks everybody for future help.

答:
As the way you want to do, someone corrects me if I'm wrong, you can't. You would need to do it in a different column or with VBA. In your case, you would need the column J and put the function you've created:

Column I, you keep the values.
Column J, you check each row =if(I1="",123,I1), then =if(I2="",123,I2) and so on...

Body:
I've been trying to understand how to make a function like that but couldn't figure it out. I have a column (I2:I48) with some values but also empty cells and I want to put let's say "123" in every empty cell and do nothing if cell has values already.

=IF(I2:II48 = "","123","")

This one isn't working for me. Thanks everybody for future help.


问:
Schema export with hibernate annotations
I'm using hibernate annotations and i want to export my database schema.

Similar to the schemaexporttask with hbm xml files.

答:
In case someone is interested how to do this with JPA+Spring from a unit test (you can generate the sql running the unit test from inside Eclipse like a breeze):

ExportDatabaseSchema.java:

```<code>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration(defaultRollback=true)
public class ExportDatabaseSchema {

  @Resource(name="&entityManagerFactory")
  private LocalContainerEntityManagerFactoryBean entityManagerFactory;

  @Test
  public void exportDatabaseSchema(){
    PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
    Map jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();

    Configuration configuration = new Ejb3Configuration().configure( persistenceUnitInfo, jpaPropertyMap ).getHibernateConfiguration();

    SchemaExport schema = new SchemaExport(configuration);
    schema.setOutputFile("resources/sql/schema.sql");
    schema.create(false, false);
  }
}
</code>```

You need an ExportDatabaseSchema-context.xml:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:p="http://www.springframework.org/schema/p"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<import resource="classpath:applicationContext-jpa.xml" />
</beans>
</code>```

The applicationContext-jpa.xml contains the annotation configured entityManagerFactory bean. The trick is to inject it with & like this: "&entityManagerFactory", to dereference the spring generated proxy.

Body:
In case someone is interested how to do this with JPA+Spring from a unit test (you can generate the sql running the unit test from inside Eclipse like a breeze):

ExportDatabaseSchema.java:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration(defaultRollback=true)
public class ExportDatabaseSchema {

  @Resource(name="&entityManagerFactory")
  private LocalContainerEntityManagerFactoryBean entityManagerFactory;

  @Test
  public void exportDatabaseSchema(){
    PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
    Map jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();

    Configuration configuration = new Ejb3Configuration().configure( persistenceUnitInfo, jpaPropertyMap ).getHibernateConfiguration();

    SchemaExport schema = new SchemaExport(configuration);
    schema.setOutputFile("resources/sql/schema.sql");
    schema.create(false, false);
  }
}

You need an ExportDatabaseSchema-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:p="http://www.springframework.org/schema/p"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<import resource="classpath:applicationContext-jpa.xml" />
</beans>

The applicationContext-jpa.xml contains the annotation configured entityManagerFactory bean. The trick is to inject it with & like this: "&entityManagerFactory", to dereference the spring generated proxy.


问:
where are the individual dataproc spark logs?
Where are the dataproc spark job logs located? I know there are logs from the driver under "Logging" section but what about the execution nodes? Also, where are the detailed steps that Spark is executing logged (I know I can see them in the Application Master)? I am attempting to debug a script that seems to hang and spark seems to freeze.</p>

答:
UPDATE in Q3 2022: This answer is outdated, see Dataproc YARN container logs location for the latest info.

The task logs are stored on each worker node under /tmp.

It is possible to collect them in one place via yarn log aggregation. Set these properties at cluster creation time (via --properties with yarn: prefix):

yarn.log-aggregation-enable=true

yarn.nodemanager.remote-app-log-dir=gs://${LOG_BUCKET}/logs

yarn.log-aggregation.retain-seconds=-1

Here's an article that discusses log management:

https://hortonworks.com/blog/simplifying-user-logs-management-and-access-in-yarn/


问:
Dygraphs - How do I restrict drawing to canvas
I have a graph where I am using underlays to draw vertical lines between the points. I have a line of code that restricts these vertical lines to NOT draw outside the active canvas. But when I use this underlayCallback, the 'points' are still drawn outside the canvas. If I remove my underlayCallback, the points are restricted to the canvas as one would expect. Here is what they look like and my code. (Sorry, the site is too secure to provide working sample.)

```<code>g[i] = new Dygraph(thisdiv, mylines, {
            labels: graphlbls[i],
            ylabel: graphunits[i].capitalizeFirstLetter(),
            xlabel: '',
            xLabelHeight:15,
            yLabelWidth:15,
            rightGap: 5,
            labelsDivStyles: {
                'text-align': 'right',
                'background': 'none'
            },
            colors: ['#D48513','#1D6EB5'],
            title: graphtitles[i],
            titleHeight:23,
            drawPoints: true,
            showRoller: false,
            drawXGrid: false,
            drawYGrid: true,
            strokeWidth: 0,
            pointSize: 4,
            highlightCircleSize: 6,
            gridLineColor: "#ddd",
            axisLabelFontSize: 12,
            xAxisHeight: 20,
            valueRange: [minval, maxval],
            rangeSelectorHeight: 30,
            showRangeSelector: true,
            rangeSelectorPlotFillColor: '#ffffff',
            rangeSelectorPlotStrokeColor: '#ffffff',
            interactionModel: Dygraph.defaultInteractionModel,
            axes: {
                x: {
                    valueFormatter: function (ms) {
                        var d = new Date(ms);
                        var day = "0"+d.getDate();
                        var month = "0"+(d.getMonth()+1);
                        var year = d.getFullYear();
                        var hour = "0"+ d.getHours();
                        var min = "0"+d.getMinutes();
                        var p = "AM";
                        if (hour > 12) { p = "PM"; hour = hour - 12; }
                        if (df == 0) var dd = month.slice(-2)+"/"+day.slice(-2)+"/"+year;
                        if (df == 1) var dd = day.slice(-2)+"/"+month.slice(-2)+"/"+year;
                        if (tf == 0) var tt = hour.slice(-2)+":"+min.slice(-2)+" "+p+" ";
                        if (tf == 1) var tt = hour.slice(-2)+":"+min.slice(-2)+" ";
                        return dd + " - " + tt;
                    }
                }
            },
            underlayCallback: function(ctx, area, g) {
                //if (typeof(g[i]) == 'undefined') return;  // won't be set on the initial draw.
                var range = g.xAxisRange();
                var rows = g.numRows();

                // get max and min y
                for (var i = 0; i < rows; i++) {
                    miny = 99999;
                    maxy = -99999;
                    xx = g.getValue(i,0);
                    if (xx < range[0] || xx > range[1]) continue;   // constrain to graph canvas
                    for (var j=1; j<= range.length; j++) {
                        if (g.getValue(i,j) <= miny) miny = g.getValue(i,j);
                        if (g.getValue(i,j) >= maxy) maxy = g.getValue(i,j);
                    }
                    p1 = g.toDomCoords(xx, miny);
                    p2 = g.toDomCoords(xx, maxy);
                    ctx.strokeStyle = "rgba(192,192,224,1)";
                    ctx.lineWidth = 1.0;
                    ctx.beginPath();
                    ctx.moveTo(p1[0], p1[1]);
                    ctx.lineTo(p2[0], p2[1]);
                    ctx.closePath();
                    ctx.stroke();
                    ctx.restore();
                }
            }
        });
</code>```

答:
You're calling ctx.restore() many times without corresponding calls to ctx.save(). This pops off dygraphs' own drawing context, including the clipping rectangle. Make one call to save at the top of your underlayCallback and one to restore at the end.

Stepping back a bit, what you're doing might be easier with a custom plotter, rather than an underlayCallback.

Body:
I have a graph where I am using underlays to draw vertical lines between the points. I have a line of code that restricts these vertical lines to NOT draw outside the active canvas. But when I use this underlayCallback, the 'points' are still drawn outside the canvas. If I remove my underlayCallback, the points are restricted to the canvas as one would expect. Here is what they look like and my code. (Sorry, the site is too secure to provide working sample.)

g[i] = new Dygraph(thisdiv, mylines, {
            labels: graphlbls[i],
            ylabel: graphunits[i].capitalizeFirstLetter(),
            xlabel: '',
            xLabelHeight:15,
            yLabelWidth:15,
            rightGap: 5,
            labelsDivStyles: {
                'text-align': 'right',
                'background': 'none'
            },
            colors: ['#D48513','#1D6EB5'],
            title: graphtitles[i],
            titleHeight:23,
            drawPoints: true,
            showRoller: false,
            drawXGrid: false,
            drawYGrid: true,
            strokeWidth: 0,
            pointSize: 4,
            highlightCircleSize: 6,
            gridLineColor: "#ddd",
            axisLabelFontSize: 12,
            xAxisHeight: 20,
            valueRange: [minval, maxval],
            rangeSelectorHeight: 30,
            showRangeSelector: true,
            rangeSelectorPlotFillColor: '#ffffff',
            rangeSelectorPlotStrokeColor: '#ffffff',
            interactionModel: Dygraph.defaultInteractionModel,
            axes: {
                x: {
                    valueFormatter: function (ms) {
                        var d = new Date(ms);
                        var day = "0"+d.getDate();
                        var month = "0"+(d.getMonth()+1);
                        var year = d.getFullYear();
                        var hour = "0"+ d.getHours();
                        var min = "0"+d.getMinutes();
                        var p = "AM";
                        if (hour > 12) { p = "PM"; hour = hour - 12; }
                        if (df == 0) var dd = month.slice(-2)+"/"+day.slice(-2)+"/"+year;
                        if (df == 1) var dd = day.slice(-2)+"/"+month.slice(-2)+"/"+year;
                        if (tf == 0) var tt = hour.slice(-2)+":"+min.slice(-2)+" "+p+" ";
                        if (tf == 1) var tt = hour.slice(-2)+":"+min.slice(-2)+" ";
                        return dd + " - " + tt;
                    }
                }
            },
            underlayCallback: function(ctx, area, g) {
                //if (typeof(g[i]) == 'undefined') return;  // won't be set on the initial draw.
                var range = g.xAxisRange();
                var rows = g.numRows();

                // get max and min y
                for (var i = 0; i < rows; i++) {
                    miny = 99999;
                    maxy = -99999;
                    xx = g.getValue(i,0);
                    if (xx < range[0] || xx > range[1]) continue;   // constrain to graph canvas
                    for (var j=1; j<= range.length; j++) {
                        if (g.getValue(i,j) <= miny) miny = g.getValue(i,j);
                        if (g.getValue(i,j) >= maxy) maxy = g.getValue(i,j);
                    }
                    p1 = g.toDomCoords(xx, miny);
                    p2 = g.toDomCoords(xx, maxy);
                    ctx.strokeStyle = "rgba(192,192,224,1)";
                    ctx.lineWidth = 1.0;
                    ctx.beginPath();
                    ctx.moveTo(p1[0], p1[1]);
                    ctx.lineTo(p2[0], p2[1]);
                    ctx.closePath();
                    ctx.stroke();
                    ctx.restore();
                }
            }
        });


问:
Samsung S7 Media Queries
I'm trying to use these media queries for S7 and it's not working
any other recommendations?</p>

```<code>@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 4)
  and (orientation: portrait) {

/* Style */

}
</code>```

答:
I've run into the same problem just now.

After some testing on my device I've found that a device-pixel-ratio of 3 is what targets my Galaxy S7.

Additionally,
I've found that the address bar is 75px tall if you wanna line something up with the fold.

This was in the Chrome browser.

Title: Samsung S7 Media Queries

Body:
I'm trying to use these media queries for S7 and it's not working
any other recommendations?

@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 4)
  and (orientation: portrait) {

/* Style */

}


问:
How to aggregate-initialize this struct?
I'm having a struct that I would like to initialize like this:

```<code>checkPoints someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};
</code>```

Basically a vector of position vectors initialization using aggregators.

This is working without problems:

```<code>std::vector<PosVec> someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};
</code>```

However I need to use struct in order to add some additional functionality.

My code:

```<code>struct mPosition {
    mPosition(int32_t x, int32_t y) : x(x), y(y) {}

    int32_t x;
    int32_t y;
};

typedef std::vector<mPosition> PosVec;

struct checkPoints {
    explicit checkPoints(std::vector<PosVec>& checkPoints) {
        checkPointsVec = checkPoints;
    };

    const PosVec& getRandom() const {
        return checkPointsVec[getRandomInt(0, checkPointsVec.size())];
    }

    std::vector<PosVec> checkPointsVec;
};

checkPoints someCheckpoints = { // no matching constructor
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};
</code>```

This is producing no matching constructor error. I would like it to use a proper vector-like aggregation constructor. Should my struct extend vector class
instead or would I be able to do this declaring my own constructor (which one)?

How can I solve this?

答:
std::vector is not represented by braces. When using in initialization, you're using std::initializer_list. And const is making a difference. So I would like to write

```<code>explicit checkPoints(const std::initializer_list<PosVec>& checkPoints)
                     ^~~~~      ^~~~~~~~~~~~~~~~
</code>```

In this way your constructor can catch literal constants.

Also, as Jarod42 noted in comments, an explicit constructor cannot be called like checkPoints a = {};. You can only call it like

```<code>checkPoints a { /* stuff */ };
checkPoints a ( /* stuff */ };
</code>```

Do note that you're using an rvalue initialization here, so it won't be catched by a non-const lvalue reference. It can only be catched by an rvalue reference or a const lvalue reference.

```<code>checkPoints someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
}; // This is an rvalue!
</code>```

Anyway, it's a good practice to declare parameters as const if you don't modify the reference in it.

Body:
I'm having a struct that I would like to initialize like this:

checkPoints someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};

Basically a vector of position vectors initialization using aggregators.

This is working without problems:

std::vector<PosVec> someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};

However I need to use struct in order to add some additional functionality.

My code:

struct mPosition {
    mPosition(int32_t x, int32_t y) : x(x), y(y) {}

    int32_t x;
    int32_t y;
};

typedef std::vector<mPosition> PosVec;

struct checkPoints {
    explicit checkPoints(std::vector<PosVec>& checkPoints) {
        checkPointsVec = checkPoints;
    };

    const PosVec& getRandom() const {
        return checkPointsVec[getRandomInt(0, checkPointsVec.size())];
    }

    std::vector<PosVec> checkPointsVec;
};

checkPoints someCheckpoints = { // no matching constructor
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};

This is producing no matching constructor error. I would like it to use a proper vector-like aggregation constructor. Should my struct extend vector class
instead or would I be able to do this declaring my own constructor (which one)?

How can I solve this?

Body:
std::vector is not represented by braces. When using in initialization, you're using std::initializer_list. And const is making a difference. So I would like to write

explicit checkPoints(const std::initializer_list<PosVec>& checkPoints)
                     ^~~~~      ^~~~~~~~~~~~~~~~

In this way your constructor can catch literal constants.

Also, as Jarod42 noted in comments, an explicit constructor cannot be called like checkPoints a = {};. You can only call it like

checkPoints a { /* stuff */ };
checkPoints a ( /* stuff */ };

Do note that you're using an rvalue initialization here, so it won't be catched by a non-const lvalue reference. It can only be catched by an rvalue reference or a const lvalue reference.

checkPoints someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
}; // This is an rvalue!

Anyway, it's a good practice to declare parameters as const if you don't modify the reference in it.