问:
Ways to invoke python and Spyder on OSX
I recently bought a MacBook and install Python on it via Anaconda. Here's the version information:

```<code>Python 2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Nov 11 2013, 10:49:09)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
</code>```

I'd like to be able do all of the following:

Launch Spyder without having to go through the Launcher application (say, by typing things into Spotlight and Quicksilver)

Run Python code from the Finder, presumably by double-clicking on my .py file or by selecting and and pressing Cmd-O

Run Python code by typing a Python script's name into Quicksilver (as if it was a regular program)

Here's what I've tried:

(nothing; no ideas here)

I've associated .py files with /Users/kuzzooroo/anaconda/python.app/Contents/MacOS/python and made them executable (chmod u+x). When I try to run the application never launches and I don't get an error message (don't know where to look)

Made the files executable and tried to run them from Spotlight. Same result as #2.

Here's what I can do:

Run my code from a Terminal window, if I have the right shebang on top and have made the file executable

Generate an application using py2app. Unfortunately, this method suffers the following drawbacks:

I frequently modify my scripts and would prefer not to have to run py2app every time I do

Even for a trivial script the resulting app is 7 MB

To run the application in some contexts I have to dig around in the bundle to find the actual "Unix Executable File" and run that instead

Once I have this working, I'm interested in doing the following:

A. Controlling which scripts create a console window when they run and which do not

B. Controlling whether the resulting console window disappears when the script completes or waits around for the user (me) to close it

However, I suspect it may be easy to figure out how to do these (or whether it's possible) once I've figured out how I'm going to invoke my scripts in the first place.

答:
The accepted answer has two drawbacks: a console windows appears when starting spyder and one cannot keep a spyder icon in the dock. These drawbakcs can be avoided by creating a proper Mac application bundle for spyder, which is surprisingly easy to do.

To convert /usr/local/bin/spyder3 (the result of which spyder3 on my machine) into a traditional Mac application:

Create a Mac application bundle (basically a folder structure containing an executable file):

```<code>cd /Applications
mkdir -p spyder.app/Contents/MacOS
echo -e '#!/bin/bash'"\n /usr/local/bin/spyder3 $@" >> spyder.app/Contents/MacOS/spyder
chmod +x spyder.app/Contents/MacOS/spyder
</code>```

Create a plain text file called Info.plist in the Contents folder (i.e. at spyder.app/Contents/Info.plist) with the following content:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>CFBundleExecutable</key>
<string>spyder</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>3.1.4</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>3.1.4</string>
</dict>
</plist>
</code>```

(Optional) Create an app icon like in steps 4 and 5 of the accepted answer.

Voilà, spyder has become suddenly much more Mac-friendly!

EDIT:
One can further improve the mac-friendliness of spyder by:

Preventing the generic python rocket icon to appear besides the spyder icon

For this, uncheck in spyder the option Tools -> Preferences -> iPython console -> Graphics -> Activate (matplotlib)

Making spyder the default editor for .py files.

This one is more tricky. First make sure that the content of spyder.app/Contents/MacOS/spyder reads

```<code>#!/bin/bash
/usr/local/bin/spyder $@
</code>```

Create then an automator script containg a single action "Execute a shell script". Paste the following (bash) script in it:

```<code>for f in "$@"
do
    open /Applications/spyder.app --args $f
done
if [ -z "$f" ]; then
    open /Applications/spyder.app --args ~
fi
</code>```

Choose "As argument" for the input data, as shown in the screenshot below (the "--args ~" is missing in the screenshot but it is needed to avoid an error when launching spyder without any file).

Save this script as an application called "SpyderOpener" for instance.

Make SpyderOpener the default application for opening .py files (by using the Finder "Get Info" dialog on a .py file)

Title: Ways to invoke python and Spyder on OSX

Body:
I recently bought a MacBook and install Python on it via Anaconda. Here's the version information:

Python 2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Nov 11 2013, 10:49:09)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin

I'd like to be able do all of the following:

Launch Spyder without having to go through the Launcher application (say, by typing things into Spotlight and Quicksilver)

Run Python code from the Finder, presumably by double-clicking on my .py file or by selecting and and pressing Cmd-O

Run Python code by typing a Python script's name into Quicksilver (as if it was a regular program)

Here's what I've tried:

(nothing; no ideas here)

I've associated .py files with /Users/kuzzooroo/anaconda/python.app/Contents/MacOS/python and made them executable (chmod u+x). When I try to run the application never launches and I don't get an error message (don't know where to look)

Made the files executable and tried to run them from Spotlight. Same result as #2.

Here's what I can do:

Run my code from a Terminal window, if I have the right shebang on top and have made the file executable

Generate an application using py2app. Unfortunately, this method suffers the following drawbacks:

I frequently modify my scripts and would prefer not to have to run py2app every time I do

Even for a trivial script the resulting app is 7 MB

To run the application in some contexts I have to dig around in the bundle to find the actual "Unix Executable File" and run that instead

Once I have this working, I'm interested in doing the following:

A. Controlling which scripts create a console window when they run and which do not

B. Controlling whether the resulting console window disappears when the script completes or waits around for the user (me) to close it

However, I suspect it may be easy to figure out how to do these (or whether it's possible) once I've figured out how I'm going to invoke my scripts in the first place.

Body:
The accepted answer has two drawbacks: a console windows appears when starting spyder and one cannot keep a spyder icon in the dock. These drawbakcs can be avoided by creating a proper Mac application bundle for spyder, which is surprisingly easy to do.

To convert /usr/local/bin/spyder3 (the result of which spyder3 on my machine) into a traditional Mac application:

Create a Mac application bundle (basically a folder structure containing an executable file):

cd /Applications
mkdir -p spyder.app/Contents/MacOS
echo -e '#!/bin/bash'"\n /usr/local/bin/spyder3 $@" >> spyder.app/Contents/MacOS/spyder
chmod +x spyder.app/Contents/MacOS/spyder

Create a plain text file called Info.plist in the Contents folder (i.e. at spyder.app/Contents/Info.plist) with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>CFBundleExecutable</key>
<string>spyder</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>3.1.4</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>3.1.4</string>
</dict>
</plist>

(Optional) Create an app icon like in steps 4 and 5 of the accepted answer.

Voilà, spyder has become suddenly much more Mac-friendly!

EDIT:
One can further improve the mac-friendliness of spyder by:

Preventing the generic python rocket icon to appear besides the spyder icon

For this, uncheck in spyder the option Tools -> Preferences -> iPython console -> Graphics -> Activate (matplotlib)

Making spyder the default editor for .py files.

This one is more tricky. First make sure that the content of spyder.app/Contents/MacOS/spyder reads

#!/bin/bash
/usr/local/bin/spyder $@

Create then an automator script containg a single action "Execute a shell script". Paste the following (bash) script in it:

for f in "$@"
do
    open /Applications/spyder.app --args $f
done
if [ -z "$f" ]; then
    open /Applications/spyder.app --args ~
fi

Choose "As argument" for the input data, as shown in the screenshot below (the "--args ~" is missing in the screenshot but it is needed to avoid an error when launching spyder without any file).

Save this script as an application called "SpyderOpener" for instance.

Make SpyderOpener the default application for opening .py files (by using the Finder "Get Info" dialog on a .py file)


来源: stackexchange

问:
How to use list constructors (./2) in SWI-Prolog
I am trying to use list constructor in SWI-Prolog, but am getting 'dict' expected error.

For example,

```<code>.(a, []) == [a].

ERROR: Type error: `dict' expected, found `a' (an atom)
ERROR: In:
ERROR:   [11] throw(error(type_error(dict,a),_14808))
ERROR:   [10] '$type_error'(dict,a) at /Applications/SWI-Prolog.app/Contents/swipl/boot/init.pl:3369
ERROR:    [9] '$dicts':'.'(a,[],_14874) at /Applications/SWI-Prolog.app/Contents/swipl/boot/dicts.pl:46
ERROR:    [8] '<meta-call>'(user:(...,...)) <foreign>
ERROR:    [7] <user>
Exception: (9) '.'(a, [], _14200) ?
</code>```

Could anyone help me configure this functionality?

答:
SWI-Prolog 7.x uses a different list constructor, '[|]'/2, instead of the traditional ./2 Prolog constructor:

```<code>?- '[|]'(1,[]) == [1].
true.
</code>```

The change was motivated to free ./2 for other uses, notably in dict terms, as hinted in the error message you got for your query.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use list constructor in SWI-Prolog, but am getting 'dict' expected error.

For example,

.(a, []) == [a].

ERROR: Type error: `dict' expected, found `a' (an atom)
ERROR: In:
ERROR:   [11] throw(error(type_error(dict,a),_14808))
ERROR:   [10] '$type_error'(dict,a) at /Applications/SWI-Prolog.app/Contents/swipl/boot/init.pl:3369
ERROR:    [9] '$dicts':'.'(a,[],_14874) at /Applications/SWI-Prolog.app/Contents/swipl/boot/dicts.pl:46
ERROR:    [8] '<meta-call>'(user:(...,...)) <foreign>
ERROR:    [7] <user>
Exception: (9) '.'(a, [], _14200) ?

Could anyone help me configure this functionality?

Body:
SWI-Prolog 7.x uses a different list constructor, '[|]'/2, instead of the traditional ./2 Prolog constructor:

?- '[|]'(1,[]) == [1].
true.

The change was motivated to free ./2 for other uses, notably in dict terms, as hinted in the error message you got for your query.


问:
Can a rake task be triggered via a rails interface?
Or am I thinking about this wrong?  Basically, I want to be able to upload a zip file to a model, and after uploading I want to run a bunch of processes on it.  It would be nice to be able to do this from the back end/console, as well as have a way of triggering the actions via the rails front-end interface.

The idea here:

Gallery has collection.zip

Gallery has many children :item

collection.zip has information for each Item

I want to trigger a batch gallery.items.build process that will extract the information from the zip and use it to create the new items.  I thought about using a Paperclip::Processor for this task, but I have yet to find a lot of truly useful or comprehensive documentation on how that would work, and experimentation has only led to frustration and confusion.  I saw some people use rake tasks for this sort of thing, but I really don't want to have to use the console to do perform the task, and would really just like to have a button that says "Generate Gallery" that will run all the necessary tasks.

So, is there a way of doing this?  Would this be considered bad practice?  If so, is there another way that I should be approaching this problem?

答:
If you do want to know how to run a rake task from rails, Ryan Bates has an excellent free screencast that show you how.

http://railscasts.com/episodes/127-rake-in-background

ContentLicense: CC BY-SA 2.5


问:
find size of union of two sets?
Is there any way to find size of union of two sets.
I know can do this

```<code>vector < int > s3( s1.size() , s2.size() );
auto it=set_union( s1.begin() , s1.end() , s2.begin() ,s2.end(), s3.begin());
int size = it - s3.begin();
</code>```

print size

example

```<code>s1 = {2 4 5 6}   size 4

s2 = {1 4 5 9 10}  size 5

s3 = {1 2 4 5 6 9 10}  size 7

complexity of set_union is 2*(s1 size + s2 size)-1
</code>```

Is there any other method to get size of union of two sets faster method, I just need the size do not  want the values of new union set formed.
If you know a faster method please suggest.

答:
You can just put a counting iterator in last argument to set_union. E.g.

```<code>int count = 0;
it=set_union( s1.begin() , s1.end() , s2.begin() ,s2.end(), boost::make_function_output_iterator([&count](int){ ++count; }));
</code>```

Or a non-boost equivalent of that output iterator

```<code>struct counter {
    using difference_type = void;
    using value_type = void;
    using pointer = void;
    using reference = void;
    using iterator_category = std::output_iterator_tag;
    int count = 0;
    void operator&(int) { ++count }
    counter& operator++ { return *this; }
};
</code>```

Title: find size of union of two sets?

Body:
Is there any way to find size of union of two sets.
I know can do this

vector < int > s3( s1.size() , s2.size() );
auto it=set_union( s1.begin() , s1.end() , s2.begin() ,s2.end(), s3.begin());
int size = it - s3.begin();

print size

example

s1 = {2 4 5 6}   size 4

s2 = {1 4 5 9 10}  size 5

s3 = {1 2 4 5 6 9 10}  size 7

complexity of set_union is 2*(s1 size + s2 size)-1

Is there any other method to get size of union of two sets faster method, I just need the size do not  want the values of new union set formed.
If you know a faster method please suggest.

Body:
You can just put a counting iterator in last argument to set_union. E.g.

int count = 0;
it=set_union( s1.begin() , s1.end() , s2.begin() ,s2.end(), boost::make_function_output_iterator([&count](int){ ++count; }));

Or a non-boost equivalent of that output iterator

struct counter {
    using difference_type = void;
    using value_type = void;
    using pointer = void;
    using reference = void;
    using iterator_category = std::output_iterator_tag;
    int count = 0;
    void operator&(int) { ++count }
    counter& operator++ { return *this; }
};


问:
bootstrap carousel image height
i'm having some problems with the images in bootstrap v4 image carousel. If i scale down the browser width the height of image stays the same but the width of image getting smaller so the image gets very stretched out on the height.

I have been looking at similar threads here on stackoverflow and tried everything i found in the comments but it still does not work. So i decided to make a new thread about this.

Here is a codepen link https://codepen.io/anon/pen/owNyyx but i paste the code here too if you do not wish to visit codepen :)

So here is the code i have

```<code><div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="images/image1.png" alt="First slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>Random Title for image1</h3>
        <p>Random description1</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="images/image2.png" alt="Second slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>Random title for image2</h3>
        <p>Random description2</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="images/image3.png" alt="Third slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>Random title for image3</h3>
        <p>Random description3</p>
      </div>
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</code>```

答:
It's because the img parent, .carousel-item is display: flex and the img is a flex-child, so it's "stretching" via the default align-items: stretch on the parent.

A number of ways you can fix this. Easiest is probably to give align-items a value other than stretch.

Or if you don't want to apply custom CSS and keep your changes in the markup, wrap each img in a block element like div or figure or whatever works for your site.

.carousel-item {
  align-items: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="http://lorempixel.com/1900/500" alt="First slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>Cheap prizes for hairstyling</h3>
        <p>Good prizes to style your hair</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="http://lorempixel.com/1900/500/cats/2" alt="Second slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>3 Years of experience as Hairstylist</h3>
        <p>Awesome results !</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="http://lorempixel.com/1900/500/cats/3" alt="Third slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>Some random caption text</h3>
        <p>Some random description</p>
      </div>
    </div>
  </div>

    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>

    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>

</div></code>```

Title: bootstrap carousel image height

Body:
i'm having some problems with the images in bootstrap v4 image carousel. If i scale down the browser width the height of image stays the same but the width of image getting smaller so the image gets very stretched out on the height.

I have been looking at similar threads here on stackoverflow and tried everything i found in the comments but it still does not work. So i decided to make a new thread about this.

Here is a codepen link https://codepen.io/anon/pen/owNyyx but i paste the code here too if you do not wish to visit codepen :)

So here is the code i have

Random Title for image1

Random description1

Random title for image2

Random description2

Random title for image3

Random description3

    Previous

    Next

Body:
It's because the img parent, .carousel-item is display: flex and the img is a flex-child, so it's "stretching" via the default align-items: stretch on the parent.

A number of ways you can fix this. Easiest is probably to give align-items a value other than stretch.

Or if you don't want to apply custom CSS and keep your changes in the markup, wrap each img in a block element like div or figure or whatever works for your site.

.carousel-item {
  align-items: flex-start;
}

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="http://lorempixel.com/1900/500" alt="First slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>Cheap prizes for hairstyling</h3>
        <p>Good prizes to style your hair</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="http://lorempixel.com/1900/500/cats/2" alt="Second slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>3 Years of experience as Hairstylist</h3>
        <p>Awesome results !</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="http://lorempixel.com/1900/500/cats/3" alt="Third slide">
      <div class="carousel-caption d-none d-md-block">
        <h3>Some random caption text</h3>
        <p>Some random description</p>
      </div>
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

ContentLicense: CC BY-SA 4.0


问:
using php to place image names within a folder to feed HTML img src inside bootstrap carousel
I have a folder containing images that I want to put inside a Bootstrap carousel. Instead of hardcode everything in my HTML, I thought to use PHP to scan the image files and create my carousel list dynamically.

After various attempts, my best achievement was having a carousel listing the names of my images (rather than the image themselves).

My code is below. I have two question about it:

(obviously) Why is it not working?

Is there a better way to separate such a long PHP function from the HTML code (like a call with include but that would work with functions)?

```<code><div class="container-fluid">
  <?php
    $img_folder = './img/img_animazione/';
    function carousel_loop($folder)
    {
      echo '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
      echo '<ol class="carousel-indicators">';
      $i = -1;
      $images = scandir($folder);
      foreach($images as $image) {
        $i++; //$i is the index of the current loop.
        if ($i == 0) {
          echo '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
        } else {
          echo '<li data-target="#myCarousel" data-slide-to="' . $i . '"</li>';
        }
      }
      echo '</ol>';
      echo '<div class="carousel-inner">';
      foreach($images as $image) {
        if ($image === reset($images)) {
          echo '<div class="item active">';
          echo '<img src="' . $image . '" alt="'. $image . '">';
          echo '</div>';
        } else {
          echo '<div class="item">';
          echo '<img src="' . $image . '" alt="'. $image . '">';
          echo '</div>';
        }
      }
      echo '</div>';
      echo '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
      echo '<span class="glyphicon glyphicon-chevron-left"></span>';
      echo '<span class="sr-only">Previous</span>';
      echo '</a>';
      echo '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
      echo '<span class="glyphicon glyphicon-chevron-right"></span>';
      echo '<span class="sr-only">Next</span>';
      echo '</a>';
      echo '</div>';
    }
    carousel_loop($img_folder);
  ?>
</div>
</code>```

答:
That's not the way to use functions. You can't echo like that from inside the function. You have to build up the HTML inside the function and return it. Then either just echo the function or assign what it returns to a variable.

So like this:

```<code><?php
   function carousel_loop($folder)
   {
   html = "";
   html .= '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
   html .= '<ol class="carousel-indicators">';
   $i = -1;
   $images = scandir($folder);
   foreach($images as $image) {
      $i++; //$i is the index of the current loop.
      if ($i == 0) {
        html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
      } else {
         html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '"</li>';
      }
    }
    html .= '</ol>';
    html .= '<div class="carousel-inner">';
    foreach($images as $image) {
      if ($image === reset($images)) {
        html .= '<div class="item active">';
        html .= '<img src="' . $image . '" alt="'. $image . '">';
        html .= '</div>';
      } else {
        html .= '<div class="item">';
        html .= '<img src="' . $image . '" alt="'. $image . '">';
        html .= '</div>';
      }
    }
    html .= '</div>';
    html .= '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
    html .= '<span class="glyphicon glyphicon-chevron-left"></span>';
    html .= '<span class="sr-only">Previous</span>';
    html .= '</a>';
    html .= '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
    html .= '<span class="glyphicon glyphicon-chevron-right"></span>';
    html .= '<span class="sr-only">Next</span>';
    html .= '</a>';
    html .= '</div>';

    return html;
}
?>
<div class="container-fluid">
<?php
$img_folder = './img/img_animazione/';
echo carousel_loop($img_folder);
?>
</div>
</code>```

Body:
I have a folder containing images that I want to put inside a Bootstrap carousel. Instead of hardcode everything in my HTML, I thought to use PHP to scan the image files and create my carousel list dynamically.

After various attempts, my best achievement was having a carousel listing the names of my images (rather than the image themselves).

My code is below. I have two question about it:

(obviously) Why is it not working?

Is there a better way to separate such a long PHP function from the HTML code (like a call with include but that would work with functions)?

  <?php
    $img_folder = './img/img_animazione/';
    function carousel_loop($folder)
    {
      echo '
';
      echo '
';
      $i = -1;
      $images = scandir($folder);
      foreach($images as $image) {
        $i++; //$i is the index of the current loop.
        if ($i == 0) {
          echo '

';
        } else {
          echo '<li data-target="#myCarousel" data-slide-to="' . $i . '"
';
        }
      }
      echo '
';
      echo '
';
      foreach($images as $image) {
        if ($image === reset($images)) {
          echo '
';
          echo '';
          echo '
';
        } else {
          echo '
';
          echo '';
          echo '
';
        }
      }
      echo '
';
      echo '';
      echo '';
      echo 'Previous';
      echo '';
      echo '';
      echo '';
      echo 'Next';
      echo '';
      echo '
';
    }
    carousel_loop($img_folder);
  ?>

Body:
That's not the way to use functions. You can't echo like that from inside the function. You have to build up the HTML inside the function and return it. Then either just echo the function or assign what it returns to a variable.

So like this:

<?php
   function carousel_loop($folder)
   {
   html = "";
   html .= '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
   html .= '<ol class="carousel-indicators">';
   $i = -1;
   $images = scandir($folder);
   foreach($images as $image) {
      $i++; //$i is the index of the current loop.
      if ($i == 0) {
        html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
      } else {
         html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '"</li>';
      }
    }
    html .= '</ol>';
    html .= '<div class="carousel-inner">';
    foreach($images as $image) {
      if ($image === reset($images)) {
        html .= '<div class="item active">';
        html .= '<img src="' . $image . '" alt="'. $image . '">';
        html .= '</div>';
      } else {
        html .= '<div class="item">';
        html .= '<img src="' . $image . '" alt="'. $image . '">';
        html .= '</div>';
      }
    }
    html .= '</div>';
    html .= '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
    html .= '<span class="glyphicon glyphicon-chevron-left"></span>';
    html .= '<span class="sr-only">Previous</span>';
    html .= '</a>';
    html .= '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
    html .= '<span class="glyphicon glyphicon-chevron-right"></span>';
    html .= '<span class="sr-only">Next</span>';
    html .= '</a>';
    html .= '</div>';

    return html;
}
?>
<div class="container-fluid">
<?php
$img_folder = './img/img_animazione/';
echo carousel_loop($img_folder);
?>
</div>


问:
Javascript toggle class on element
Say I have this HTML structure

```<code><div class="sType_click">
    <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
    <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
    <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>
</code>```

How do I use JavaScript to toggle class on sType_click div with the customText span BUT without adding it on other sType_click divs?

For example if I click on one of the customText class I want to toggle class on its parent sType_click div and not adding on any others.

I currently use this

```<code>var sType_click = document.querySelector(".sType_click"),
customText = document.querySelector(".customText"),
if (null !== document.querySelector(".customText")) {
    customText.onclick = function() {
        sType_click.classList.toggle("sOpen");
    };
}
</code>```

But this toggles all sType_click divs on the page
I'm okay with jQuery but i prefer pure javascript,
Thanks in advance.

答:
Pure JS solution:

You should listen for clicks on customText elements and get 2 levels higher using parentNode twice. Also, use querySelectorAll to get all elements (non-live list, so it doesn't update when you toggle class).

var fwcustomText = document.querySelectorAll(".sType_click .customText");

for (var ct of fwcustomText) { // listen to clicks on ".customText" elements
  ct.addEventListener('click', function(event) {
    event.target.parentNode.parentNode.classList.toggle("sType_click"); // toggle class 2 levels higher
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sType_click {
   background-color: red;
}</code>```

      Custom text

      Custom text

      Custom text

```

Title: Javascript toggle class on element

Body:
Say I have this HTML structure

      Custom text

      Custom text

      Custom text

How do I use JavaScript to toggle class on sType_click div with the customText span BUT without adding it on other sType_click divs?

For example if I click on one of the customText class I want to toggle class on its parent sType_click div and not adding on any others.

I currently use this

var sType_click = document.querySelector(".sType_click"),
customText = document.querySelector(".customText"),
if (null !== document.querySelector(".customText")) {
    customText.onclick = function() {
        sType_click.classList.toggle("sOpen");
    };
}

But this toggles all sType_click divs on the page
I'm okay with jQuery but i prefer pure javascript,
Thanks in advance.

Body:
Pure JS solution:

You should listen for clicks on customText elements and get 2 levels higher using parentNode twice. Also, use querySelectorAll to get all elements (non-live list, so it doesn't update when you toggle class).

var fwcustomText = document.querySelectorAll(".sType_click .customText");

for (var ct of fwcustomText) { // listen to clicks on ".customText" elements
  ct.addEventListener('click', function(event) {
    event.target.parentNode.parentNode.classList.toggle("sType_click"); // toggle class 2 levels higher
  })
}

.sType_click {
   background-color: red;
}

<div class="sType_click">
        <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
        <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
        <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>


问:
POST variables not seen in Symfony's 3.2 Controller
Debugger shows, that there is POST data in request, but I cannot get it by $request->get('foo');

And $request->request->all(); gives array [0].

My Ajax POST request (by AngularJS):

```<code>...
    $http.post('http://admin/about-company/setJSONObj',
        {foo: 'bar'}
    );
</code>```

My controller with debugging info in comments (Symfony 3.2.9):

```<code>use Symfony\Component\HttpFoundation\Request;
    ...
    public function updateAction(Request $request)
        {
             $foo = $request->get('foo'); // null
             $requestType = $request->getContentType(); // json
             $content = $request->getContent(); // {"foo":"bar"}
</code>```

I used these approach on Symfony 2.7 project, and it worked fine, but I'm not sure, what's happening in these case?

Also, maybe there is any Symfony framework config variable that tells not to parse POST data, or hides it during caching the request?

答:
It turned out, my mistake was to expect POST variables in $request->request->all(); while posting JSON: see explanation  https://www.toptal.com/....

For creating REST api with Symfony it's normal to use FOSRestBundle: see body listener. So, it solves my problem in elegant way.

Also, @henrily suggested a workaroud somebody can use, but it's just a workaround.

Body:
Debugger shows, that there is POST data in request, but I cannot get it by $request->get('foo');

And $request->request->all(); gives array [0].

My Ajax POST request (by AngularJS):

...
    $http.post('http://admin/about-company/setJSONObj',
        {foo: 'bar'}
    );

My controller with debugging info in comments (Symfony 3.2.9):

use Symfony\Component\HttpFoundation\Request;
    ...
    public function updateAction(Request $request)
        {
             $foo = $request->get('foo'); // null
             $requestType = $request->getContentType(); // json
             $content = $request->getContent(); // {"foo":"bar"}

I used these approach on Symfony 2.7 project, and it worked fine, but I'm not sure, what's happening in these case?

Also, maybe there is any Symfony framework config variable that tells not to parse POST data, or hides it during caching the request?


问:
how to solve the error when convert string date to integer?
I would like to convert my string date to int but I get an error, example of my date 'dim. janv. 23 24:00:00 +0000 2011`
This is part of my code :

```<code>   String created_at =  (String) jsonObject.get("created_at");
   System.out.println("la date de création de tweet est: " + created_at);
   DateFormat df = new SimpleDateFormat(" ddd. MMMM. EE HH:mm:ss z yyyy");
   String s= df.format(created_at);
   int out=Integer.valueOf(s);
   System.out.println("new date " +out);
</code>```

And the output is:

java.lang.IllegalArgumentException: Cannot format given Object as a Date.

答:
Well, you already have the date in String format and that's what the format method does. I am assuming what you want to do here is to parse the date (into Date object) and not format.

Also, it looks like the date is in French locale, so you need to use appropriate locale along with SimpleDateFormat and use parse method, e.g.:

```<code>DateFormat df = new SimpleDateFormat("EEE MMMM dd HH:mm:ss z yyyy", Locale.FRANCE);
Date date = df.parse("dim. janv. 23 24:00:00 +0000 2011");
System.out.println(date);
</code>```

This would give you the Date object. If you want to format it differently, you can call format method with different format.

Update

Also, it looks like you are calling overloaded version of format method (by passing in a String and not a Date object. This evantually calls format method of TextFormat class (javadoc here) and that's why you get that Exception.

Body:
I would like to convert my string date to int but I get an error, example of my date 'dim. janv. 23 24:00:00 +0000 2011`
This is part of my code :

   String created_at =  (String) jsonObject.get("created_at");
   System.out.println("la date de création de tweet est: " + created_at);
   DateFormat df = new SimpleDateFormat(" ddd. MMMM. EE HH:mm:ss z yyyy");
   String s= df.format(created_at);
   int out=Integer.valueOf(s);
   System.out.println("new date " +out);

And the output is:

java.lang.IllegalArgumentException: Cannot format given Object as a Date.

Body:
Well, you already have the date in String format and that's what the format method does. I am assuming what you want to do here is to parse the date (into Date object) and not format.

Also, it looks like the date is in French locale, so you need to use appropriate locale along with SimpleDateFormat and use parse method, e.g.:

DateFormat df = new SimpleDateFormat("EEE MMMM dd HH:mm:ss z yyyy", Locale.FRANCE);
Date date = df.parse("dim. janv. 23 24:00:00 +0000 2011");
System.out.println(date);

This would give you the Date object. If you want to format it differently, you can call format method with different format.

Update

Also, it looks like you are calling overloaded version of format method (by passing in a String and not a Date object. This evantually calls format method of TextFormat class (javadoc here) and that's why you get that Exception.


问:
How should I indent nested case expressions?
How to indent correctly a nested case expression in haskell that would act like a nested loop in imperative programming ?

```<code>f x y = case x of
     1 -> case y of
          1 ->
          2 ->
          ...
     2 -> case y of
       ...
</code>```

The compiler gives me an indentation error at the start of the second x case, so i'm guessing it doesn't understand that the first x case is over

答: I had the same problem and it was due to that I was using tabs for identation. When I indentated the code with spaces, it worked!</p>

Body:
How to indent correctly a nested case expression in haskell that would act like a nested loop in imperative programming ?

f x y = case x of
     1 -> case y of
          1 ->
          2 ->
          ...
     2 -> case y of
       ...

The compiler gives me an indentation error at the start of the second x case, so i'm guessing it doesn't understand that the first x case is over


问:
Differences in string compare methods in C#
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?  </p>

```<code>string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
</code>```

<p>(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)</p>

答: Using .Equals is also a lot easier to read.

OwnerDisplayName: Craig

Body:
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?

string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}

(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)

OwnerDisplayName: hometoast


问:
Is it possible to mark a property shown in a property grid as a password field
I'm using C# and have a windows form containing a property grid control.

I have assigned the SelectedObject of the propertygrid to a settings file, which displays and lets me edit the settings. However one of the settings is a password - and I'd like it to display asterisks in the field rather than the plain text value of the password setting.

The field will be encrypted when saved, but I want it to behave like a normal password entry box with asterisks displayed when the user is entering in the password.

I'm wondering if there is an attribute that can be applied to the setting property to mark it as being a password?

Thanks.

答:
Here's what I've done in the past. It displays "********" for the password in the grid, with a "..." button to allow the user to set the password (using a dialog that you supply).</p>

```<code>public class User
{
    [TypeConverter(typeof(PasswordConverter))]
    [Editor(typeof(PasswordEditor), typeof(UITypeEditor))]
    public string Password { get; set; }
}

public class PasswordConverter : TypeConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(string)) return true;

        return base.CanConvertTo(context, destinationType);
    }

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            string password = (string)value;

            if (password != null && password.Length > 0)
            {
                return "********";
            }
        }

        return base.ConvertTo(context, culture, value, destinationType);
    }
}

public class PasswordEditor : UITypeEditor
{
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        string password = (string)value;

        // Show a dialog allowing the user to enter a password

        return password;
    }

    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }
}
</code>```

Body:
Here's what I've done in the past. It displays "********" for the password in the grid, with a "..." button to allow the user to set the password (using a dialog that you supply).

public class User
{
    [TypeConverter(typeof(PasswordConverter))]
    [Editor(typeof(PasswordEditor), typeof(UITypeEditor))]
    public string Password { get; set; }
}

public class PasswordConverter : TypeConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(string)) return true;

        return base.CanConvertTo(context, destinationType);
    }

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            string password = (string)value;

            if (password != null && password.Length > 0)
            {
                return "********";
            }
        }

        return base.ConvertTo(context, culture, value, destinationType);
    }
}

