问:
How to avoid lists when analyzing order for palindromes?
Just want to apologize in advance for the general coding and logic gore you might encounter while reading this. I recently discovered Project Euler and thought it was fun. I've made it a point to not only find the answer, but make a generic function that could find the answer for any similar case given the appropriate input. For instance, problem number 4, involving palindromes, which can be seen here: https://projecteuler.net/problem=4

Essentially what I did was found a way to multiply every possible combination of numbers given a number of digits, n, then found products that were palindromes. However, anything above 3 digits just takes way too long to process. I believe this is because I used the list() function to take advantage of indexing to determine whether the product was a palindrome. Is there another way to do something of this nature? I feel like this is shoving a square through a circular hole.

Here's the function in question.

```<code>def palindrome(n):
    number = 0
    for i in range(0,n):
        number = number + 9 * pow(10, i)
    a = pow(10, n - 1) - 1
    b = pow(10, n - 1)
    while a * b < number * number:
        a = a + 1
        b = a
        while b <= number:
            c = a * b
            b = b + 1
            digits = list(str(int(c)))
            lastdigits = digits[::-1]
            numdigits = len(digits)
            middle = int((numdigits - (numdigits % 2)) / 2) - 1
            if numdigits > 1 and digits[:middle + 1] == lastdigits[:middle + 1] and digits[0] == digits[-1] == '9' and numdigits == 2 * n:
                print(c)
</code>```

答:
"Find the largest palindrome made from the product of two 3-digit numbers."

3-digit numbers would be anything from 100 - 999. One thing about the largest product is guaranteed: The two operands must be as large as possible.

Thus, it would make sense to step through a loop starting from the largest number (999) to the smallest (100). We can append palindromes to a list and then later return the largest one.

When you calculate a product, convert it to a string using str(...). Now, checking for palindromes is easy thanks to python's string splicing. A string is a palindrome if string == string[::-1], where string[::-1] does nothing but return a reversed copy of the original.

Implementing these strategies, we have:

```<code>def getBiggestPalindrome():
    max_palindrome = -1
    for i in range(999, 99, -1):
        for j in range(999, i - 1, -1):
            prod = i * j
            str_prod = str(prod)
            if str_prod == str_prod[::-1] and prod > max_palindrome:
                print(prod)
                max_palindrome = prod

    return max_palindrome
</code>```

getBiggestPalindrome()

And, this returns

```<code>>>> getBiggestPalindrome()
906609
</code>```

Note that you can use the range function to generate values from start, to end, with step. The iteration stops just before end, meaning the last value would be 100.

Body:
Just want to apologize in advance for the general coding and logic gore you might encounter while reading this. I recently discovered Project Euler and thought it was fun. I've made it a point to not only find the answer, but make a generic function that could find the answer for any similar case given the appropriate input. For instance, problem number 4, involving palindromes, which can be seen here: https://projecteuler.net/problem=4

Essentially what I did was found a way to multiply every possible combination of numbers given a number of digits, n, then found products that were palindromes. However, anything above 3 digits just takes way too long to process. I believe this is because I used the list() function to take advantage of indexing to determine whether the product was a palindrome. Is there another way to do something of this nature? I feel like this is shoving a square through a circular hole.

Here's the function in question.

def palindrome(n):
    number = 0
    for i in range(0,n):
        number = number + 9 * pow(10, i)
    a = pow(10, n - 1) - 1
    b = pow(10, n - 1)
    while a * b < number * number:
        a = a + 1
        b = a
        while b <= number:
            c = a * b
            b = b + 1
            digits = list(str(int(c)))
            lastdigits = digits[::-1]
            numdigits = len(digits)
            middle = int((numdigits - (numdigits % 2)) / 2) - 1
            if numdigits > 1 and digits[:middle + 1] == lastdigits[:middle + 1] and digits[0] == digits[-1] == '9' and numdigits == 2 * n:
                print(c)

Body:
"Find the largest palindrome made from the product of two 3-digit numbers."

3-digit numbers would be anything from 100 - 999. One thing about the largest product is guaranteed: The two operands must be as large as possible.

Thus, it would make sense to step through a loop starting from the largest number (999) to the smallest (100). We can append palindromes to a list and then later return the largest one.

When you calculate a product, convert it to a string using str(...). Now, checking for palindromes is easy thanks to python's string splicing. A string is a palindrome if string == string[::-1], where string[::-1] does nothing but return a reversed copy of the original.

Implementing these strategies, we have:

def getBiggestPalindrome():
    max_palindrome = -1
    for i in range(999, 99, -1):
        for j in range(999, i - 1, -1):
            prod = i * j
            str_prod = str(prod)
            if str_prod == str_prod[::-1] and prod > max_palindrome:
                print(prod)
                max_palindrome = prod

    return max_palindrome

getBiggestPalindrome()

And, this returns

>>> getBiggestPalindrome()
906609

Note that you can use the range function to generate values from start, to end, with step. The iteration stops just before end, meaning the last value would be 100.


来源: stackexchange

问:
MoviePy Error: The system cannot find the file specified
I'm getting the error in the title when trying to run the example code below on Windows 10/Python 3.6.1/Sublime Text Editor 3. I made sure to set my MAGICK_HOME environment variable to point to where I manually installed ImageMagick. I made sure to only have 1 version of ImageMagick installed. I made sure FFMPEG, Numpy, imageio, Decorator, and tqdm were all installed.

Yes, the file "vidclip.mp4" exists. The desired behavior here is to simply clip the video and add text to the center as per the example on the github page, i.e. to simply run the code successfully.

Does anyone know what might be wrong?

Example code from github:

```<code>from moviepy.editor import *

video = VideoFileClip("vidclip.mp4").subclip(7,64)

# Make the text. Many more options are available.
txt_clip = ( TextClip("Ken Block who?",fontsize=70,color='white')
             .set_position('center')
             .set_duration(10) )

result = CompositeVideoClip([video, txt_clip]) # Overlay text on video
result.write_videofile("vidclip_edited.webm",fps=25) # Many options...
</code>```

The full error trace:

```<code>Traceback (most recent call last):
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1220, in __init__
    subprocess_call(cmd, verbose=False )
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\tools.py", line 42, in subprocess_call
    proc = sp.Popen(cmd, **popen_params)
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 707, in __init__
    restore_signals, start_new_session)
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 990, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\av\Desktop\Desktop\Projects\Youtube\blender\test\testMoviePy.py", line 6, in <module>
    txt_clip = ( TextClip("Ken Block who?",fontsize=70,color='white')
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1229, in __init__
    raise IOError(error)
OSError: MoviePy Error: creation of None failed because of the following error:

[WinError 2] The system cannot find the file specified.

.This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or.that the path you specified is incorrect
</code>```

答: Found the problem. I didn't realize it was imperative that I specify the location of ffmpeg.exe and convert.exe within ImageMagick's config_defaults.py file. After that, I install MoviePy (in that order).

ContentLicense: CC BY-SA 3.0

Body:
I'm getting the error in the title when trying to run the example code below on Windows 10/Python 3.6.1/Sublime Text Editor 3. I made sure to set my MAGICK_HOME environment variable to point to where I manually installed ImageMagick. I made sure to only have 1 version of ImageMagick installed. I made sure FFMPEG, Numpy, imageio, Decorator, and tqdm were all installed.

Yes, the file "vidclip.mp4" exists. The desired behavior here is to simply clip the video and add text to the center as per the example on the github page, i.e. to simply run the code successfully.

Does anyone know what might be wrong?

Example code from github:

from moviepy.editor import *

video = VideoFileClip("vidclip.mp4").subclip(7,64)

# Make the text. Many more options are available.
txt_clip = ( TextClip("Ken Block who?",fontsize=70,color='white')
             .set_position('center')
             .set_duration(10) )

result = CompositeVideoClip([video, txt_clip]) # Overlay text on video
result.write_videofile("vidclip_edited.webm",fps=25) # Many options...

The full error trace:

Traceback (most recent call last):
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1220, in __init__
    subprocess_call(cmd, verbose=False )
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\tools.py", line 42, in subprocess_call
    proc = sp.Popen(cmd, **popen_params)
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 707, in __init__
    restore_signals, start_new_session)
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 990, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\av\Desktop\Desktop\Projects\Youtube\blender\test\testMoviePy.py", line 6, in <module>
    txt_clip = ( TextClip("Ken Block who?",fontsize=70,color='white')
  File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1229, in __init__
    raise IOError(error)
OSError: MoviePy Error: creation of None failed because of the following error:

[WinError 2] The system cannot find the file specified.

.This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or.that the path you specified is incorrect


问:
File permission in git
I run git repository with visual studio. I create website using MVC. How can I share source with my teammate but he can only read and write View folder not other file? It is important that he can't copy or change other file.
Thanks</p>

答:
Depending on which Git central repository you are using, you might have some options for setting permissions on specific branches which could be a way to control this.

However, in general Git terms, your teammate should only have read-only access to your central repository.  You can then use either branch or fork methodology with pull-requests to only allow changes you approve, back into the main repository.

Title: File permission in git


问:
Django runfcgi mode timeout
```<code>manage runfcgi host=127.0.0.1 port=8002 maxrequests=200 maxchildren=100 minchildren=4
</code>```

I started django fcgi in this way. It seems all right in processes monitor. But when I open http://127.0.0.1:8002, it keep runing and no result come out.

```<code>manage runserver 127.0.0.1:8002
</code>```

This method was fine. Does any one knows why?

答:
As explained in the Django docs on FastCGI:

FastCGI is an efficient way of letting
  an external application serve pages to
  a Web server. The Web server delegates
  the incoming Web requests (via a
  socket) to FastCGI, which executes the
  code and passes the response back to
  the Web server, which, in turn, passes
  it back to the client’s Web browser.

You're trying to connect directly to the FCGI process from your browser, which won't work: you need an FCGI-compliant webserver to handle your request and delegate it to Django.

See the Django docs for a thorough explanation of how to set this up.

ContentLicense: CC BY-SA 2.5

Title: Django runfcgi mode timeout

Body:
manage runfcgi host=127.0.0.1 port=8002 maxrequests=200 maxchildren=100 minchildren=4

I started django fcgi in this way. It seems all right in processes monitor. But when I open http://127.0.0.1:8002, it keep runing and no result come out.

manage runserver 127.0.0.1:8002

This method was fine. Does any one knows why?


问:
Visual Studio 2013 - How do I view output in the console?
I'm new to C# and VS and I'm just trying to print a line using Console.WriteLine(...) but it only shows up in the command prompt. Is there a way to make output show in the output window instead?

EDIT: It's a console application.

Also, how do I access the command line in order to run programs? I've only been able to figure out how to run with F5, but this won't work if I need to type in arguments.

答:
```<code>using System;
#region Write to Console
/*2 ways to write to console
 concatenation
 place holder syntax - most preferred
 Please note that C# is case sensitive language.
*/
#region
namespace _2__CShrp_Read_and_Write
{
    class Program
    {
        static void Main(string[] args)
        {

            // Prompt the user for his name
            Console.WriteLine("Please enter your name");

            // Read the name from console
            string UserName = Console.ReadLine();
            // Concatenate name with hello word and print
            //Console.WriteLine("Hello " + UserName);

            //place holder syntax
            //what goes in the place holder{0}
            //what ever you pass after the comma i.e. UserName
            Console.WriteLine("Hello {0}", UserName);
            Console.ReadLine();
        }
    }
}
I hope this helps
</code>```


问:
Why is print_r return value and 1
My class getting the name

```<code>public function getGameName($gameID){
    $gameIDValid = false;

    try {
        $db = database::databaseConnect();

        $getGame_stmt = $db->prepare('SELECT gameID, shortTitle FROM games WHERE gameID =:gameID');
        $getGame_stmt->bindParam(':gameID', $gameID, PDO::PARAM_INT);

        $getGame_stmt->execute();

        if($getGame_stmt->rowCount() == 1){
            $gameIDValid = true;
        }

        $db = NULL;

    } catch (PDOException $e) {
        $gameIDValid = false;
    }

    return $gameIDValid;

}
</code>```

From my class doing error checking

```<code>public function validategameID($gameID) {
    $validGame = userValidation::getGameName($gameID);
    if($validGame === false){
         return 'Problem adding your game';
    }
}
</code>```

My Validation code:

```<code>$validatedGameID = $validateUserInput->validategameID($gameID);
die($validatedGameID);
</code>```

If I choose a wrong Game ID I get the error message.  However when I use:

```<code>    die(print_r($validatedGameID));
</code>```

I get the following output:

```<code>Problem adding your game1
</code>```

If I use the correct Game ID I can't execute any other code after the:

```<code>die($validatedGameID);
</code>```

Can anyone please help?  Why is the function returning a 1 at the end of the error message when I use print_r and why can't I execute any code after the die even with a correct game id?

答:
The line:

```<code>die(print_r($validateGameID));
</code>```

performs the following steps:

Call print_r($validateGameID). This prints the value of $validateGameID, because that's what print_r() does when called with 1 argument.

Call die() with the return value of print_r(). print_r() returns TRUE when called with 1 argument. This performs the following steps:

Print 1, because TRUE becomes 1 when converted to a string.

Exit the script, because that's what die() does (it's just an alternate name for exit(), but by convention used when exiting because of an error)

So all together it prints $validateGameID, then prints 1, then exits the script.

Since it exits the script, nothing after it executes.

You can give print_r() a second argument to make it return the formatted version of its argument, rather than printing it:

```<code>die(print_r($validateGameID, true));
</code>```

Or you could simply call print_r() and die() seperately:

```<code>print_r($validateGameID);
die();
</code>```

Title: Why is print_r return value and 1

Body:
My class getting the name

public function getGameName($gameID){
    $gameIDValid = false;

    try {
        $db = database::databaseConnect();

        $getGame_stmt = $db->prepare('SELECT gameID, shortTitle FROM games WHERE gameID =:gameID');
        $getGame_stmt->bindParam(':gameID', $gameID, PDO::PARAM_INT);

        $getGame_stmt->execute();

        if($getGame_stmt->rowCount() == 1){
            $gameIDValid = true;
        }

        $db = NULL;

    } catch (PDOException $e) {
        $gameIDValid = false;
    }

    return $gameIDValid;

}

From my class doing error checking

public function validategameID($gameID) {
    $validGame = userValidation::getGameName($gameID);
    if($validGame === false){
         return 'Problem adding your game';
    }
}

My Validation code:

$validatedGameID = $validateUserInput->validategameID($gameID);
die($validatedGameID);

If I choose a wrong Game ID I get the error message.  However when I use:

    die(print_r($validatedGameID));

I get the following output:

Problem adding your game1

If I use the correct Game ID I can't execute any other code after the:

die($validatedGameID);

Can anyone please help?  Why is the function returning a 1 at the end of the error message when I use print_r and why can't I execute any code after the die even with a correct game id?

Body:
The line:

die(print_r($validateGameID));

performs the following steps:

Call print_r($validateGameID). This prints the value of $validateGameID, because that's what print_r() does when called with 1 argument.

Call die() with the return value of print_r(). print_r() returns TRUE when called with 1 argument. This performs the following steps:

Print 1, because TRUE becomes 1 when converted to a string.

Exit the script, because that's what die() does (it's just an alternate name for exit(), but by convention used when exiting because of an error)

So all together it prints $validateGameID, then prints 1, then exits the script.

Since it exits the script, nothing after it executes.

You can give print_r() a second argument to make it return the formatted version of its argument, rather than printing it:

die(print_r($validateGameID, true));

Or you could simply call print_r() and die() seperately:

print_r($validateGameID);
die();


问:
Emulate a mouse click without using the actual mouse on linux
I am working with a program that collects a lot of data then shows it to you in the program. Unfortunately, the program is poorly designed and requires you to "approve" each bit of data collected manually by clicking a checkbox to approve it. In order to automate this process, I wrote a small script that scans for a checkbox, clicks it, then clicks "next item".

Unfortunately, this requires moving the actual mouse, meaning I can't use my computer until the program has finished. There are other questions that reference automating this with the winapi, however none of these work on Linux. What is a way to automate this on Linux?

答:
You can simply start the program in a separate X server, for example using xvfb with

```<code>xvfb-run YOUR_PROGRAM
</code>```

If you want to wrap just the instrumented program, that's possible too:

```<code>export DISPLAY=:42
Xvfb :42
THE_INSTRUMENTED_PROGRAMM
xdotool mousemove 1 1 click 1 # your instrumentation goes here
</code>```

Body:
You can simply start the program in a separate X server, for example using xvfb with

xvfb-run YOUR_PROGRAM

If you want to wrap just the instrumented program, that's possible too:

export DISPLAY=:42
Xvfb :42
THE_INSTRUMENTED_PROGRAMM
xdotool mousemove 1 1 click 1 # your instrumentation goes here


问:
Exception in junit cases implementation for Spring batch
I am writing junit testcase for spring batch application.Code is given below

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { AppTest.BatchTestConfig.class })
public class AppTest {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Test
    public void demo() throws Exception {
        JobExecution jobExecution = jobLauncherTestUtils.launchJob();

        Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
    }

    @Configuration
    @EnableBatchProcessing
    static class BatchTestConfig {

        @Bean
        JobLauncherTestUtils jobLauncherTestUtils() {
            return new JobLauncherTestUtils();
        }

    }
}
</code>```

but the same is giving exception given below:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'jobLauncherTestUtils':
Unsatisfied dependency expressed through method 'setJob' parameter 0;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.batch.core.Job' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
</code>```

Please suggest

答:
This line:

@SpringBootTest(classes = { AppTest.BatchTestConfig.class })

loads your test configuration only, but that configuration doesn't contain a Job to test.  You need to include the configuration with your job in the classes array, for example:

@SpringBootTest(classes = { AppTest.BatchTestConfig.class, MyJobConfig.class })

Body:
I am writing junit testcase for spring batch application.Code is given below

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { AppTest.BatchTestConfig.class })
public class AppTest {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Test
    public void demo() throws Exception {
        JobExecution jobExecution = jobLauncherTestUtils.launchJob();

        Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
    }

    @Configuration
    @EnableBatchProcessing
    static class BatchTestConfig {

        @Bean
        JobLauncherTestUtils jobLauncherTestUtils() {
            return new JobLauncherTestUtils();
        }

    }
}

but the same is giving exception given below:

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'jobLauncherTestUtils':
Unsatisfied dependency expressed through method 'setJob' parameter 0;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.batch.core.Job' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

Please suggest


问:
Netty: getting remote ip address in messageReceived
In my class (extends SimpleChannelHandler) I'm trying to get the ip where the message was originally sent from.

```<code>@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent ev) throws Exception {
    String host = ((InetSocketAddress)ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress();
    int port = ((InetSocketAddress)ctx.getChannel().getRemoteAddress()).getPort();
    LOG.debug(String.format("host:%s port:%d", host, port));

    ..
</code>```

This prints ip 10.0.0.1 (gateway), instead of the correct client address (10.52.45.4).

Is there any way to get the ip i'm trying to or could there be something wrong with the network configuration ?