public class PasswordEditor : UITypeEditor
{
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        string password = (string)value;

        // Show a dialog allowing the user to enter a password

        return password;
    }

    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }
}

OwnerDisplayName: Jon B


问:
Command-line arguments to an exe
I have a slight problem with Powershell strings. There is a Java program I'm using called SymmetricDS which accepts arguments to a Windows batch file for certain administrative functions. One of these is to open registration for a node, passing a string containing the node's group and id:

```<code>& .\bin\sym.bat -p symmetric.properties --open-registration 'store,01'
</code>```

In the batch file, java is called, with properties I passed above being passed in like so:

```<code>java -Dthis -Dthat -Dfoo -Dbar %1 %2 %3 %4 %5 %6 %7 %8 %9
</code>```

The function in the java itself fails after this part:

```<code>int index = argument.trim().indexOf(",");
if (index < 0) {
    throw new SymmetricException("LauncherMissingFilenameTriggerSQL", OPTION_OPEN_REGISTRATION);
}
</code>```

index apparently is -1. Why it is not finding the comma character, I don't know. I just know that when I run the same in a .cmd or .bat file, it works just fine:

```<code>.\bin\sym.bat -p symmetric.properties --open-registration "store,01"
</code>```

I suspect it has something to do with Powershell's string being Unicode, and something improper happens in their journey from there into a batch file and then into java.