答: Ip addresses starting with 10.0.0 are internal, you are probably connecting it to something on the same WiFi router. To get the 10.52.45.4 ip, you have to connect outside of your router. (don't forget to port forward)</p>

Body:
In my class (extends SimpleChannelHandler) I'm trying to get the ip where the message was originally sent from.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent ev) throws Exception {
    String host = ((InetSocketAddress)ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress();
    int port = ((InetSocketAddress)ctx.getChannel().getRemoteAddress()).getPort();
    LOG.debug(String.format("host:%s port:%d", host, port));

    ..

This prints ip 10.0.0.1 (gateway), instead of the correct client address (10.52.45.4).

Is there any way to get the ip i'm trying to or could there be something wrong with the network configuration ?


Title: Yield and do operations on each 3 rows of DataFrame

Body:
I have this DataFrame, and would like to yield slices of 3 rows, returning a new DateFrame with all those 3 rows sets aggregated to one containing the highest date, the lowest open, highest high, and last close.

       date        open        high         low       close
0    1498907700  0.00010020  0.00010020  0.00009974  0.00010019
1    1498908000  0.00010010  0.00010010  0.00010010  0.00010010
2    1498908300  0.00010010  0.00010010  0.00009957  0.00009957
3    1498908600  0.00009957  0.00009957  0.00009957  0.00009957
4    1498908900  0.00010009  0.00010009  0.00009949  0.00009959
5    1498909200  0.00009987  0.00009991  0.00009956  0.00009956
...
789

Can I do sort of a groupby and apply a function on all those slices to yield a new DataSet?

The output DataSet should look like this :

       date        open        high         low       close
0   1498908300  0.00010010  0.00010020  0.00009957  0.00009957
1   1498909200  0.00009957  0.00010009  0.00009949  0.00009956
...
789

If the rows number are not a multiple of 3 I'd like to have the orphans processed in the first set of 3 rows.

Body:
You can use groupby and aggregate

df.groupby(df.index//3).agg({'date': 'max', 'open': 'min', 'high': 'max', 'low': 'min','close': 'last'})

You get

    date        open        high        low         close
0   1498908300  0.00010010  0.00010020  0.00009957  0.00009957
1   1498909200  0.00009957  0.00010009  0.00009949  0.00009956


问:
Change overview ruler color in Eclipse
How to change overview rule background color in Eclipse 3.4.0.I20080617-2000 (vertical bar on right of editing window with some annotations) ?

General > Editors > Text Editors > Annotations allows only to change colors of marks itself not background of whole bar.

It looks like my web searching skills are getting weaker since I cannot find it anywhere ...

答:
I have the same problem as Michal - this seems to be non-customisable.

I have trouble seeing some of the annotation marks in the overview ruler due to Vista's lighter colouring. You can change the colour of the marks, but the bar itself doesn't change colour.

It looks like the only way to change it is to change the system colours for all windows.

OwnerDisplayName: Michal Sznajder

Title: Change overview ruler color in Eclipse

LastEditorDisplayName: Michal Sznajder

OwnerDisplayName: phoglenix


问:
Print words using string module and ascii in python?
I was curious about how ASCII worked in python, so I decided to find out more. I learnt quite a bit, before I began to try to print letters using ASCII numbers. I'm not sure if I am doing it correctly, as I am using the string module, but I keep picking up an error

```<code>print(string.ascii_lowercase(104))
</code>```

This should print out "h", as far as I know, but all that happens is that I receive an error.

```<code>Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    string.ascii_lowercase(104)
TypeError: 'str' object is not callable
</code>```

If someone could help me solve this, or tell me a better way, I would be ever grateful. Thanks in advance! :)

答: ascii_lowercase is a string, not a function. Use chr(104).

Body:
I was curious about how ASCII worked in python, so I decided to find out more. I learnt quite a bit, before I began to try to print letters using ASCII numbers. I'm not sure if I am doing it correctly, as I am using the string module, but I keep picking up an error

print(string.ascii_lowercase(104))

This should print out "h", as far as I know, but all that happens is that I receive an error.

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    string.ascii_lowercase(104)
TypeError: 'str' object is not callable

If someone could help me solve this, or tell me a better way, I would be ever grateful. Thanks in advance! :)


问:
how to extract text from link (href) when its withing li.h3
How to extract text from  link (href) when its withing li.h3
follwoing is my code:

```<code><div class="lvpic pic img left" iid="263050872757">
        <div class="lvpicinner full-width picW">

<div class="triangle"></div>
        <div class="urgency"></div>
    <a class="img imgWr2" href="http://www.ebay.com/itm/LEGO-31313-Mindstorms-EV3-Robot-Technic-NEW-SEALED-/263050872757?epid=140182845&hash=item3d3f0dc7b5:g:4EIAAOSwLsBZS6bF">
                 <img class="img" alt="LEGO 31313 Mindstorms EV3 - Robot Technic ***NEW & SEALED***" src="https://i.ebayimg.com/thumbs/images/g/4EIAAOSwLsBZS6bF/s-l225.jpg">
            </a>
        </div></div>
<h3 class="lvtitle"><a title="Click this link to access LEGO 31313 Mindstorms EV3 - Robot Technic ***NEW & SEALED***" class="vip" href="http://www.ebay.com/itm/LEGO-31313-Mindstorms-EV3-Robot-Technic-NEW-SEALED-/263050872757?epid=140182845&hash=item3d3f0dc7b5:g:4EIAAOSwLsBZS6bF">LEGO 31313 Mindstorms EV3 - Robot Technic ***NEW & SEALED***</a>
    </h3>
</code>```

答:
Not sure if I'm understanding your question correctly. But if you are looking to grab the href in  tags, within the
 tags and parse it, you could do something like this. Hope that helps.

```<code> document.querySelector('.lvtitle .vip').href.split("/")
</code>```

This would be the results of the above query:

```<code> ["http:", "", "www.ebay.com", "itm", "LEGO-31313-Mindstorms-EV3-Robot-
 Technic-NEW-SEALED-", "263050872757?
 epid=140182845&hash=item3d3f0dc7b5:g:4EIAAOSwLsBZS6bF"]
</code>```

Body:
How to extract text from  link (href) when its withing li.h3
follwoing is my code:

LEGO 31313 Mindstorms EV3 - Robot Technic ***NEW & SEALED***

Body:
Not sure if I'm understanding your question correctly. But if you are looking to grab the href in <a> tags, within the <h3> tags and parse it, you could do something like this. Hope that helps.

 document.querySelector('.lvtitle .vip').href.split("/")

This would be the results of the above query:

 ["http:", "", "www.ebay.com", "itm", "LEGO-31313-Mindstorms-EV3-Robot-
 Technic-NEW-SEALED-", "263050872757?
 epid=140182845&hash=item3d3f0dc7b5:g:4EIAAOSwLsBZS6bF"]


问:
Symfony2 JMS Serializer - modify certain values
I have to work with an existing project and I have to modify some data before they are being serialized. A simple example:

This is what my serializer returns at the moment:

```<code>[
  {
    "id": 3,
    "reward": "reg"
  },
  {
    "id": 4,
    "reward": "inv"
  },
]
</code>```

And this is what I want returned:

```<code>[
  {
    "id": 3,
    "reward": "Registration"
  },
  {
    "id": 4,
    "reward": "inviting another user"
  },
]
</code>```

I want to rewrite stupid strings that come from the database to actually readable outputs. So I have to run a str_replace over certain fields from certain entities. How can I achieve this?

I tried creating my own visitor, but that seems to only have the possibility to change "visitString", which is not specific enough. Is there any other way to do this?

答:
I think you can simply use Accessor annotation to explicitly set the getter.

http://jmsyst.com/libs/serializer/master/reference/annotations#accessor

```<code>/** @JMS\Accessor(getter="getReward") */
private $reward;

public function getReward()
{
    switch ($this->reward) {
            case 'reg':
                return 'Registration';
            case 'inv':
                return 'inviting another user';
            default:
                return $this->reward;
        }
}
</code>```

Body:
I have to work with an existing project and I have to modify some data before they are being serialized. A simple example:

This is what my serializer returns at the moment:

[
  {
    "id": 3,
    "reward": "reg"
  },
  {
    "id": 4,
    "reward": "inv"
  },
]

And this is what I want returned:

[
  {
    "id": 3,
    "reward": "Registration"
  },
  {
    "id": 4,
    "reward": "inviting another user"
  },
]

I want to rewrite stupid strings that come from the database to actually readable outputs. So I have to run a str_replace over certain fields from certain entities. How can I achieve this?

I tried creating my own visitor, but that seems to only have the possibility to change "visitString", which is not specific enough. Is there any other way to do this?

Body:
I think you can simply use Accessor annotation to explicitly set the getter.

http://jmsyst.com/libs/serializer/master/reference/annotations#accessor

/** @JMS\Accessor(getter="getReward") */
private $reward;

public function getReward()
{
    switch ($this->reward) {
            case 'reg':
                return 'Registration';
            case 'inv':
                return 'inviting another user';
            default:
                return $this->reward;
        }
}


问:
security concerns with Perl /e modifier
Let's say that I have a Perl script which contains a substitution command which takes replacement string as a positional parameter and uses /e modifier:

```<code>perl -pe 's/abc/$ARGV[0]/ge;'
</code>```

Are there any security concerns with this approach? I mean is it possible to give such positional parameter value which causes perl to execute an unwanted function? I mean something similar: perl -pe 's/abc//;unlink ("/tmp/file");'.

答:
```<code>perl -pe 's/abc/$ARGV[0]/ge'
</code>```

Are there any security concerns with this approach? I mean is it possible to give such positional parameter value which causes perl to execute an unwanted function?

In
perldoc perlop
in the section
Regexp Quote-Like Operators
it explains

e Evaluate the right side as an expression

ee Evaluate the right side as a string then eval the result.

But this isn't entirely true. In both cases the "right side"—the replacement—is evaluated as if it were a do block†. In the  first case the result provides the replacement string, while in the second the result is passed to eval and the result of that provides the replacement string. There is no distinction whereby the replacement is evaluated as an "expression" in the first place and as a "string" in the second.

Both /e and /ee allow for any valid Perl code sequence, including loops, conditionals, and multiple statements, and aren't limited to a single expression

There's never anything wrong with $ARGV[0] in isolation. Tainted strings become dangerous only if you execute them, either as Perl, using eval, or as shell code using system, qx//, or backticks. So it's fine in the replacement part of a substitution with a single /e modifier

But if you use something else in the replacement, for instance

```<code>perl -pe 's/abc/qx{$ARGV[0]}/eg'
</code>```

then that parameter will be executed as a shell command, so it clearly isn't safe. But then nor is

```<code>perl -pe 's/abc/unlink glob "*.*"/eg'
</code>```

so you have to be sensible about it

What is dangerous is the double-e modifier /ee, which treats the replacement as a Perl do block and then does an eval on the result. So something like

```<code>    s/abc/$ARGV[0]/eeg
</code>```

is very unsafe, because you could run your code like this

```<code>    perl -pe 's/abc/$ARGV[0]/eeg' 'unlink glob *.*'
</code>```

With just a single /e this would just replace abc with the string
unlink glob *.*
in $ARGV[0]. But using /ee, the string is passed to eval and all your files are deleted!

Remember this:

/e — replacement is an expression (a do block)

/ee — replacement is an expression (a do block) and the result is passed to eval

†
This is why I choose to use braces to delimit substitutions that use one of the /e modes. With
s{abc}{ $ARGV[0] }ge the replacement looks much more like the block of code that it is than if I had used the usual slashes

Title: security concerns with Perl /e modifier

Body:
Let's say that I have a Perl script which contains a substitution command which takes replacement string as a positional parameter and uses /e modifier:

perl -pe 's/abc/$ARGV[0]/ge;'

Are there any security concerns with this approach? I mean is it possible to give such positional parameter value which causes perl to execute an unwanted function? I mean something similar: perl -pe 's/abc//;unlink ("/tmp/file");'.

Body:
perl -pe 's/abc/$ARGV[0]/ge'

Are there any security concerns with this approach? I mean is it possible to give such positional parameter value which causes perl to execute an unwanted function?

In
perldoc perlop
in the section
Regexp Quote-Like Operators
it explains

e Evaluate the right side as an expression

ee Evaluate the right side as a string then eval the result.

But this isn't entirely true. In both cases the "right side"—the replacement—is evaluated as if it were a do block†. In the  first case the result provides the replacement string, while in the second the result is passed to eval and the result of that provides the replacement string. There is no distinction whereby the replacement is evaluated as an "expression" in the first place and as a "string" in the second.

Both /e and /ee allow for any valid Perl code sequence, including loops, conditionals, and multiple statements, and aren't limited to a single expression

There's never anything wrong with $ARGV[0] in isolation. Tainted strings become dangerous only if you execute them, either as Perl, using eval, or as shell code using system, qx//, or backticks. So it's fine in the replacement part of a substitution with a single /e modifier

But if you use something else in the replacement, for instance

perl -pe 's/abc/qx{$ARGV[0]}/eg'

then that parameter will be executed as a shell command, so it clearly isn't safe. But then nor is

perl -pe 's/abc/unlink glob "*.*"/eg'

so you have to be sensible about it

What is dangerous is the double-e modifier /ee, which treats the replacement as a Perl do block and then does an eval on the result. So something like

    s/abc/$ARGV[0]/eeg

is very unsafe, because you could run your code like this

    perl -pe 's/abc/$ARGV[0]/eeg' 'unlink glob *.*'

With just a single /e this would just replace abc with the string
unlink glob *.*
in $ARGV[0]. But using /ee, the string is passed to eval and all your files are deleted!

Remember this:

/e — replacement is an expression (a do block)

/ee — replacement is an expression (a do block) and the result is passed to eval

†
This is why I choose to use braces to delimit substitutions that use one of the /e modes. With
s{abc}{ $ARGV[0] }ge the replacement looks much more like the block of code that it is than if I had used the usual slashes


问:
R Passing Name of List Objects to List Objects Themselves
I receive a named list of data frames using an R API to a data vendor. Below is how I would struct a similar structure.

```<code>spec1 <- data.frame(speed = 100, wt = 5, price = 10)
spec2 <- data.frame(speed = 1000, wt = 1, price = 100)
spec3 <- data.frame(speed = 1, wt = 50, price = 5)
mylist <- list(car = spec1,exotic = spec2, truck = spec3)
</code>```

My goal is to turn this into a flat data frame like below so that I can export it into an SQL database.

```<code>car_type   speed     wt     price
--------   ------    ----   -----
car        100       5      10
exotic     1000      1      100
truck      1         50     5
</code>```

My problem is that the identifier for "car_type" is stored as the name of the data frame in the list, and I don't know how to pass it to a repeat function to populate the table.

For example I use the following to get the car_type from the names of the items in the list

```<code>car_type <- sapply(seq_along(mylist), function(x) names(mylist)[x])
</code>```

And then I use the following to repeat the a car_type (substituted by "X") in the underlying tables and then append.

```<code>category <- lapply(mylist, function(y) rep("X" ,dim(y)[1]))
mylist <- lapply(seq_along(mylist), function(x)
</code>```

However, I can't seem to manage to pass the names found in car_type back into create a new category column in my dataset, which will persist when it's flattened.

答:
Or a base R option would be with Map to create the 'car_type' from the names of 'mylist' and then rbind the list elements

```<code>do.call(rbind, unname(Map(cbind, car_type = names(mylist), mylist)))
#   car_type speed wt price
#1      car   100  5    10
#2   exotic  1000  1   100
#3    truck     1 50     5
</code>```

Body:
I receive a named list of data frames using an R API to a data vendor. Below is how I would struct a similar structure.

spec1 <- data.frame(speed = 100, wt = 5, price = 10)
spec2 <- data.frame(speed = 1000, wt = 1, price = 100)
spec3 <- data.frame(speed = 1, wt = 50, price = 5)
mylist <- list(car = spec1,exotic = spec2, truck = spec3)

My goal is to turn this into a flat data frame like below so that I can export it into an SQL database.

car_type   speed     wt     price
--------   ------    ----   -----
car        100       5      10
exotic     1000      1      100
truck      1         50     5

My problem is that the identifier for "car_type" is stored as the name of the data frame in the list, and I don't know how to pass it to a repeat function to populate the table.

For example I use the following to get the car_type from the names of the items in the list

car_type <- sapply(seq_along(mylist), function(x) names(mylist)[x])

And then I use the following to repeat the a car_type (substituted by "X") in the underlying tables and then append.

category <- lapply(mylist, function(y) rep("X" ,dim(y)[1]))
mylist <- lapply(seq_along(mylist), function(x)

However, I can't seem to manage to pass the names found in car_type back into create a new category column in my dataset, which will persist when it's flattened.

Body:
Or a base R option would be with Map to create the 'car_type' from the names of 'mylist' and then rbind the list elements

do.call(rbind, unname(Map(cbind, car_type = names(mylist), mylist)))
#   car_type speed wt price
#1      car   100  5    10
#2   exotic  1000  1   100
#3    truck     1 50     5


问:
Why can't I restore this model?
I am currently having trouble restoring this model to make a prediction.

Code:

def neural_network(data):
    with tf.name_scope("network"):
        layer1 = tf.layers.dense(data, 1000, activation=tf.nn.relu, name="hidden_layer1")
        layer2 = tf.layers.dense(layer1, 1000, activation=tf.nn.relu, name="hidden_layer2")
        output = tf.layers.dense(layer2, 2, name="output_layer")

        return output

def evaluate():
    with tf.name_scope("loss"):
        global x
        xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=neural_network(x))
        loss = tf.reduce_mean(xentropy, name="loss")

    with tf.name_scope("train"):
        optimizer = tf.train.AdamOptimizer()
        training_op = optimizer.minimize(loss)

    with tf.name_scope("exec"):
        with tf.Session() as sess:
            for i in range(1, 10):
                sess.run(tf.global_variables_initializer())
                sess.run(training_op, feed_dict={x: np.array(train_data).reshape([-1, 1]), y: label})
                print "Training " + str(i)
                saver = tf.train.Saver()
                saver.save(sess, "saved_models/testing")
                print "Model Saved."

def predict():
    with tf.name_scope("predict"):
        output = neural_network(x)
        output = tf.nn.softmax(output)

        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            # saver = tf.train.Saver()
            saver.restore(sess, "saved_models/testing")
            print sess.run(output, feed_dict={x: np.array([12003]).reshape([-1, 1])})
```

<p>I have tried using <code>tf.train.Saver()</code> to restore but also gives the same error.</p>

```The error given is ValueError: Variable hidden_layer1/kernel already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:
```

I have tried setting reuse=True for tf.layers.dense() but it results in me unable to train the graph (gives the same ValueError as above but asking to set reuse=None).

I am guessing it has to do with the graph still existing in the session so when I try to restore it, it detects a duplicate graph. However, I thought this should not happen as the session have already closed.

link to entire code: gistlink

答:
I think you are loading the variables in the same graph. For testing try to create a new graph and load it. Do something like this:

loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
   # Load the graph with the trained states
```

Title: Why can't I restore this model?

Body:
I am currently having trouble restoring this model to make a prediction.

Code:

def neural_network(data):
    with tf.name_scope("network"):
        layer1 = tf.layers.dense(data, 1000, activation=tf.nn.relu, name="hidden_layer1")
        layer2 = tf.layers.dense(layer1, 1000, activation=tf.nn.relu, name="hidden_layer2")
        output = tf.layers.dense(layer2, 2, name="output_layer")

        return output

def evaluate():
    with tf.name_scope("loss"):
        global x
        xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=neural_network(x))
        loss = tf.reduce_mean(xentropy, name="loss")

    with tf.name_scope("train"):
        optimizer = tf.train.AdamOptimizer()
        training_op = optimizer.minimize(loss)

    with tf.name_scope("exec"):
        with tf.Session() as sess:
            for i in range(1, 10):
                sess.run(tf.global_variables_initializer())
                sess.run(training_op, feed_dict={x: np.array(train_data).reshape([-1, 1]), y: label})
                print "Training " + str(i)
                saver = tf.train.Saver()
                saver.save(sess, "saved_models/testing")
                print "Model Saved."

def predict():
    with tf.name_scope("predict"):
        output = neural_network(x)
        output = tf.nn.softmax(output)

        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            # saver = tf.train.Saver()
            saver.restore(sess, "saved_models/testing")
            print sess.run(output, feed_dict={x: np.array([12003]).reshape([-1, 1])})

I have tried using tf.train.Saver() to restore but also gives the same error.

The error given is ValueError: Variable hidden_layer1/kernel already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

I have tried setting reuse=True for tf.layers.dense() but it results in me unable to train the graph (gives the same ValueError as above but asking to set reuse=None).

I am guessing it has to do with the graph still existing in the session so when I try to restore it, it detects a duplicate graph. However, I thought this should not happen as the session have already closed.

link to entire code: gistlink


问:
Scale div to browser height vh troubles
I want the content inside of my div to scale with the browser vertically to prevent the need for scrolling The images will be different orientations so the width will be different. I know this can be achieved horizontally with width:100%; but max-height:100%; or height:auto; both still extend past the browser window for me and I'm not sure why.

EDIT: Had a lot of additional modal code in here, and simplified it down to the html/css and switched from simple width:100% height: 100% to vh and vw.

Fiddle :https://jsfiddle.net/duckyduck/6soe8zs0/

What's happening:

How I want it to look:

```<code><body>
<style>

.modal {
  display: block;
  position: fixed;
  z-index: 1;
  box-sizing:border-box;

  left: 0;
  top: 0;
height: 100%;
width:100%;

  overflow:auto;
  background-color:#D81E21;
}

.modal-content {
  position: relative;/*modal x button */
  width: auto;
  height: auto;
  background-color: #7E7DE1;
  max-height: 50vh;
  max-width:70vw;
  margin: auto;
  }

.mySlides{
    max-height:100%;
    max-width: 100%;
    height:auto;
    width:auto;
}

.roll-img {
display:flex;
flex-wrap:wrap;
}

.column {
flex:1;
}

.caption-container {
  text-align: center;
  background-color: black;
  padding: 2px 16px;
  color: white;
}

</style>

<div id="myModal" class="modal">

    <div class="modal-content">

        <div class="mySlides">
          <img src="images/5_2.jpg">
        </div>

        <div class="caption-container">
          <p id="caption"></p>
        </div>

      <div class="roll-img">
        <div class="column">
            <img class="demo cursor" src="images/5_2.jpg">
        </div>
      </div> <!--roll-img-->

  </div> <!--modal-content-->
</div> <!--myModal-->

</body>
</code>```

答:
As your .modal-content width is 30%. it might help

```<code>.modal-content .mySlides img {
   position: relative;
   width: 100%;
   height: auto;
}
</code>```

to fit image in 30% width of model content

Title: Scale div to browser height vh troubles

Body:
As your .modal-content width is 30%. it might help

.modal-content .mySlides img {
   position: relative;
   width: 100%;
   height: auto;
}

to fit image in 30% width of model content


问:
Cordova - download image from URL to the pictures gallery
I created a simple cordova android app and I am trying to download an image from an URL to the pictures gallery, but I really can't figure out what is going wrong.
I have already searched a lot here in stackoverflow, including the following links:

Phonegap - Save image from url into device photo gallery

How to save an Image object into a file in Android with Phonegap?

I have installed cordova File Transfer plugin and tried to do the example from the official site, but it didn't work too: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file-transfer/

I tried 2 different codes, which are:

1) First attempt:

```<code>document.getElementById("myBtn").addEventListener("click", function () {
    download("http://cordova.apache.org/static/img/cordova_bot.png", "data", "new_file");
});

function download(URL, Folder_Name, File_Name) {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);

    function fileSystemSuccess(fileSystem) {
        var download_link = encodeURI(URL);
        ext = download_link.substr(download_link.lastIndexOf('.') + 1); //Get extension of URL

        var directoryEntry = fileSystem.root; // to get root path of directory
        directoryEntry.getDirectory(Folder_Name, {
            create: true,
            exclusive: false
        }, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
        var rootdir = fileSystem.root;
        var fp = rootdir.toURL();
        fp = fp + "/" + Folder_Name + "/" + File_Name + "." + ext; // fullpath and name of the file which we want to give
        filetransfer(download_link, fp);
    }

    function onDirectorySuccess(parent) {
        // Directory created successfuly
    }

    function onDirectoryFail(error) {
        alert("Unable to create new directory: " + error.code);
    }

    function fileSystemFail(evt) {
        //Unable to access file system
        alert(evt.target.error.code);
    }
}

function filetransfer(download_link, fp) {
    var fileTransfer = new FileTransfer();
    fileTransfer.download(download_link, fp,
        function (entry) {
            alert("download complete: " + entry.fullPath);
            //cordova.plugins.imagesaver.saveImageToGallery(entry.fullPath, successCallback, errorCallback);
        },
        function (error) {
            alert("download error source " + error.source);
        }
    );
}
</code>```

In this attempt, I get the alert message "download complete: /my_folder/new_file.png" but I can't find where the picture is downloaded.
It is definitely not in the pictures gallery or anywhere I can find it.

2) Second attempt:

```<code>function download() {
    window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {

        var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
        fs.root.getFile('downloaded-image.png', {
            create: true,
            exclusive: false
        }, function (fileEntry) {
            file_transfer(fileEntry, encodeURI(url), true);

        }, onErrorCreateFile);

    }, onErrorLoadFs);
}

function onErrorLoadFs(msg){
    alert(msg);
}

function onErrorCreateFile(msg){
    alert(msg);
}

function file_transfer(fileEntry, uri, readBinaryData) {

    var fileTransfer = new FileTransfer();
    var fileURL = fileEntry.toURL();

    fileTransfer.download(
        uri,
        fileURL,
        function (entry) {
            alert("download complete: " + entry.toURL());

            if (readBinaryData) {
                // Read the file...
                readBinaryFile(entry);
            } else {
                // Or just display it.
                displayImageByFileURL(entry);
            }

        },
        function (error) {
            alert("download error source " + error.source);
            alert("download error target " + error.target);
            alert("upload error code" + error.code);
        },
        null, // or, pass false
        {
            //headers: {
            //    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
            //}
        }
    );
}
</code>```

In this attempt, I get the alert message "download complete: file:///data/user/0/com.companyname.xxxxxxx/cache/downloaded-image.png", but I also can't find the picture anywhere in the device.

I have already tried the application in two different android devices.

答:
You should change the line

```<code>window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024,
->
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
</code>```

and
if download success, you should re-scan your device storage, because Cordova does not know if the file is downloaded.

so i made a plugin ,

It is a plugin that updates the gallery after downloading.

https://github.com/pouu69/cordova-plugin-gallery-refresh

Body:
I created a simple cordova android app and I am trying to download an image from an URL to the pictures gallery, but I really can't figure out what is going wrong.
I have already searched a lot here in stackoverflow, including the following links:

Phonegap - Save image from url into device photo gallery

How to save an Image object into a file in Android with Phonegap?

I have installed cordova File Transfer plugin and tried to do the example from the official site, but it didn't work too: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file-transfer/

I tried 2 different codes, which are:

1) First attempt:

document.getElementById("myBtn").addEventListener("click", function () {
    download("http://cordova.apache.org/static/img/cordova_bot.png", "data", "new_file");
});

function download(URL, Folder_Name, File_Name) {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);

    function fileSystemSuccess(fileSystem) {
        var download_link = encodeURI(URL);
        ext = download_link.substr(download_link.lastIndexOf('.') + 1); //Get extension of URL

        var directoryEntry = fileSystem.root; // to get root path of directory
        directoryEntry.getDirectory(Folder_Name, {
            create: true,
            exclusive: false
        }, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
        var rootdir = fileSystem.root;
        var fp = rootdir.toURL();
        fp = fp + "/" + Folder_Name + "/" + File_Name + "." + ext; // fullpath and name of the file which we want to give
        filetransfer(download_link, fp);
    }

    function onDirectorySuccess(parent) {
        // Directory created successfuly
    }

    function onDirectoryFail(error) {
        alert("Unable to create new directory: " + error.code);
    }

    function fileSystemFail(evt) {
        //Unable to access file system
        alert(evt.target.error.code);
    }
}

function filetransfer(download_link, fp) {
    var fileTransfer = new FileTransfer();
    fileTransfer.download(download_link, fp,
        function (entry) {
            alert("download complete: " + entry.fullPath);
            //cordova.plugins.imagesaver.saveImageToGallery(entry.fullPath, successCallback, errorCallback);
        },
        function (error) {
            alert("download error source " + error.source);
        }
    );
}

In this attempt, I get the alert message "download complete: /my_folder/new_file.png" but I can't find where the picture is downloaded.
It is definitely not in the pictures gallery or anywhere I can find it.

2) Second attempt:

function download() {
    window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {

        var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
        fs.root.getFile('downloaded-image.png', {
            create: true,
            exclusive: false
        }, function (fileEntry) {
            file_transfer(fileEntry, encodeURI(url), true);

        }, onErrorCreateFile);

    }, onErrorLoadFs);
}

function onErrorLoadFs(msg){
    alert(msg);
}

function onErrorCreateFile(msg){
    alert(msg);
}

function file_transfer(fileEntry, uri, readBinaryData) {

    var fileTransfer = new FileTransfer();
    var fileURL = fileEntry.toURL();

    fileTransfer.download(
        uri,
        fileURL,
        function (entry) {
            alert("download complete: " + entry.toURL());

            if (readBinaryData) {
                // Read the file...
                readBinaryFile(entry);
            } else {
                // Or just display it.
                displayImageByFileURL(entry);
            }

        },
        function (error) {
            alert("download error source " + error.source);
            alert("download error target " + error.target);
            alert("upload error code" + error.code);
        },
        null, // or, pass false
        {
            //headers: {
            //    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
            //}
        }
    );
}

In this attempt, I get the alert message "download complete: file:///data/user/0/com.companyname.xxxxxxx/cache/downloaded-image.png", but I also can't find the picture anywhere in the device.

I have already tried the application in two different android devices.

Body:
You should change the line

window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024,
->
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,

and
if download success, you should re-scan your device storage, because Cordova does not know if the file is downloaded.

so i made a plugin ,

It is a plugin that updates the gallery after downloading.

https://github.com/pouu69/cordova-plugin-gallery-refresh


问:
Vim getting indentation wrong for Python code (with the python-mode Plugin)
As shown in the following screen-cast, I demonstrate the strange behaviors of Vim when it comes to adding comments to Python code. Between Demo 1 and Demo 2, I was only starting the line of comments at different indentation level (inside a class definition).

Demo 1

Demo 2

The problem:

As demonstrated towards the end of screen-cast, only typing : in insert mode will get the indentation right.

An ideal solution would achieve:

That when starting a line of comment, please leave the indentation level correctly;

答:
This sounds like a vim setting issue. Starting with vanilla vim, there is no indenting on each line, when I create a new line. If I create a file called .vimrc in my home directory. i.e. ~/.vimrc and put

filetype indent plugin on

in the file, I get what seems like expected indenting behavior. Does that work for you.


答:
The chr() function returns the corresponding character to the ASCII value you put in.

The ord() function returns the ASCII value of the character you put in.

Example:

```<code>chr(104) = 'h'
ord('h') = 104
</code>```

Title: Print words using string module and ascii in python?

Body:
The chr() function returns the corresponding character to the ASCII value you put in.

The ord() function returns the ASCII value of the character you put in.

Example:

chr(104) = 'h'
ord('h') = 104


答:
I guess what you want is chr

```<code>>>> chr(104)
'h'
</code>```

Body:
I guess what you want is chr

>>> chr(104)
'h'


问:
iOS audio samples play only on earphone output
I'm developing a program that plays a short sample when a button is pressed. The problem is that it only plays through earphone output and not through the device's speaker. I've tried .wav and .aiff and AVAudioPlayer and SystemSoundID. On the simulator I can hear the sound. I'm using iPod Touch 4th gen. running iOS 4.1. Example code:

```<code>NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"button" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:soundFile];
AudioServicesCreateSystemSoundID( (CFURLRef)url, &buttonID);
AudioServicesPlaySystemSound( buttonID );
</code>```