Anybody know how I can call this directly in Powershell?

Resolved: zdan's answer works, as does tricking Powershell a little bit like this:

```<code>.\bin\sym.bat -p symmetric.properties --open-registration '"store,01"'
</code>```

答:
It's not a unicode issue. You stumbling against powershell's parser. When you invoke the call operator, powershell parses the rest of your arguments and then passes them to the script you are calling. The single quotes around the string 'store,01' effectively get stripped and gets interpreted a list that is expanded into two separate arguments.

Just run cmd.exe directly, while carefully quoting your command string:

```<code> cmd.exe /c ' .\sym.bat -p symmetric.properties --open-registration "store,01" '
</code>```

Note that you have to pass the command to cmd.exe as a single string, otherwise it will be parsed by powershell.

Title: Command-line arguments to an exe

Body:
I have a slight problem with Powershell strings. There is a Java program I'm using called SymmetricDS which accepts arguments to a Windows batch file for certain administrative functions. One of these is to open registration for a node, passing a string containing the node's group and id:

& .\bin\sym.bat -p symmetric.properties --open-registration 'store,01'

In the batch file, java is called, with properties I passed above being passed in like so:

java -Dthis -Dthat -Dfoo -Dbar %1 %2 %3 %4 %5 %6 %7 %8 %9