Edit (solution found): I tried with another .wav file and it worked. Odd, because the original .wav's format is supported by iOS.

答:
Sounds like you've solved the issue, but as a heads-up, you should only be using SystemSoundID style playback for user interface related sounds.

If the audio is a key part of your app, you need to set the appropriate AVAudioSession category and use (for example) the AVAudioPlayer playback methods.

Then again, this might not be relevant. :-)

Body:
I'm developing a program that plays a short sample when a button is pressed. The problem is that it only plays through earphone output and not through the device's speaker. I've tried .wav and .aiff and AVAudioPlayer and SystemSoundID. On the simulator I can hear the sound. I'm using iPod Touch 4th gen. running iOS 4.1. Example code:

NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"button" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:soundFile];
AudioServicesCreateSystemSoundID( (CFURLRef)url, &buttonID);
AudioServicesPlaySystemSound( buttonID );

Edit (solution found): I tried with another .wav file and it worked. Odd, because the original .wav's format is supported by iOS.


问:
Optimizing Apply() In R
The goal of the below code is to perform recursive and iterative analysis on a data set that has 400 columns and 6000 rows. It takes, two columns at a time and performs analysis on it, before moving to all the possible combinations.

Small sub set of large data set being used:

  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.71397
-0.710585   -0.714491   -0.710223   -0.713885
-0.710414   -0.714092   -0.710166   -0.71434
-0.711255   -0.714116   -0.70945    -0.714173
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644
```

<p><strong>Code using <code>apply()</code>:</strong></p>

```# Function
analysisFunc <- function () {

    # Fetch next data to be compared
    nextColumn <<- currentColumn + 1

    while (nextColumn <= ncol(Data)){

        # Fetch the two columns on which to perform analysis
        c1 <- Data[, currentColumn]
        c2 <- Data[, nextColumn]

        # Create linear model
        linearModel <- lm(c1 ~ c2)

        # Capture model data from summary
        modelData <- summary(linearModel)

        # Residuals
        residualData <- t(t(modelData$residuals))

        # Keep on appending data
        linearData <<- cbind(linearData, residualData)

        # Fetch next column
        nextColumn <<- nextColumn + 1

    }

    # Increment the counter
    currentColumn <<- currentColumn + 1

}