The function in the java itself fails after this part:

int index = argument.trim().indexOf(",");
if (index < 0) {
    throw new SymmetricException("LauncherMissingFilenameTriggerSQL", OPTION_OPEN_REGISTRATION);
}

index apparently is -1. Why it is not finding the comma character, I don't know. I just know that when I run the same in a .cmd or .bat file, it works just fine:

.\bin\sym.bat -p symmetric.properties --open-registration "store,01"

I suspect it has something to do with Powershell's string being Unicode, and something improper happens in their journey from there into a batch file and then into java.

Anybody know how I can call this directly in Powershell?

Resolved: zdan's answer works, as does tricking Powershell a little bit like this:

.\bin\sym.bat -p symmetric.properties --open-registration '"store,01"'

Body:
It's not a unicode issue. You stumbling against powershell's parser. When you invoke the call operator, powershell parses the rest of your arguments and then passes them to the script you are calling. The single quotes around the string 'store,01' effectively get stripped and gets interpreted a list that is expanded into two separate arguments.

Just run cmd.exe directly, while carefully quoting your command string:

 cmd.exe /c ' .\sym.bat -p symmetric.properties --open-registration "store,01" '

Note that you have to pass the command to cmd.exe as a single string, otherwise it will be parsed by powershell.


答:
Or you can make it with jquery so much easier:

$('.fw_customText').on('click', function() {
     $(this).closest(".sType_click").toggleClass("sOpen");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sOpen{
   background-color:green;
}</code>```

      Custom text

      Custom text

      Custom text

```

Title: Javascript toggle class on element

Body:
Or you can make it with jquery so much easier:

$('.fw_customText').on('click', function() {
     $(this).closest(".sType_click").toggleClass("sOpen");
});

.sOpen{
   background-color:green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sType_click">
        <div class="Switcher">
      <span class="fw_customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
        <div class="Switcher">
      <span class="fw_customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
        <div class="Switcher">
      <span class="fw_customText">Custom text</span>
    </div>
</div>


问:
Javascript/HTML5 - Save mute on localstorage
I'm creating 5 games with javascript and html5 and I'm using sound. I have a mute button that activates the function down bellow. Thing is, I want to make so that if I press the mute button and I move to another page, it will still be muted, but I can't seem to figure out how to integrate it in this function. If someone could help me out by editing the code, I'd really apreciate it :D</p>

```<code>function init(){
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;

    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);

function mute(){
    if (audio.muted){
        audio.muted = false;
        document.getElementById("mutebtn").src = "img/soundON.png";
    } else {
        audio.muted = true;
        document.getElementById("mutebtn").src = "img/soundOFF.png";

        }

    }
}
</code>```

答:
Add the muted value to your localStorage in your 'mute' method.

```<code>function mute(){
        ...
        audio.muted = false;
        localStorage.setItem('muted', 'false');
    } else {
        audio.muted = true;
        localStorage.setItem('muted', 'true');
    }
}
</code>```

}

Then on your init retrieve the localStorage value or default to false if it wasn't set prior.

```<code>function init(){
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;
    var isMuted = (localStorage.getItem("muted") && localStorage.getItem("muted") == 'true') || false

    audio.muted = isMuted;
    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);
}
</code>```

Body:
I'm creating 5 games with javascript and html5 and I'm using sound. I have a mute button that activates the function down bellow. Thing is, I want to make so that if I press the mute button and I move to another page, it will still be muted, but I can't seem to figure out how to integrate it in this function. If someone could help me out by editing the code, I'd really apreciate it :D

function init(){
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;

    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);

function mute(){
    if (audio.muted){
        audio.muted = false;
        document.getElementById("mutebtn").src = "img/soundON.png";
    } else {
        audio.muted = true;
        document.getElementById("mutebtn").src = "img/soundOFF.png";

        }

    }
}

Body:
Add the muted value to your localStorage in your 'mute' method.

function mute(){
        ...
        audio.muted = false;
        localStorage.setItem('muted', 'false');
    } else {
        audio.muted = true;
        localStorage.setItem('muted', 'true');
    }
}

}

Then on your init retrieve the localStorage value or default to false if it wasn't set prior.

function init(){
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;
    var isMuted = (localStorage.getItem("muted") && localStorage.getItem("muted") == 'true') || false

    audio.muted = isMuted;
    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);
}


答:
Modify your function like this</p>

```<code>function init() {
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;
    var muteState = localStorage.getItem('muteState');
    if (!muteState || muteState !== 'true') {
        audio.muted = false;
        document.getElementById("mutebtn").src = "img/soundON.png";
    }
    else {
        audio.muted = true;
        document.getElementById("mutebtn").src = "img/soundOFF.png";
    }
    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);

    function mute() {
        if (audio.muted) {
            audio.muted = false;
            document.getElementById("mutebtn").src = "img/soundON.png";
        } else {
            audio.muted = true;
            document.getElementById("mutebtn").src = "img/soundOFF.png";
        }
        localStorage.setItem('muteState', String(audio.muted));
    }

}
</code>```

Title: Javascript/HTML5 - Save mute on localstorage

Body:
Modify your function like this

function init() {
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;
    var muteState = localStorage.getItem('muteState');
    if (!muteState || muteState !== 'true') {
        audio.muted = false;
        document.getElementById("mutebtn").src = "img/soundON.png";
    }
    else {
        audio.muted = true;
        document.getElementById("mutebtn").src = "img/soundOFF.png";
    }
    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);

    function mute() {
        if (audio.muted) {
            audio.muted = false;
            document.getElementById("mutebtn").src = "img/soundON.png";
        } else {
            audio.muted = true;
            document.getElementById("mutebtn").src = "img/soundOFF.png";
        }
        localStorage.setItem('muteState', String(audio.muted));
    }

}