# Apply on function
apply(Data, 2, function(x) analysisFunc ())
```

I thought instead of using loops, apply() will help me optimize the code. However, it seems to have no major effect. Run time is more than two hours.

Does anyone think, I am going wrong on how apply() has been used? Is having while() within apply() call not a good idea? Any other way I can improve this code?

This is first time I am working with functional programming. Please let me know your suggestion, thanks.

答:
Consider an expand.grid of column names and then using mapply the multiple input version of apply family where you pass two+ vectors/lists and run a function across each input elementwise. With this approach you avoid expanding vectors within looping and running an inner while loop:

Data

```<code>Data <- read.table(text="  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.71397
-0.710585   -0.714491   -0.710223   -0.713885
-0.710414   -0.714092   -0.710166   -0.71434
-0.711255   -0.714116   -0.70945    -0.714173
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644", header=TRUE)
</code>```

Process

```<code># Data frame of all combinations excluding same columns
modelcols <- subset(expand.grid(c1=names(Data), c2=names(Data),
                    stringsAsFactors = FALSE), c1!=c2)

# Function
analysisFunc <- function(x,y) {
      # Fetch the two columns on which to perform analysis
      c1 <- Data[[x]]
      c2 <- Data[[y]]

      # Create linear model
      linearModel <- lm(c1 ~ c2)

      # Capture model data from summary
      modelData <- summary(linearModel)

      # Residuals
      residualData <- modelData$residuals
}

# Apply function to return matrix of residuals
linearData <- mapply(analysisFunc, modelcols$c1, modelcols$c2)
# re-naming matrix columns
colnames(linearData) <- paste(modelcols$c1, modelcols$c2, sep="_")
</code>```

Output

```<code>    data2_data1   data3_data1   data4_data1   data1_data2   data3_data2   data4_data2
1  1.440828e-04  8.629813e-05  1.514109e-04  5.583917e-04 -0.0001205821  2.866488e-04
2 -6.949384e-04 -2.508770e-04 -2.487813e-04 -1.005367e-04 -0.0001263202 -2.145225e-04
3  2.132192e-04 -4.609125e-04  4.551430e-04 -8.715424e-05 -0.0004593840  4.133856e-04
4  3.692403e-04  2.182627e-04 -1.116648e-04  3.835538e-04  0.0000408864 -4.244855e-05
5 -2.025772e-04 -4.032600e-04  5.442655e-05 -8.423568e-05 -0.0003484501  4.986815e-05
6  2.336373e-04 -2.838073e-04 -4.425935e-04  1.967203e-04 -0.0003805576 -4.109706e-04
7  2.661145e-05  1.250425e-04 -6.893342e-05 -6.508936e-04  0.0003408023 -2.436194e-04
8  1.456357e-04  3.991303e-04 -2.496687e-05 -3.501856e-04  0.0004980726 -1.304535e-04
9 -2.349110e-04  5.701233e-04  2.359596e-04  1.343401e-04  0.0005555326  2.921120e-04
    data1_data3   data2_data3   data4_data3   data1_data4   data2_data4   data3_data4
1  5.121547e-04  4.313395e-05  2.829814e-04  4.232081e-04  1.795365e-05 -9.584175e-05
2 -1.649379e-06 -6.684696e-04 -2.349827e-04  1.975728e-04 -7.112598e-04 -3.014160e-04
3 -2.942277e-04  3.141257e-04  4.029018e-04 -3.420290e-04  2.382149e-04 -3.760631e-04
4  3.371847e-04  2.859362e-04 -3.420612e-05  3.168009e-04  3.048006e-04  1.062117e-04
5 -1.651011e-04 -1.308671e-04  3.332034e-05 -5.127719e-05 -1.969902e-04 -3.890484e-04
6  2.550032e-05  2.586674e-04 -4.196917e-04  3.235528e-04  2.115955e-04 -3.627735e-04
7 -5.692790e-04  1.157675e-04 -2.277195e-04 -5.922595e-04  1.840773e-04  3.645036e-04
8 -2.258187e-04  1.445371e-04 -1.077903e-04 -3.583290e-04  2.386756e-04  5.422018e-04
9  3.812360e-04 -3.628313e-04  3.051868e-04  8.276013e-05 -2.870674e-04  5.122258e-04
</code>```

Title: Optimizing Apply() In R

Body:
The goal of the below code is to perform recursive and iterative analysis on a data set that has 400 columns and 6000 rows. It takes, two columns at a time and performs analysis on it, before moving to all the possible combinations.

Small sub set of large data set being used:

  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.71397
-0.710585   -0.714491   -0.710223   -0.713885
-0.710414   -0.714092   -0.710166   -0.71434
-0.711255   -0.714116   -0.70945    -0.714173
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644

Code using apply():

# Function
analysisFunc <- function () {

    # Fetch next data to be compared
    nextColumn <<- currentColumn + 1

    while (nextColumn <= ncol(Data)){

        # Fetch the two columns on which to perform analysis
        c1 <- Data[, currentColumn]
        c2 <- Data[, nextColumn]

        # Create linear model
        linearModel <- lm(c1 ~ c2)

        # Capture model data from summary
        modelData <- summary(linearModel)

        # Residuals
        residualData <- t(t(modelData$residuals))

        # Keep on appending data
        linearData <<- cbind(linearData, residualData)

        # Fetch next column
        nextColumn <<- nextColumn + 1

    }

    # Increment the counter
    currentColumn <<- currentColumn + 1

}

# Apply on function
apply(Data, 2, function(x) analysisFunc ())

I thought instead of using loops, apply() will help me optimize the code. However, it seems to have no major effect. Run time is more than two hours.

Does anyone think, I am going wrong on how apply() has been used? Is having while() within apply() call not a good idea? Any other way I can improve this code?

This is first time I am working with functional programming. Please let me know your suggestion, thanks.

Body:
Consider an expand.grid of column names and then using mapply the multiple input version of apply family where you pass two+ vectors/lists and run a function across each input elementwise. With this approach you avoid expanding vectors within looping and running an inner while loop:

Data

Data <- read.table(text="  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.71397
-0.710585   -0.714491   -0.710223   -0.713885
-0.710414   -0.714092   -0.710166   -0.71434
-0.711255   -0.714116   -0.70945    -0.714173
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644", header=TRUE)

Process

# Data frame of all combinations excluding same columns
modelcols <- subset(expand.grid(c1=names(Data), c2=names(Data),
                    stringsAsFactors = FALSE), c1!=c2)

# Function
analysisFunc <- function(x,y) {
      # Fetch the two columns on which to perform analysis
      c1 <- Data[[x]]
      c2 <- Data[[y]]

      # Create linear model
      linearModel <- lm(c1 ~ c2)

      # Capture model data from summary
      modelData <- summary(linearModel)

      # Residuals
      residualData <- modelData$residuals
}

# Apply function to return matrix of residuals
linearData <- mapply(analysisFunc, modelcols$c1, modelcols$c2)
# re-naming matrix columns
colnames(linearData) <- paste(modelcols$c1, modelcols$c2, sep="_")

Output

    data2_data1   data3_data1   data4_data1   data1_data2   data3_data2   data4_data2
1  1.440828e-04  8.629813e-05  1.514109e-04  5.583917e-04 -0.0001205821  2.866488e-04
2 -6.949384e-04 -2.508770e-04 -2.487813e-04 -1.005367e-04 -0.0001263202 -2.145225e-04
3  2.132192e-04 -4.609125e-04  4.551430e-04 -8.715424e-05 -0.0004593840  4.133856e-04
4  3.692403e-04  2.182627e-04 -1.116648e-04  3.835538e-04  0.0000408864 -4.244855e-05
5 -2.025772e-04 -4.032600e-04  5.442655e-05 -8.423568e-05 -0.0003484501  4.986815e-05
6  2.336373e-04 -2.838073e-04 -4.425935e-04  1.967203e-04 -0.0003805576 -4.109706e-04
7  2.661145e-05  1.250425e-04 -6.893342e-05 -6.508936e-04  0.0003408023 -2.436194e-04
8  1.456357e-04  3.991303e-04 -2.496687e-05 -3.501856e-04  0.0004980726 -1.304535e-04
9 -2.349110e-04  5.701233e-04  2.359596e-04  1.343401e-04  0.0005555326  2.921120e-04
    data1_data3   data2_data3   data4_data3   data1_data4   data2_data4   data3_data4
1  5.121547e-04  4.313395e-05  2.829814e-04  4.232081e-04  1.795365e-05 -9.584175e-05
2 -1.649379e-06 -6.684696e-04 -2.349827e-04  1.975728e-04 -7.112598e-04 -3.014160e-04
3 -2.942277e-04  3.141257e-04  4.029018e-04 -3.420290e-04  2.382149e-04 -3.760631e-04
4  3.371847e-04  2.859362e-04 -3.420612e-05  3.168009e-04  3.048006e-04  1.062117e-04
5 -1.651011e-04 -1.308671e-04  3.332034e-05 -5.127719e-05 -1.969902e-04 -3.890484e-04
6  2.550032e-05  2.586674e-04 -4.196917e-04  3.235528e-04  2.115955e-04 -3.627735e-04
7 -5.692790e-04  1.157675e-04 -2.277195e-04 -5.922595e-04  1.840773e-04  3.645036e-04
8 -2.258187e-04  1.445371e-04 -1.077903e-04 -3.583290e-04  2.386756e-04  5.422018e-04
9  3.812360e-04 -3.628313e-04  3.051868e-04  8.276013e-05 -2.870674e-04  5.122258e-04


问:
VueJS dynamic class
Reading the documentation I don't understand how I can change a class.

My component data looks like this:

```<code>props: [
  'm_c_id',
  'recipient_id',
  'sender_id',
  'userId'
],
</code>```

Now if sender_id == userId I want to show this in my template:

```<code><div class="msg-from-me">
   <p>Hello</p>
</div>
</code>```

or if recipient_id == userId I want to show this:

```<code><div class="msg-from-them">
   <p>Hello</p>
</div>
</code>```

答:
You can also use the ternary operator to toggle classes:

```<code><div v-bind:class="[sender_id === userId ? msg-from-me : msg-from-them]">
</code>```

This way, if the only two options are sender_id or recipient_id, the proper class will toggle.

ContentLicense: CC BY-SA 4.0

Title: VueJS dynamic class

Body:
Reading the documentation I don't understand how I can change a class.

My component data looks like this:

props: [
  'm_c_id',
  'recipient_id',
  'sender_id',
  'userId'
],

Now if sender_id == userId I want to show this in my template:

Hello

or if recipient_id == userId I want to show this:

Hello

Body:
You can also use the ternary operator to toggle classes:

<div v-bind:class="[sender_id === userId ? msg-from-me : msg-from-them]">

This way, if the only two options are sender_id or recipient_id, the proper class will toggle.


问:
merge two nested org.json.JSONObject
I have two JSON object from org.json:   the first one is

```<code>json1 = {a: {b : {c: val1} } }
</code>```

and the second is

```<code>json2= {a {b: {c2: val2 } } }
</code>```

is there any way to merge this two object to have one object like this:

```<code>result = {a: { b: {c: val1, c2: val2 } } }
</code>```

I don't have any idea about the keys of the two objects, so i need to loop dynamically over these objects and do the merge. Is there any built in method to do this trick. Thanks.

答:
```<code>static JSONObject merge(JSONObject obj1, JSONObject obj2) {
    obj2.forEach((k2, v2) -> obj1.merge(k2, v2, (v1, _v2) ->
            v1 instanceof JSONObject && _v2 instanceof JSONObject
                    ? merge((JSONObject)v1, (JSONObject)_v2) : "conflict!!"));
    return obj1;
}
</code>```

Title: merge two nested org.json.JSONObject

Body:
I have two JSON object from org.json:   the first one is

json1 = {a: {b : {c: val1} } }

and the second is

json2= {a {b: {c2: val2 } } }

is there any way to merge this two object to have one object like this:

result = {a: { b: {c: val1, c2: val2 } } }

I don't have any idea about the keys of the two objects, so i need to loop dynamically over these objects and do the merge. Is there any built in method to do this trick. Thanks.


问:
Extract values from a plot by mouse in bokeh
I have a function y=f(x,a,b), where x,y are the independent and dependent variables and a,b are parameters.

I want to generate a two-panel figure [A,B], where A is the a-versus-b parameter space and B is the y-versus-x function line. I want to be able to use the mouse (say, by hovering over) in panel A to select a pair of (a,b) values and then update the y--x line in the panel B correspondingly.

What widget/method I need to achieve this? I did some research on bokeh hover tool but it generates a tooltip instead of a panel plot, plus I don't know how to extract the values from mouse other than the tooltips syntax in hover tool.

PS: I know this can be achieved by using two sliders (one for a, one for b), but using a panel and mouse gives more flexibility in probing the a-b phase space.

答:
PARTIAL SOLUTION

I found a very similar question with the answer on how to extract the value from the mouse hover tool. Combined with another example about changing a subplot from a callback in a different widget/subplot, here is a working solution with some major disadvantages listing below:

```<code># my test
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, HoverTool
from bokeh.plotting import Figure, output_notebook, show

output_notebook()

x0 = [x*0.005 for x in range(0, 200)]
y0 = x0
sB = ColumnDataSource(data=dict(x=x0, y=y0))
sA = ColumnDataSource(data = dict(x=[0],y=[0]))

callback = CustomJS(args=dict(sA=sA,sB=sB), code="""
    var geometry = cb_data['geometry'];
    var a = geometry.x; // current mouse x position in plot coordinates
    var b = geometry.y; // current mouse y position in plot coordinates
    var as = sA.get('data')['x'];
    var bs = sA.get('data')['y'];
    as[0] = a;
    bs[0] = b;
    sA.trigger('change');

    var data = sB.data;
    x = data['x']
    y = data['y']
    for (i = 0; i < x.length; i++) {
        y[i] = Math.pow(x[i], a+b) // have to convert python function to js here!!!
    }
    sB.trigger('change');
""")

hover_tool = HoverTool(callback=callback)
A = Figure(x_range=(0,1), y_range=(0,1), tools= [hover_tool,
                        "crosshair,box_zoom,wheel_zoom,pan,reset"])
A.circle(x='x',y='y',source=sA)
B = Figure(x_range=(0,1), y_range=(0,1), tools= ["crosshair,box_zoom,wheel_zoom,pan,reset"])
B.line(x='x',y='y',source=sB)
layout = column(A,B)
show(layout)
</code>```

One MAJOR DRAWBACK of this solution is that it utilizes the javascript which I'm totally unfamiliar with and that I have to convert the function f(x,a,b) from python to javascript. I'd appreciate any better solution that can keep the original python function f or other workarounds?

Body:
PARTIAL SOLUTION

I found a very similar question with the answer on how to extract the value from the mouse hover tool. Combined with another example about changing a subplot from a callback in a different widget/subplot, here is a working solution with some major disadvantages listing below:

# my test
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, HoverTool
from bokeh.plotting import Figure, output_notebook, show

output_notebook()

x0 = [x*0.005 for x in range(0, 200)]
y0 = x0
sB = ColumnDataSource(data=dict(x=x0, y=y0))
sA = ColumnDataSource(data = dict(x=[0],y=[0]))

callback = CustomJS(args=dict(sA=sA,sB=sB), code="""
    var geometry = cb_data['geometry'];
    var a = geometry.x; // current mouse x position in plot coordinates
    var b = geometry.y; // current mouse y position in plot coordinates
    var as = sA.get('data')['x'];
    var bs = sA.get('data')['y'];
    as[0] = a;
    bs[0] = b;
    sA.trigger('change');

    var data = sB.data;
    x = data['x']
    y = data['y']
    for (i = 0; i < x.length; i++) {
        y[i] = Math.pow(x[i], a+b) // have to convert python function to js here!!!
    }
    sB.trigger('change');
""")

hover_tool = HoverTool(callback=callback)
A = Figure(x_range=(0,1), y_range=(0,1), tools= [hover_tool,
                        "crosshair,box_zoom,wheel_zoom,pan,reset"])
A.circle(x='x',y='y',source=sA)
B = Figure(x_range=(0,1), y_range=(0,1), tools= ["crosshair,box_zoom,wheel_zoom,pan,reset"])
B.line(x='x',y='y',source=sB)
layout = column(A,B)
show(layout)

One MAJOR DRAWBACK of this solution is that it utilizes the javascript which I'm totally unfamiliar with and that I have to convert the function f(x,a,b) from python to javascript. I'd appreciate any better solution that can keep the original python function f or other workarounds?


问:
how to get image from MySQL and display using angular 2
I am trying to build an ionic 2 mobile application. Right now, I had no clues on how to display the blob type image from MySQL using angular 2 method.

Moreover, previously before I trying to get the images (getting normal string data), the code works fine. After I add the sql statement store.storePhoto, I am unable to get my other data.

I add the images for the output of the PHP File before and after I add the store.storePhoto.

php

```<code><?php
header('Access-Control-Allow-Origin: *');

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'storeListing';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            =>
PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);
$data = array();

// Attempt to query database table and retrieve data
try {
  $listing    = $pdo->query('SELECT
                             joblistings.ListingTitle,
                             joblistings.ListingDescription,
                             store.storeAddress,
                             store.storeName,
                             store.storePhoto
                             FROM store INNER JOIN joblistings
                             ON store.storeID=joblistings.storeID
                             ');

  while($listing_row  = $listing->fetch(PDO::FETCH_OBJ))
  {
     // Assign each row of data to associative array
     $listing_data[] = $listing_row;
     $newArrData = [];

     foreach ($listing_data as $key =>$value){
         $newArrData["storePhoto"] = base64_encode($value->storePhoto);
     }
  }

  $array = array($newArrData);
  echo json_encode($array);
  echo json_encode($listing_data);
}
catch(PDOException $e)
{
  echo $e->getMessage();
}

?>
</code>```

TypeScript for getting the data

```<code>load()
  {
   this.http.get('http://localhost/php-mysql/retrieve-data.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.listings = data;
  });
  }