问:
Scipy Import Error; cannot import name NUMPY_MKL
I used python xy recently with an old lib of scipy (0.15). Because I wanted to use Spherical Voronoi, I had to install a more recent version of scipy. For this I used pip and the unofficial distributions for python modules with wheel. The install worked without error messages. But now, if I try to import scipy by code, I get this error message below. I already unistalled whole python packages so far and instead installed anaconda. But the error message is still the same. I checked my registry (Windows 10) - can't find anything suspicious.

Any idea? Thank you!

```<code>test.py
1.12.1
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    import scipy
  File "C:\Users\Boss\AppData\Roaming\Python\Python27\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name NUMPY_MKL
</code>```

答:
Updated - Your error is basically that  numpy+mkl (numpy with Intel math Kernel library) so this is because when you have installed the scipy by precompiled archive, which requires  numpy+mkl but installing numpy using pip won't get you that.

This problem can be easy solved by installation for numpy+mkl from whl file from - http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

Old -  This is due to the improper installation of numpy, I've had this error few days ago and then I had to install the numpy again. So, upgrade pip and then try installing the numpy whl again. It just worked for me.

Get it here -https://pypi.python.org/pypi/numpy

even this has almost everything - http://www.lfd.uci.edu/~gohlke/pythonlibs/

Body:
I used python xy recently with an old lib of scipy (0.15). Because I wanted to use Spherical Voronoi, I had to install a more recent version of scipy. For this I used pip and the unofficial distributions for python modules with wheel. The install worked without error messages. But now, if I try to import scipy by code, I get this error message below. I already unistalled whole python packages so far and instead installed anaconda. But the error message is still the same. I checked my registry (Windows 10) - can't find anything suspicious.

Any idea? Thank you!

test.py
1.12.1
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    import scipy
  File "C:\Users\Boss\AppData\Roaming\Python\Python27\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name NUMPY_MKL


问:
What is a good way to assign order #s to ordered rows in a table in Sybase
I have a table T (structure below) which initially contains all-NULL values in an integer order column:

```
col1  varchar(30),
col2  varchar(30),
order int NULL
```

I also have a way to order the "colN" columns, e.g.

SELECT * FROM T ORDER BY some_expression_involving_col1_and_col2

What's the best way to assign - IN SQL - numeric order values 1-N to the order table, so that the order values match the order of rows returned by the above ORDER BY?

In other words, I would like a single query (Sybase SQL syntax so no Oracle's rowcount) which assigns order values so that SELECT * FROM T ORDER BY order returns 100% same order of rows as the query above.

The query does NOT necessarily need to update the table T in place, I'm OK with creating a copy of the table T2 if that'll make the query simpler.

NOTE1: A solution must be real query or a set of queries, not involving a loop or a cursor.

NOTE2: Assume that the data is uniquely orderable according to the order by above - no need to worry about situation when 2 rows can be assigned the same order at random.

NOTE3: I would prefer a generic solution, but if you wish a specific example of ordering expression, let's say:

```
SELECT * FROM T
ORDER BY CASE WHEN col1="" THEN "AAAAAA" ELSE col1 END, ISNULL(col2, "ZZZ")
```

答:
DVK

People have answered your specific question, and you have chosen an answer.

But the whole issue has a deeper problem.

From what I can understand, the Order is a column in the table; which identifies the Order in which the rows are to be presented (or similar).  Is that correct ?

If so, then the table is massively denormalised: you have broken 3NF (Functional Dependency rule is broken); you have a derived value in a column (duplicated information); introduced Update Anomalies (when you update data in a column, you now need to update the duplicated [dependent] data in another column).

The most important of those is of course the Update Anomalies.  You can no longer insert a row into the (now non-relational, unnormalised) table.  For every insert, you have to recalculate and UPDATE the Order column for at least one and at most every other row in the table.

None of that is necessary.

I could answer your question within the scope of your question only, to populate the Order column (to be called by the code segment that constantly maintains it).  The code required is 5 lines. Pure standard SQL on the base table.  No views. No temp tables. No loops or cursors. Works the same as the Oracle RANK() function, and is therefore generic (just substitute your table and column names).

but the point is, that is the same code that could and would be used at runtime to produce the Order column, if it was a Derived Value, not a real column in the database.  So again, the Order column, and all the code required to maintain it, can be removed.

therefore I may as well give you the code to produce the Order or Rank [derived] value directly from your base tables, without regard to the Order column.

Following that, the assignment of Order is trivial.  Another way of stating that is, I would replace your first SELECT, and perform both functions in one code segment; there is no need for the COUNT() as a separate code segment.

Are you interested ?

In which case I need to know the exact col_N types, and what the Order value is based on, eg. highest Student Mark.  Table Definition (obfuscated) is easier.

Response to Comments

Well, if it is a temp table, there is a much easier way, a different approach:

Give it an Order column

define it as IDENTITY

ensure the SELECT you use to populate it has the correct ORDER BY

.

Do you still need the Order computed ?

If so, pardon me, I don't know how to make this sound more nice. I realise you think  I do not need to know the answer to my question; but the code I use is beyond that threshold, otherwise you would have coded it by now (you seem to have some experience SQL and Sybase).

I am  not "drafting", I have had the code for 20 years.  In each instance, I just have to plug in the specific table and column names, takes 10 seconds.  Therefore I do know what the code needs (as in, I understand the logical principle the code uses, the code itself is dead simple).  And of course there are variations, because it is a logical solution, not merely a piece of clever code: one person wants Students ranked by Mark; someone else wants two columns with the second one DESCending.

It always takes longer to explain the problem, than to fix it.

Eg. you have 2 columns (the description is fine, thanks). But you are asking for an ordinal, which (by definition) requires only one column or aggregate. Imagine an Unique Clustered Index on (col_1, col2), which is what you are saying the Order needs to identify. I do not understand why is col_2 relevant.  If the ordinal for the row where col_1 is "KKKKKK" is 12345, then the ordinal for the row is "KKKKKL" will have to be 12346; regardless of what col_2 is, in either of those two rows.  It is the leading column of the index.

The code I supply has to take whatever you are logically doing in that ORDER BY clause into account.  Otherwise it will be "unfinished" or "incomplete", and you still have to mess with it; which is not going to be fair to you because you do not understand the logical principle behind it.

Then you have the complication due to the use of VARCHARs, which is easy to code around, but I need to know what it is.  Using my Clustered Index visualisation, which of these four is correct ?  Do I need LTRIM() ?
( col_1 , col2)

( CONVERT( CHAR(30), col_1 ) , CONVERT( CHAR(30), col_2 ) )

( col_1 + col_2 )  -- as varchars

( CONVERT( CHAR(30), col_1 ) + CONVERT( CHAR(30), col_2 ) )

Cheers

Body:
I have a table T (structure below) which initially contains all-NULL values in an integer order column:

col1  varchar(30),
col2  varchar(30),
order int NULL

I also have a way to order the "colN" columns, e.g.

SELECT * FROM T ORDER BY some_expression_involving_col1_and_col2

What's the best way to assign - IN SQL - numeric order values 1-N to the order table, so that the order values match the order of rows returned by the above ORDER BY?

In other words, I would like a single query (Sybase SQL syntax so no Oracle's rowcount) which assigns order values so that SELECT * FROM T ORDER BY order returns 100% same order of rows as the query above.

The query does NOT necessarily need to update the table T in place, I'm OK with creating a copy of the table T2 if that'll make the query simpler.

NOTE1: A solution must be real query or a set of queries, not involving a loop or a cursor.

NOTE2: Assume that the data is uniquely orderable according to the order by above - no need to worry about situation when 2 rows can be assigned the same order at random.

NOTE3: I would prefer a generic solution, but if you wish a specific example of ordering expression, let's say:

SELECT * FROM T
ORDER BY CASE WHEN col1="" THEN "AAAAAA" ELSE col1 END, ISNULL(col2, "ZZZ")


答:
its easy, Just add an event click to the object

es:

```<code><div class="sType_click" onclick="sType_click_eve(this)">
    <div class="Switcher">
    <span class="fw_customText">Custom text</span>
</div>
</code>```

And on the page

```<code>function sType_click_eve(ele){
      var sType_click = ele,
      customText = document.querySelector(".customText"),
      if (null !== document.querySelector(".customText")) {
         customText.onclick = function() {
            sType_click.classList.toggle("sOpen");
         };
      }
}
</code>```

Title: Javascript toggle class on element

Body:
its easy, Just add an event click to the object

es:

<div class="sType_click" onclick="sType_click_eve(this)">
    <div class="Switcher">
    <span class="fw_customText">Custom text</span>
</div>

And on the page

function sType_click_eve(ele){
      var sType_click = ele,
      customText = document.querySelector(".customText"),
      if (null !== document.querySelector(".customText")) {
         customText.onclick = function() {
            sType_click.classList.toggle("sOpen");
         };
      }
}


问:
MVC Model Duplication in C#
I have a need for models that are mapped to their corresponding data tables, and every time the models/tables are updated, I need to mapped the changes to the archived tables for historical references. For example -

```<code>[Table("A")]
public class A
{
    [Key]
    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

[Table("A_History")]
public class A_History
{
    [Key]
    public int A_History_Id { get; set; }

    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}
</code>```

So every time Table A is modified, I need to add an entry to A_History with an exact copy of the new or original data. Is there a generic way to do this, such that I can pass in a string as the Model name to a method or class, and the method can automatically loop through all the properties of the Model class, and map them to another class to be added by matching the names?

答:
If your history model has the same properties as the model that holds the history of then you can do something like.

Add the Newtonsoft.Json nuget package and do.

Add the code shown bellow.

```<code>A model = new A();
//.....
// add data to the model
var json = JsonConvert.SerializeObject(model);
A_History historyModel = JsonConvert.DeserializeObject<A_History>(json);
</code>```

Now your history model will have filled all the properties that are the same with the A model.

Title: MVC Model Duplication in C#

Body:
I have a need for models that are mapped to their corresponding data tables, and every time the models/tables are updated, I need to mapped the changes to the archived tables for historical references. For example -

[Table("A")]
public class A
{
    [Key]
    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

[Table("A_History")]
public class A_History
{
    [Key]
    public int A_History_Id { get; set; }

    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

So every time Table A is modified, I need to add an entry to A_History with an exact copy of the new or original data. Is there a generic way to do this, such that I can pass in a string as the Model name to a method or class, and the method can automatically loop through all the properties of the Model class, and map them to another class to be added by matching the names?

Body:
If your history model has the same properties as the model that holds the history of then you can do something like.

Add the Newtonsoft.Json nuget package and do.

Add the code shown bellow.

A model = new A();
//.....
// add data to the model
var json = JsonConvert.SerializeObject(model);
A_History historyModel = JsonConvert.DeserializeObject<A_History>(json);

Now your history model will have filled all the properties that are the same with the A model.


问:
Howler.js error: ' An array of source files must be passed with any new Howl '
So i'm trying to test out using Howler.js to play an audio file. When I run this html file and press the button I get an error in console saying "An array of source files must be passed with any new Howl."

html:

```<code><!DOCTYPE html>
<html>
<head>
<title>Play Sound</title>
<script src='./howler.js/dist/howler.js'></script>
</head>
<body>
<button id="btn">Play</button>

<script>
  var pong = new Howl({urls: ['sound.mp3', 'sound.ogg']});
  document.getElementById('btn').onclick=function(){pong.play();}
</script>
</body>
</html>
</code>```

答:
Should be </p>

```<code>var pong = new Howl({
     src: ['sound.mp3', 'sound.ogg']
});
</code>```

Body:
So i'm trying to test out using Howler.js to play an audio file. When I run this html file and press the button I get an error in console saying "An array of source files must be passed with any new Howl."

html:

<!DOCTYPE html>

<title>Play Sound</title>

<button id="btn">Play</button>

Body:
Should be

var pong = new Howl({
     src: ['sound.mp3', 'sound.ogg']
});


问:
Difference between typealias and val for object
For a class, it is clear that we can not use val to refer to a type.

For example,

```<code>class LongName {
    ...
}

typealias A = LongName // OK
val B = LongName // compile error
val C = LongName() // compiles, but it refers to an instance, not the class itself
</code>```

However, for an (singleton) object, both compiles. In addition, both can be used for its members.

```<code>object LongName {
    val a = "123"
}

typealias A = LongName
val B = LongName

...

// In a function,
println(A.a) // compiles
println(B.a) // compiles
</code>```

What is difference between them?

答:
Assigning a typealias to a class or an object will always work because you are just giving another name to it. From the docs,

Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead.

While assigning a val is different. val can only be used for properties or objects.

In your first example,

val B = LongName

here the compiler tries to find an object or property and assign it to B which it cannot, because LongName is a class and it does not have any companion object either.

In case, if you define a companion object with the class like,

```<code>class LongName {
    companion object {
        val a = "123"
    }
}
</code>```

Then you can access it like,

```<code>val b = LongName
info(b.a) //123
</code>```

Though it doesn't make much sense to do it this way as you always have access to properties in companion object statically like, LongName.a.

Body:
For a class, it is clear that we can not use val to refer to a type.

For example,

class LongName {
    ...
}

typealias A = LongName // OK
val B = LongName // compile error
val C = LongName() // compiles, but it refers to an instance, not the class itself

However, for an (singleton) object, both compiles. In addition, both can be used for its members.

object LongName {
    val a = "123"
}

typealias A = LongName
val B = LongName

...

// In a function,
println(A.a) // compiles
println(B.a) // compiles

What is difference between them?

Body:
Assigning a typealias to a class or an object will always work because you are just giving another name to it. From the docs,

Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead.

While assigning a val is different. val can only be used for properties or objects.

In your first example,

val B = LongName

here the compiler tries to find an object or property and assign it to B which it cannot, because LongName is a class and it does not have any companion object either.

In case, if you define a companion object with the class like,

class LongName {
    companion object {
        val a = "123"
    }
}

Then you can access it like,

val b = LongName
info(b.a) //123

Though it doesn't make much sense to do it this way as you always have access to properties in companion object statically like, LongName.a.


问:
C# how to use a specific method with interfaces
I have 2 classes and an interface:
Program, superSecretWork and openDoor.

What I want to do is, whenever my class is using an interface, I want that interface to call a particular method of the class that's inheriting it.

I know I could just use the class superSecretWork, but that isn't the point. I might want to inherit another base class but need parts of other classes (used by other interfaces).

Code example:

```<code>namespace Test
{
    class Program: openDoor
    {
        static void Main(string[] args)
        {
        }
    }

    public interface openDoor
    {
        bool open();
    }
    public class superSecretWork : openDoor
    {
        /// <summary>
        /// I only want this method to be used when using the interface
        /// </summary>
        /// <returns></returns>
        public bool open()
        {
            //some custom logic here
            return true;
        }
    }
}
</code>```

答:
You can't prevent someone from calling a method on a class without casting it as an interface.

For example:

```<code>public interface IDoesSomething
{
    void DoSomething();
}

public class DoerOfStuff : IDoesSomething

    void DoSomething()
    {
        // whatever
    }
}
</code>```

You can't prevent someone from calling DoSomething on an instance of DoerOfStuff. The class has that method, so someone can call it.

What you can do is have a class implement multiple interfaces, and cast a class according to the interface that a method should see.

For example:

```<code>public interface IFryCook
{
    void Fry(FrenchFries fries);
}

public interface IGrillCook
{
    void Grill(Burger burger);
}

public class FastFoodCook : IFryCook, IGrillCook
{
    public void Fry(FrenchFries fries) { }
    public void Grill(Burger burger) { }
}
</code>```

If you do this:

```<code>public void ProcessFrenchFryOrder(IFryCook frycook)
</code>```

You can pass an instance of FastFoodCook to the method, but it will only be "seen" as an instance of IFryCook. The method doesn't know that the class also implements other methods.

It's also good to rethink whether you want to use class inheritance. It sounds like that already added some difficulty to your problem. If you have functionality in class A that you want in class B, inheriting from A often causes difficulties. It's better for class B to depend on a separate instance of class A. The principle is "favor composition over inheritance." If the way we get classes to work together is by having them inherit from each other then we paint ourselves into a corner because sooner or later we'll want to use functionality from two classes and we can't inherit from them both.

Body:
I have 2 classes and an interface:
Program, superSecretWork and openDoor.

What I want to do is, whenever my class is using an interface, I want that interface to call a particular method of the class that's inheriting it.

I know I could just use the class superSecretWork, but that isn't the point. I might want to inherit another base class but need parts of other classes (used by other interfaces).

Code example:

namespace Test
{
    class Program: openDoor
    {
        static void Main(string[] args)
        {
        }
    }

    public interface openDoor
    {
        bool open();
    }
    public class superSecretWork : openDoor
    {
        ///
        /// I only want this method to be used when using the interface
        ///
        /// <returns></returns>
        public bool open()
        {
            //some custom logic here
            return true;
        }
    }
}

Body:
You can't prevent someone from calling a method on a class without casting it as an interface.

For example:

public interface IDoesSomething
{
    void DoSomething();
}

public class DoerOfStuff : IDoesSomething

    void DoSomething()
    {
        // whatever
    }
}

You can't prevent someone from calling DoSomething on an instance of DoerOfStuff. The class has that method, so someone can call it.

What you can do is have a class implement multiple interfaces, and cast a class according to the interface that a method should see.

For example:

public interface IFryCook
{
    void Fry(FrenchFries fries);
}

public interface IGrillCook
{
    void Grill(Burger burger);
}

public class FastFoodCook : IFryCook, IGrillCook
{
    public void Fry(FrenchFries fries) { }
    public void Grill(Burger burger) { }
}

If you do this:

public void ProcessFrenchFryOrder(IFryCook frycook)

You can pass an instance of FastFoodCook to the method, but it will only be "seen" as an instance of IFryCook. The method doesn't know that the class also implements other methods.

It's also good to rethink whether you want to use class inheritance. It sounds like that already added some difficulty to your problem. If you have functionality in class A that you want in class B, inheriting from A often causes difficulties. It's better for class B to depend on a separate instance of class A. The principle is "favor composition over inheritance." If the way we get classes to work together is by having them inherit from each other then we paint ourselves into a corner because sooner or later we'll want to use functionality from two classes and we can't inherit from them both.


问:
ActionController::InvalidAuthenticityToken error in rails
I wanted to add some custom fields to devise authentication, so I followed a tutorial and did some changes. I unpacked the devise gem, added the fields to the views, and devise controller. I added the fields "first_name" and "last_name" to my users table. The changes didn't work. So I didn't want to spend much time on that, so I wanted to move on, I removed all the code I added to the devise gem sourcecode, created a migration to remove first_name, and last_name from users. Everything looked fine, I can move about on the site and everything. But as soon as I try to sign out, I get this error:

In the command line, the error also says "can't verify CSRF token auhtenticity"

This is the code I have in my layout view navbar for the user to sign out:

```<code>    <% if user_signed_in? %>
        <li><%= link_to "Sign out", destroy_user_session_path, method: :delete %></li>
    <%else%>
        <li>
            <%= link_to "sign up" , new_user_registration_path %>
        </li>
        <li>
            <%= link_to "Log in", new_user_session_path%>
        </li>
    <%end%>
</code>```

I restarted the server and all that. The user is still signed in. I can't do anything to sign out. Is there a way to fix this?

答:
To destroy a user session in devise, you have to do the following:

```<code><%= link_to "Logout", destroy_user_session_path, :method => :delete %>
</code>```

the hash ':method' will trigger delete action and sign the user out and destroy current session. Make sure your pointing to your "destroy_user_session_path", or the path you specified. You should be able to see what the name of the path is by using "rails routes" or "rake routes" command depending on what version of rails you're using.

Hope this helps.

Body:
I wanted to add some custom fields to devise authentication, so I followed a tutorial and did some changes. I unpacked the devise gem, added the fields to the views, and devise controller. I added the fields "first_name" and "last_name" to my users table. The changes didn't work. So I didn't want to spend much time on that, so I wanted to move on, I removed all the code I added to the devise gem sourcecode, created a migration to remove first_name, and last_name from users. Everything looked fine, I can move about on the site and everything. But as soon as I try to sign out, I get this error:

In the command line, the error also says "can't verify CSRF token auhtenticity"

This is the code I have in my layout view navbar for the user to sign out:

    <% if user_signed_in? %>

<%= link_to "Sign out", destroy_user_session_path, method: :delete %>

    <%else%>

            <%= link_to "sign up" , new_user_registration_path %>

            <%= link_to "Log in", new_user_session_path%>

    <%end%>

I restarted the server and all that. The user is still signed in. I can't do anything to sign out. Is there a way to fix this?

Body:
To destroy a user session in devise, you have to do the following:

<%= link_to "Logout", destroy_user_session_path, :method => :delete %>

the hash ':method' will trigger delete action and sign the user out and destroy current session. Make sure your pointing to your "destroy_user_session_path", or the path you specified. You should be able to see what the name of the path is by using "rails routes" or "rake routes" command depending on what version of rails you're using.

Hope this helps.


问:
Could not get resource for Android Architecture Components
I applied to my project Android Architecture Components, by adding this lines to build.gradle:

```<code>// Android Architecture Lifecycle
compile "android.arch.lifecycle:runtime:1.0.0-alpha1"
compile "android.arch.lifecycle:extensions:1.0.0-alpha1"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"

// Android Architecture Room
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
compile "android.arch.persistence.room:rxjava2:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
</code>```

It worked, but after updating Android Studio to Canary 3 version I'm still getting this error while compiling

Error:org.gradle.api.resources.ResourceException: Could not get
  resource
  'https://jitpack.io/android/arch/lifecycle/runtime/1.0.0-alpha1/runtime-1.0.0-alpha1.pom'.

Error:org.gradle.api.UncheckedIOException: Could not HEAD
  'https://jitpack.io/android/arch/lifecycle/runtime/1.0.0-alpha1/runtime-1.0.0-alpha1.pom'.
  Received status code 401 from server: Unauthorized

... other poms from library with the same error.

I tried restarting Android Studio, uninstalling app and of course clean-rebuild.

答:
You need to add the new public Maven repo that Google is using to your build.gradle file.

For example, you could add it to the allprojects closure in the top-level build.gradle file:

```<code>allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}
</code>```

Then, all of your modules (e.g., app/) will know to look there in addition to other places for the artifacts.

From your error message, it would appear that Android Studio is only looking in jitpack.io.

Body:
I applied to my project Android Architecture Components, by adding this lines to build.gradle:

// Android Architecture Lifecycle
compile "android.arch.lifecycle:runtime:1.0.0-alpha1"
compile "android.arch.lifecycle:extensions:1.0.0-alpha1"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"

// Android Architecture Room
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
compile "android.arch.persistence.room:rxjava2:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"

It worked, but after updating Android Studio to Canary 3 version I'm still getting this error while compiling

Error:org.gradle.api.resources.ResourceException: Could not get
  resource
  'https://jitpack.io/android/arch/lifecycle/runtime/1.0.0-alpha1/runtime-1.0.0-alpha1.pom'.

Error:org.gradle.api.UncheckedIOException: Could not HEAD
  'https://jitpack.io/android/arch/lifecycle/runtime/1.0.0-alpha1/runtime-1.0.0-alpha1.pom'.
  Received status code 401 from server: Unauthorized

... other poms from library with the same error.

I tried restarting Android Studio, uninstalling app and of course clean-rebuild.

Body:
You need to add the new public Maven repo that Google is using to your build.gradle file.

For example, you could add it to the allprojects closure in the top-level build.gradle file:

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

Then, all of your modules (e.g., app/) will know to look there in addition to other places for the artifacts.

From your error message, it would appear that Android Studio is only looking in jitpack.io.


问:
What is the best tool to draw out large inheritance pieces of code?
I have started doing a code review for someone, and there is a large inheritance model (many layers deep).  After filling up my white board, I realized that I need a tool to draw this out.

What is the best tool (preferably free) to draw this out, so I can visualize what's happening in the code base.  The code is in Python, but I think my question or the solution should be generic.  I don't mind drawing it out by hand as the value for me is the scalability around the visualization.

答:
You can also look for Epydoc to generate an UML diagram from the source code (see this Stack Overflow question)

Also, AutoDia and HappyDoc claims that can generate Dia UML diagrams from the Python source