</code>```

HTML for display

```<code><ion-row center>
  <ion-col col-12 text-center>
  <h4>
    <ion-input formControlName="ListingTitle" [(ngModel)]="ListingTitle" readonly="true"></ion-input>
  </h4>
  </ion-col>
 </ion-row>

 <ion-row>
 <ion-card>
  <img src="xxx">// Not sure how to get the image
 </ion-card>

 <ion-row>
  <ion-col col-12>
   <h6>Job Description</h6>
   <ion-input formControlName="ListingDescription" [(ngModel)]="ListingDescription" readonly="true"></ion-input>
   </ion-col>
 </ion-row>

 <div text-center>
 <button fab-center ion-button color="primary">
  Submit
 </button>
</div>
</code>```

After add in storePhoto

Before add in storePhoto

答:
You return the picture as base64, so you should be able to display it like that:</p>

```<code><img src="data:image/jpeg;base64,{{listings.storePhoto}}"/>
</code>```

Body:
I am trying to build an ionic 2 mobile application. Right now, I had no clues on how to display the blob type image from MySQL using angular 2 method.

Moreover, previously before I trying to get the images (getting normal string data), the code works fine. After I add the sql statement store.storePhoto, I am unable to get my other data.

I add the images for the output of the PHP File before and after I add the store.storePhoto.

php

<?php
header('Access-Control-Allow-Origin: *');

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'storeListing';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            =>
PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);
$data = array();

// Attempt to query database table and retrieve data
try {
  $listing    = $pdo->query('SELECT
                             joblistings.ListingTitle,
                             joblistings.ListingDescription,
                             store.storeAddress,
                             store.storeName,
                             store.storePhoto
                             FROM store INNER JOIN joblistings
                             ON store.storeID=joblistings.storeID
                             ');

  while($listing_row  = $listing->fetch(PDO::FETCH_OBJ))
  {
     // Assign each row of data to associative array
     $listing_data[] = $listing_row;
     $newArrData = [];

     foreach ($listing_data as $key =>$value){
         $newArrData["storePhoto"] = base64_encode($value->storePhoto);
     }
  }

  $array = array($newArrData);
  echo json_encode($array);
  echo json_encode($listing_data);
}
catch(PDOException $e)
{
  echo $e->getMessage();
}

?>

TypeScript for getting the data

load()
  {
   this.http.get('http://localhost/php-mysql/retrieve-data.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.listings = data;
  });
  }

HTML for display

<ion-row center>
  <ion-col col-12 text-center>

    <ion-input formControlName="ListingTitle" [(ngModel)]="ListingTitle" readonly="true"></ion-input>

  </ion-col>
 </ion-row>

 <ion-row>
 <ion-card>
  // Not sure how to get the image
 </ion-card>

 <ion-row>
  <ion-col col-12>

Job Description

   <ion-input formControlName="ListingDescription" [(ngModel)]="ListingDescription" readonly="true"></ion-input>
   </ion-col>
 </ion-row>

 <button fab-center ion-button color="primary">
  Submit
 </button>

After add in storePhoto

Before add in storePhoto

Body:
You return the picture as base64, so you should be able to display it like that:

<img src="data:image/jpeg;base64,{{listings.storePhoto}}"/>


问:
Why would an overflow on an object of built-in type cause an exception/undefined behavior?
From what I can tell, "overflow" works very much like "narrowing" (if not outright the same exact thing).

For example, an unsigned char object with the value 255; its bit pattern would be all 1s: 1111 1111

So, by adding 1 to the object: char_object++;

Widening would occur on some temporary object, having 1 added to it, so the bit pattern (on the temporary) should be 256: 0000 0001 0000 0000

The temporary is then copy-assigned into the original object, causing narrowing (losing the left-most byte), which leaves it with the value of 0.

If this works as narrowing does, I'm curious why the standard suggests that on some machines, overflow causes exceptions? Some books even suggest undefined behavior as the result. Would this not imply that narrowing would do the same thing on said machines? If they are not the same thing, then how are they different?

(edit:) Perhaps by comparing the bit-pattern of an unsigned 8-bit object against that of a signed 8-bit object, this can be made clearer? Seems that in 2's complement, the bit pattern doesn't change, but the representation does. Anyway, this still doesn't truly answer the question, "What's the difference between narrowing, and overflow?" Because they still seem to be the same thing:

```<code>#include <bitset>
#include <cstdint>
#include <iostream>

void show_bits(int8_t&);

int main()
{
    for (int8_t number{ 1 }; number; ++number)
    {
        show_bits(number);
    }
    return 0;
}

void show_bits(int8_t& number)
{
    std::cout << static_cast<int16_t>(number) << ' ';
    std::cout << '(' << static_cast<uint16_t>(static_cast<uint8_t>(number)) << ')' << '\t';
    std::bitset<sizeof(int8_t) * 8> bits_of(number);
    std::cout << bits_of << '\n';
}
</code>```

答:
There is no intuition to find here, only specification. https://stackoverflow.com/a/83763/451600. The spec may have historical reasons for its decisions.

For instance, the fact that ++unsigned_max is well defined and ++signed_max  is not, is likely related to the fact that not all signed numbers are represented the same way. 2's complement isn't mandated.

The compiler is a black box to a c++ programmer/program, as long as it follows spec.

Body:
From what I can tell, "overflow" works very much like "narrowing" (if not outright the same exact thing).

For example, an unsigned char object with the value 255; its bit pattern would be all 1s: 1111 1111

So, by adding 1 to the object: char_object++;

Widening would occur on some temporary object, having 1 added to it, so the bit pattern (on the temporary) should be 256: 0000 0001 0000 0000

The temporary is then copy-assigned into the original object, causing narrowing (losing the left-most byte), which leaves it with the value of 0.

If this works as narrowing does, I'm curious why the standard suggests that on some machines, overflow causes exceptions? Some books even suggest undefined behavior as the result. Would this not imply that narrowing would do the same thing on said machines? If they are not the same thing, then how are they different?

(edit:) Perhaps by comparing the bit-pattern of an unsigned 8-bit object against that of a signed 8-bit object, this can be made clearer? Seems that in 2's complement, the bit pattern doesn't change, but the representation does. Anyway, this still doesn't truly answer the question, "What's the difference between narrowing, and overflow?" Because they still seem to be the same thing:

#include <bitset>
#include <cstdint>
#include <iostream>

void show_bits(int8_t&);

int main()
{
    for (int8_t number{ 1 }; number; ++number)
    {
        show_bits(number);
    }
    return 0;
}

void show_bits(int8_t& number)
{
    std::cout << static_cast<int16_t>(number) << ' ';
    std::cout << '(' << static_cast<uint16_t>(static_cast<uint8_t>(number)) << ')' << '\t';
    std::bitset<sizeof(int8_t) * 8> bits_of(number);
    std::cout << bits_of << '\n';
}


问:
Redux - Updating deeply nested store props using spread operator
I am building a relatively large web app using react+redux and dealing with my store is getting really confusing.

I came up with a problem in updating nested properties in store and found Immutable Update Patterns section of redux docs which indicates I should do something like this:

```<code>function updateVeryNestedField(state, action) {
    return {
        ....state,
        first : {
            ...state.first,
            second : {
                ...state.first.second,
                [action.someId] : {
                    ...state.first.second[action.someId],
                    fourth : action.someValue
                }
            }
        }
    }
}
</code>```

And I've done so, and as a result some parts of my reducers are looking like this:

```<code>.
.
.
case "CHANGE_RANGED_INPUT": {
        return {
          ...state,
          searchPanel: {
            ...state.searchPanel,
            [action.payload.category]: {
              ...state.searchPanel[action.payload.category],
              rangedInputs: {
                ...state.searchPanel[action.payload.category].rangedInputs,
                [action.payload.type]: {
                  ...state.searchPanel[action.payload.category].rangedInputs[action.payload.type],
                  [action.payload.key]: {
                    ...state.searchPanel[action.payload.category].rangedInputs[action.payload.type][action.payload.key],
                    value: action.payload.value
                  }
                }
              },
            }
          },
        }
      }
.
.
.
</code>```

I guess you agree that my code is getting more confusing than it should be. My question is not about the performance of the way recommended by redux docs (eventhough it feels like a lot of work for an action which in my case is dispatched almost every second) and I assume it is the best way.

My question is about readability of my code. Is there an approach which can make my reducer cleaner?

Actually I am using react-redux-form for some of my giant forms, not because I need all the features this library is providing, but to use just one feature of it. this library lets me create a huge form model with lots of nested stuff and all I have to do is add its model route to the input to get its predefined onChange events working and the related values updating.

Is this library doing so with spread operator under its hood?

Is there any other way like adding some index to some input and be able to update the related value in the store with that index when input value is changed?

答:
I actually found dozens of utilities for this in redux docs!
Immutable Update Utilities

and I think dot-prop-immutable is pretty simple and straight forward.

Body:
I am building a relatively large web app using react+redux and dealing with my store is getting really confusing.

I came up with a problem in updating nested properties in store and found Immutable Update Patterns section of redux docs which indicates I should do something like this:

function updateVeryNestedField(state, action) {
    return {
        ....state,
        first : {
            ...state.first,
            second : {
                ...state.first.second,
                [action.someId] : {
                    ...state.first.second[action.someId],
                    fourth : action.someValue
                }
            }
        }
    }
}

And I've done so, and as a result some parts of my reducers are looking like this:

.
.
.
case "CHANGE_RANGED_INPUT": {
        return {
          ...state,
          searchPanel: {
            ...state.searchPanel,
            [action.payload.category]: {
              ...state.searchPanel[action.payload.category],
              rangedInputs: {
                ...state.searchPanel[action.payload.category].rangedInputs,
                [action.payload.type]: {
                  ...state.searchPanel[action.payload.category].rangedInputs[action.payload.type],
                  [action.payload.key]: {
                    ...state.searchPanel[action.payload.category].rangedInputs[action.payload.type][action.payload.key],
                    value: action.payload.value
                  }
                }
              },
            }
          },
        }
      }
.
.
.

I guess you agree that my code is getting more confusing than it should be. My question is not about the performance of the way recommended by redux docs (eventhough it feels like a lot of work for an action which in my case is dispatched almost every second) and I assume it is the best way.

My question is about readability of my code. Is there an approach which can make my reducer cleaner?

Actually I am using react-redux-form for some of my giant forms, not because I need all the features this library is providing, but to use just one feature of it. this library lets me create a huge form model with lots of nested stuff and all I have to do is add its model route to the input to get its predefined onChange events working and the related values updating.

Is this library doing so with spread operator under its hood?

Is there any other way like adding some index to some input and be able to update the related value in the store with that index when input value is changed?