问:
Removing the last child node DOM
I'm trying to create a page with two different sides, and to that end I have set up in two different divs with IDs of leftSide and rightSide.

Firstly, I add an image node to leftSide five times.

Then, I clone leftSide to the rightSide div, and I want to remove the last image from rightSide so that, in total, I have five images on the left and four images on the right.

However, my code just deletes all five images on the left side, not just the last one:

```<code>function createSmile() {

    for (var i = 0; i < 5; i++) {
        var newImg = document.createElement("img");
        newImg.src = "smile.png";
        var imgPart = document.getElementById("leftSide");
        imgPart.appendChild(newImg);
    }

    document.getElementById("rightSide").appendChild(document.getElementById("leftSide").cloneNode(true));

    document.getElementById("rightSide").removeChild(document.getElementById("rightSide").lastChild);
}
</code>```

答:
The Problem

When you clone a node, you clone it's entire block of HTML. For example, when you clone leftSide and append it into rightSide, what you are appending really is this:

```<code><div id="leftSide">
    <img src="smile.png">
    <img src="smile.png">
    <img src="smile.png">
    <img src="smile.png">
    <img src="smile.png">
</div>
</code>```

Note that the leftSide div got copied in there as well? Not only is this bad because you now have two elements with the same ID, but also now there is only one child node, that div, which then contains all of the images.

What can we do about it?

Essentially what you want is to copy only the child nodes of leftSide. There are numerous ways to go about doing this:

If you are using something such as jQuery, you can use $("#leftSide").children().clone() to clone all of the child elements;

You could get the array of child nodes (document.getElementById("leftSide").childNodes), loop through it, and clone each one;

You could simply add the image nodes to both of the divs in your initial loop;

You could also copy the raw internal HTML across: document.getElementById("rightSide").innerHTML = document.getElementById("leftSide").innerHTML

These are only some of the ways you could solve this. There are many more on Google.

Title: Removing the last child node DOM

Body:
I'm trying to create a page with two different sides, and to that end I have set up in two different divs with IDs of leftSide and rightSide.

Firstly, I add an image node to leftSide five times.

Then, I clone leftSide to the rightSide div, and I want to remove the last image from rightSide so that, in total, I have five images on the left and four images on the right.

However, my code just deletes all five images on the left side, not just the last one:

function createSmile() {

    for (var i = 0; i < 5; i++) {
        var newImg = document.createElement("img");
        newImg.src = "smile.png";
        var imgPart = document.getElementById("leftSide");
        imgPart.appendChild(newImg);
    }

    document.getElementById("rightSide").appendChild(document.getElementById("leftSide").cloneNode(true));

    document.getElementById("rightSide").removeChild(document.getElementById("rightSide").lastChild);
}

Body:
The Problem

When you clone a node, you clone it's entire block of HTML. For example, when you clone leftSide and append it into rightSide, what you are appending really is this:

<div id="leftSide">
    <img src="smile.png">
    <img src="smile.png">
    <img src="smile.png">
    <img src="smile.png">
    <img src="smile.png">
</div>

Note that the leftSide div got copied in there as well? Not only is this bad because you now have two elements with the same ID, but also now there is only one child node, that div, which then contains all of the images.

What can we do about it?

Essentially what you want is to copy only the child nodes of leftSide. There are numerous ways to go about doing this:

If you are using something such as jQuery, you can use $("#leftSide").children().clone() to clone all of the child elements;

You could get the array of child nodes (document.getElementById("leftSide").childNodes), loop through it, and clone each one;

You could simply add the image nodes to both of the divs in your initial loop;

You could also copy the raw internal HTML across: document.getElementById("rightSide").innerHTML = document.getElementById("leftSide").innerHTML

These are only some of the ways you could solve this. There are many more on Google.


来源: stackexchange

问:
Return more than one result set with T-SQL
I'm trying to mimic the functionality of the Query Analyzer piece of the SQL Server Management Studio using .NET.  The user will input a SQL script, and the program will run it.  If it returns a result set, the program will load that up into a datagrid and show the user.  </p>

<p>My question is:  Is there a way to return more than one result set from a single script?  I know Query Analyzer runs this and loads up multiple datagrids if several result sets are returned, but as far as I know when you try to do this with SqlDataAdapter.Fill(...), it only returns the last result set in the script.  </p>

答:
This will show you how to return multiple result sets: http://vb.net-informations.com/ado.net-dataproviders/ado.net-multiple-result-sets.htm

You loop through the different result sets using the sqlReader.NextResult() method.  You can then use sqlReader.Read() to get each individual record in that result set.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to mimic the functionality of the Query Analyzer piece of the SQL Server Management Studio using .NET.  The user will input a SQL script, and the program will run it.  If it returns a result set, the program will load that up into a datagrid and show the user.

My question is:  Is there a way to return more than one result set from a single script?  I know Query Analyzer runs this and loads up multiple datagrids if several result sets are returned, but as far as I know when you try to do this with SqlDataAdapter.Fill(...), it only returns the last result set in the script.


问:
Nodejs net multiple data events
I have a nodejs backend working as a proxy between an angular app using websockets and a snapserver via tcp socket.

I am using rxjs to wrap the nodejs net socket as a Subject.
For some reason the 'data' event of my tcp socket is called once more each message is sent.

After some request I get a (node:21209) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit

```<code>const log = require('./logger').init('SNAPCAST');
const utils = require('./utils');
const Rx = require('rxjs/Rx');
const net = require('net');

const createSubject = () => {

  return Rx.Observable.create((observer) => {

    const socketConnection = net.connect({port: 1705}, () => {

      const socketObservable = Rx.Observable.create((observer) => {
        socketConnection.on('data', (data) => {

          if(data) {
            String(data.toString().trim()).split('\n').forEach((line) => {

              if(line) {
                observer.next(JSON.parse(line));
              }

            });
          }

        });
        socketConnection.on('error', (err) => observer.error(err));
        socketConnection.on('close', () => observer.complete());
      });

      const socketObserver = {
        next: (data) => {
          if (!socketConnection.destroyed) {
            socketConnection.write(`${JSON.stringify(data)}\r\n`);
          }
        }
      };

      const socket = Rx.Subject.create(socketObserver, socketObservable);

      observer.next(socket);
      observer.complete();

    });

    socketConnection.on('error', (err) => {
      observer.error(err);
    });

  });

};

module.exports = () => {

  return Rx.Observable.create((observer) => {

    createSubject().subscribe((socket) => {

      const sendRequest = (message) => {

        message.id = message.id || utils.UUID();
        message.jsonrpc = message.jsonrpc || '2.0';

        socket.next(message);

        return socket.filter((response) => {
          return response.id === message.id;
        }).first();

      };

      observer.next({
        proxyRequest: (request) => {
          return sendRequest(request);
        }
      });

      observer.complete();

    }, (err) => {
      observer.error(err);
    });

  });

};
</code>```

答: That is just how TCP works, it's a stream of data. So application-level messages could arrive in one or multiple 'data' events. You have to be ready to handle either situation.

ContentLicense: CC BY-SA 3.0

Title: Nodejs net multiple data events

Body:
I have a nodejs backend working as a proxy between an angular app using websockets and a snapserver via tcp socket.

I am using rxjs to wrap the nodejs net socket as a Subject.
For some reason the 'data' event of my tcp socket is called once more each message is sent.

After some request I get a (node:21209) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit

const log = require('./logger').init('SNAPCAST');
const utils = require('./utils');
const Rx = require('rxjs/Rx');
const net = require('net');

const createSubject = () => {

  return Rx.Observable.create((observer) => {

    const socketConnection = net.connect({port: 1705}, () => {

      const socketObservable = Rx.Observable.create((observer) => {
        socketConnection.on('data', (data) => {

          if(data) {
            String(data.toString().trim()).split('\n').forEach((line) => {

              if(line) {
                observer.next(JSON.parse(line));
              }

            });
          }

        });
        socketConnection.on('error', (err) => observer.error(err));
        socketConnection.on('close', () => observer.complete());
      });

      const socketObserver = {
        next: (data) => {
          if (!socketConnection.destroyed) {
            socketConnection.write(`${JSON.stringify(data)}\r\n`);
          }
        }
      };

      const socket = Rx.Subject.create(socketObserver, socketObservable);

      observer.next(socket);
      observer.complete();

    });

    socketConnection.on('error', (err) => {
      observer.error(err);
    });

  });

};

module.exports = () => {

  return Rx.Observable.create((observer) => {

    createSubject().subscribe((socket) => {

      const sendRequest = (message) => {

        message.id = message.id || utils.UUID();
        message.jsonrpc = message.jsonrpc || '2.0';

        socket.next(message);

        return socket.filter((response) => {
          return response.id === message.id;
        }).first();

      };

      observer.next({
        proxyRequest: (request) => {
          return sendRequest(request);
        }
      });

      observer.complete();

    }, (err) => {
      observer.error(err);
    });

  });

};


问:
Create single variation for woocommerce product
i need to create a single variation for any woocommerce product, however each time i hit save it creates another variation.
i'm working outside of the loop from functions.php

why each time i hit save it creates another variation, need help to create just 1 variation/child post

```<code>add_action (save_post, create_new_vars);
function create_new_vars ($post) {
global $post;
$children = get_pages('child_of='.$post->ID);
if( count( $children ) >= 1 ) {
return;
}

$my_post = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);

    remove_action('save_post', __FUNCTION__);
    $attID = wp_insert_post($my_post);

}
</code>```

答:
ok answer is</p>

```<code>add_action (save_post, create_new_vars);
function create_new_vars ($post) {
global $post;
$args  = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);
$children = get_children( $args );
if( count( $children ) < 1 ) {

$my_post = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);

    remove_action('save_post', __FUNCTION__);
    $attID = wp_insert_post($my_post);

}
}
</code>```

Body:
i need to create a single variation for any woocommerce product, however each time i hit save it creates another variation.
i'm working outside of the loop from functions.php

why each time i hit save it creates another variation, need help to create just 1 variation/child post

add_action (save_post, create_new_vars);
function create_new_vars ($post) {
global $post;
$children = get_pages('child_of='.$post->ID);
if( count( $children ) >= 1 ) {
return;
}

$my_post = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);

    remove_action('save_post', __FUNCTION__);
    $attID = wp_insert_post($my_post);

}

Body:
ok answer is

add_action (save_post, create_new_vars);
function create_new_vars ($post) {
global $post;
$args  = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);
$children = get_children( $args );
if( count( $children ) < 1 ) {

$my_post = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);

    remove_action('save_post', __FUNCTION__);
    $attID = wp_insert_post($my_post);

}
}


问:
Learning Criteria instead of hql, how to query using criteria manytomany with List of objects?
How do I do a query when I pass an integer, as an authorId, to find the books associated with that author? I tried one below gives me a 'not an association id'. What's the proper way of doing this?

Also, this many-to-many created a third table based on the annotations on  authors attribute from books.

Entity

```<code>@Entity
class Book{
  @Id
  @GeneratedValue
  private Integer  id;

  @ManyToMany(cascade = CascadeType.ALL)
  @Column(name="Authors")
  @JoinTable(name = "author_book", joinColumns =
    { @JoinColumn(name = "authors_id") },
    inverseJoinColumns = { @JoinColumn(name = "books_id") })
  private List<Author> authors;

    //getters-setters
}

@Entity
class Author{
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

        @ManyToMany(mappedBy = "authors",cascade = CascadeType.ALL)
    private List<Book> books;

  //getters-setters
}
</code>```

Function doing the desired behavior

```<code>public List<Book> getBooksByAuthorId(int authorId) {
        Session session = HibernateUtil.getSession();
        Criteria cr = session.createCriteria(Book.class, "book");
        cr.createAlias("book.authors", "authors");
        cr.createAlias("authors.id", "authid");
        cr.add(Restrictions.eq()) //edited after  initial post this line should be removed

        cr.add(Restrictions.eq("auth.id", authorId));
        List<Book> results = cr.list();
        session.close();
        return results;
    }
</code>```

答:
Please try :

I can suggest JPA Criteria API (differs with Hibernate Criteria API)
Hibernate Criteria API is considered as deprecated now.

To obtain list of books, associated with author by supplying author id:

```<code>    CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery cq = cb.createQuery();
    Root book = cq.from(Book.class);
    // // declaring parameter 'authorId'
    cq.where(cb.equal(book.get("id"), cb.parameter(Integer.class, "authorId"));
    Query query = em.createQuery(cq);
      // supplying parameter 'authorId' to query
    query.setParameter("authorId", id);
    List<Author> authors = query.getResultList();
</code>```

Body:
How do I do a query when I pass an integer, as an authorId, to find the books associated with that author? I tried one below gives me a 'not an association id'. What's the proper way of doing this?

Also, this many-to-many created a third table based on the annotations on  authors attribute from books.

Entity

@Entity
class Book{
  @Id
  @GeneratedValue
  private Integer  id;

  @ManyToMany(cascade = CascadeType.ALL)
  @Column(name="Authors")
  @JoinTable(name = "author_book", joinColumns =
    { @JoinColumn(name = "authors_id") },
    inverseJoinColumns = { @JoinColumn(name = "books_id") })
  private List<Author> authors;

    //getters-setters
}

@Entity
class Author{
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

        @ManyToMany(mappedBy = "authors",cascade = CascadeType.ALL)
    private List<Book> books;

  //getters-setters
}

Function doing the desired behavior

public List<Book> getBooksByAuthorId(int authorId) {
        Session session = HibernateUtil.getSession();
        Criteria cr = session.createCriteria(Book.class, "book");
        cr.createAlias("book.authors", "authors");
        cr.createAlias("authors.id", "authid");
        cr.add(Restrictions.eq()) //edited after  initial post this line should be removed

        cr.add(Restrictions.eq("auth.id", authorId));
        List<Book> results = cr.list();
        session.close();
        return results;
    }

Body:
Please try :

I can suggest JPA Criteria API (differs with Hibernate Criteria API)
Hibernate Criteria API is considered as deprecated now.

To obtain list of books, associated with author by supplying author id:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery cq = cb.createQuery();
    Root book = cq.from(Book.class);
    // // declaring parameter 'authorId'
    cq.where(cb.equal(book.get("id"), cb.parameter(Integer.class, "authorId"));
    Query query = em.createQuery(cq);
      // supplying parameter 'authorId' to query
    query.setParameter("authorId", id);
    List<Author> authors = query.getResultList();


问:
Android PagerAdapter IllegalStateException in FragmentActivity
I get the following error as below and I can't figure out why it is occurring. I don't have more information about the error.

I have an Android ListView with 50 items. When you click on an item, then open second screen (Fragment Activity with pager), this Fragment activity shows all items in a fragment from clicked item  in the ListView till the last item with left or right swipe possibility.

```<code>java.lang.IllegalStateException:
  at android.support.v4.view.ViewPager.populate(ViewPager.java:1167)
  at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5797)
  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5797)
  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5797)
  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2910)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2048)
  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1185)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1406)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1073)
  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5988)
  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
  at android.view.Choreographer.doCallbacks(Choreographer.java:580)
  at android.view.Choreographer.doFrame(Choreographer.java:550)
  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:5910)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
</code>```

答:
```<code>public class ScreenSlidePagerActivity extends FragmentActivity {
    /**
     * The number of pages (wizard steps) to show in this demo.
     */
    public static int NUM_PAGES = 50;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_slide);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);

    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() <= 0) {

           //start an intent
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            Bundle bundle = new Bundle();
            bundle.putSerializable("content", "bla bla content" );

            MyFragment fragmentObj= new MyFragment();
            fragmentObj.setArguments(bundle);
            return fragmentObj;
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }

    }

}
</code>```

Body:
I get the following error as below and I can't figure out why it is occurring. I don't have more information about the error.

I have an Android ListView with 50 items. When you click on an item, then open second screen (Fragment Activity with pager), this Fragment activity shows all items in a fragment from clicked item  in the ListView till the last item with left or right swipe possibility.

java.lang.IllegalStateException:
  at android.support.v4.view.ViewPager.populate(ViewPager.java:1167)
  at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5797)
  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5797)
  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5797)
  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2910)
  at android.view.View.measure(View.java:17951)
  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2048)
  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1185)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1406)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1073)
  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5988)
  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
  at android.view.Choreographer.doCallbacks(Choreographer.java:580)
  at android.view.Choreographer.doFrame(Choreographer.java:550)
  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:5910)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)


问:
Is there something like C#'s "see cref" in Python ReST docstrings?
I'm converting some C# code to Python 3, including documentation which is typically written as XML summaries in the original C# code.

Those summaries have references to class names as a <see cref="ClassName"/> element or <paramref name="fileName"/> elements for references to parameters, creating clickable links when converting it to HTML for example. I wonder if there's something similar in the Python ReST docstring format I use.

For example, let's take this C# method documentation:

```<code>/// <summary>
/// Reads and returns a <see cref="DummyFile"/> instance from the file with the
/// given <paramref name="fileName"/>.
/// </summary>
/// <param name="fileName">The name of the file to read the data from.</param>
/// <returns>The read <see cref="DummyFile"/> instance.</returns>
public DummyFile LoadDummyFile(string fileName)
{
    // Do some dummy file work.
}
</code>```

In Python, I'd convert this to:

```<code>"""
Reads and returns a DummyFile instance from the file with the given file_name.
:param file_name: The name of the file to read the data from.
:param str file_name: The name of the file to read the data from.
:return: The read DummyFile instance.
:rtype: DummyFile
"""
def load_dummy_file(file_name: str) -> DummyFile
    # Do some dummy file work.
</code>```

(Does anyone even use :rtype?)
As you can see, I simply entered the class name and parameter name as plain-text, not knowing if there is such special syntax to create clickable links out of it when creating web documentation later on.

Is it possible to create such class references in ReST docstrings, and if yes, what would be a possible (hopefully less lengthy than C#) syntax for them?

答:
For <see cref="ClassName"> you could use

:py:class:`ClassName`

This will become a clickable ref to the class definition. See Sphinx Domains.

I don't know any similar methode for the file_name. But for what you need a clickable link to a place tow lines below?

I use this rtype directive.

Body:
I'm converting some C# code to Python 3, including documentation which is typically written as XML summaries in the original C# code.

Those summaries have references to class names as a <see cref="ClassName"/> element or <paramref name="fileName"/> elements for references to parameters, creating clickable links when converting it to HTML for example. I wonder if there's something similar in the Python ReST docstring format I use.

For example, let's take this C# method documentation:

///
/// Reads and returns a <see cref="DummyFile"/> instance from the file with the
/// given <paramref name="fileName"/>.
///
/// <param name="fileName">The name of the file to read the data from.</param>
/// <returns>The read <see cref="DummyFile"/> instance.</returns>
public DummyFile LoadDummyFile(string fileName)
{
    // Do some dummy file work.
}

In Python, I'd convert this to:

"""
Reads and returns a DummyFile instance from the file with the given file_name.
:param file_name: The name of the file to read the data from.
:param str file_name: The name of the file to read the data from.
:return: The read DummyFile instance.
:rtype: DummyFile
"""
def load_dummy_file(file_name: str) -> DummyFile
    # Do some dummy file work.

(Does anyone even use :rtype?)
As you can see, I simply entered the class name and parameter name as plain-text, not knowing if there is such special syntax to create clickable links out of it when creating web documentation later on.

Is it possible to create such class references in ReST docstrings, and if yes, what would be a possible (hopefully less lengthy than C#) syntax for them?


问:
Trouble building a library
I am having a lot of trouble compiling a library. The library is ESFlib available on this page. It is dependent on the Mescach and Ckit libraries, both of which can be found on the previously linked webpage. I have no issues building the Ckit library, however I do encounter some issues with the Meschach library, which has some issues relating to a file named zmachine. Despite this I have managed to build a mesach.a library file using the rebuild.sh file. However, when I try to build the ESFlib file I get a internal compiler error.

I am using a virtual box machine with Ubuntu 64, if this is at all relevant.  I am quite new to this sort of stuff so any help would be much appreciated as the contents of this library would save me a lot of time !

Regards,
Stephen

Results of ./configure and make

```<code>./configure
"\n            Note: \n        configure can be run with the option --enable-SECOND_DERIVATIVES=t\n        to build the ESFLIB version which supports second derivatives.\n"
"\n            Note: \n        configure can be run with the option --enable-WRAP_AROUND=t\n        to build the ESFLIB version which supports the wrap-around \n        \(diffraction\) method of weight function smoothing at crack tips.\n"
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for library containing strerror... none required
checking whether ln -s works... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking minix/config.h usability... no
checking minix/config.h presence... no
checking for minix/config.h... no
checking whether it is safe to define __EXTENSIONS__... yes
checking for ranlib... ranlib
checking for gcc... yes
checking compile with prototypes... yes (gcc )
checking preprocessor... gcc  -E
checking for _get_list_next in -lckit... yes
checking ckitcfg.h usability... yes
checking ckitcfg.h presence... yes
checking for ckitcfg.h... yes
checking for LUfactor in -lmeschach... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/meschach.a... checking /home/stephen/Documents/ESFLib/src/../../Meschach/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/meschach.a... yes
checking matrix2.h usability... yes
checking matrix2.h presence... yes
checking for matrix2.h... yes
checking for unistd.h... (cached) yes
checking for ANSI C header files... (cached) yes
checking for an ANSI C-conforming const... yes
checking for random... yes
checking for rand... yes
checking for isnan... yes
configure: creating ./config.status
config.status: creating Makefile

make
arch=`./config.guess`; arch=`config.sub $arch`; \
if test "xx86_64-pc-linux-gnu" != "x$arch" ; then \
    make reconfigure; \
fi
/bin/sh: 1: config.sub: not found
make[1]: Entering directory '/home/stephen/Documents/ESFLib/src'
make clean; ./configure
make[2]: Entering directory '/home/stephen/Documents/ESFLib/src'
for n in 1 2 3 ; do \
        make SPDIM=$n ESFLIB_LANG="" clean_${n}d; \
        make SPDIM=$n ESFLIB_LANG=f  clean_${n}d; \
done
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[2]: Leaving directory '/home/stephen/Documents/ESFLib/src'
"\n            Note: \n        configure can be run with the option --enable-SECOND_DERIVATIVES=t\n        to build the ESFLIB version which supports second derivatives.\n"
"\n            Note: \n        configure can be run with the option --enable-WRAP_AROUND=t\n        to build the ESFLIB version which supports the wrap-around \n        \(diffraction\) method of weight function smoothing at crack tips.\n"
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for library containing strerror... none required
checking whether ln -s works... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking minix/config.h usability... no
checking minix/config.h presence... no
checking for minix/config.h... no
checking whether it is safe to define __EXTENSIONS__... yes
checking for ranlib... ranlib
checking for gcc... yes
checking compile with prototypes... yes (gcc )
checking preprocessor... gcc  -E
checking for _get_list_next in -lckit... yes
checking ckitcfg.h usability... yes
checking ckitcfg.h presence... yes
checking for ckitcfg.h... yes
checking for LUfactor in -lmeschach... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/meschach.a... checking /home/stephen/Documents/ESFLib/src/../../Meschach/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/meschach.a... yes
checking matrix2.h usability... yes
checking matrix2.h presence... yes
checking for matrix2.h... yes
checking for unistd.h... (cached) yes
checking for ANSI C header files... (cached) yes
checking for an ANSI C-conforming const... yes
checking for random... yes
checking for rand... yes
checking for isnan... yes
configure: creating ./config.status
config.status: creating Makefile
make[1]: Leaving directory '/home/stephen/Documents/ESFLib/src'
Removing dim dependent files
make SPDIM=1 make_1d
make[1]: Entering directory '/home/stephen/Documents/ESFLib/src'
Running make for dim=1
make[2]: Entering directory '/home/stephen/Documents/ESFLib/src'
Creating esflibtop.h from template
Creating esflib1.h
Compiling sf.c
In file included from sf.c:19:0:
esflibpriv.h:1:0: internal compiler error: Segmentation fault
 #ifndef ESFLIBPRIV_H
 ^
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-5/README.Bugs> for instructions.
Makefile:203: recipe for target 'sf.o' failed
make[2]: *** [sf.o] Error 1
make[2]: Leaving directory '/home/stephen/Documents/ESFLib/src'
Makefile:112: recipe for target 'make_c1d' failed
make[1]: *** [make_c1d] Error 2
make[1]: Leaving directory '/home/stephen/Documents/ESFLib/src'
Makefile:100: recipe for target '1d' failed
make: *** [1d] Error 2
</code>```

答: I have seen gcc crash when it has run out of memory - increase the memory on your virtualbox instance and try again.</p>

Title: Trouble building a library

Body:
I am having a lot of trouble compiling a library. The library is ESFlib available on this page. It is dependent on the Mescach and Ckit libraries, both of which can be found on the previously linked webpage. I have no issues building the Ckit library, however I do encounter some issues with the Meschach library, which has some issues relating to a file named zmachine. Despite this I have managed to build a mesach.a library file using the rebuild.sh file. However, when I try to build the ESFlib file I get a internal compiler error.

I am using a virtual box machine with Ubuntu 64, if this is at all relevant.  I am quite new to this sort of stuff so any help would be much appreciated as the contents of this library would save me a lot of time !

Regards,
Stephen

Results of ./configure and make

./configure
"\n            Note: \n        configure can be run with the option --enable-SECOND_DERIVATIVES=t\n        to build the ESFLIB version which supports second derivatives.\n"
"\n            Note: \n        configure can be run with the option --enable-WRAP_AROUND=t\n        to build the ESFLIB version which supports the wrap-around \n        \(diffraction\) method of weight function smoothing at crack tips.\n"
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for library containing strerror... none required
checking whether ln -s works... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking minix/config.h usability... no
checking minix/config.h presence... no
checking for minix/config.h... no
checking whether it is safe to define __EXTENSIONS__... yes
checking for ranlib... ranlib
checking for gcc... yes
checking compile with prototypes... yes (gcc )
checking preprocessor... gcc  -E
checking for _get_list_next in -lckit... yes
checking ckitcfg.h usability... yes
checking ckitcfg.h presence... yes
checking for ckitcfg.h... yes
checking for LUfactor in -lmeschach... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/meschach.a... checking /home/stephen/Documents/ESFLib/src/../../Meschach/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/meschach.a... yes
checking matrix2.h usability... yes
checking matrix2.h presence... yes
checking for matrix2.h... yes
checking for unistd.h... (cached) yes
checking for ANSI C header files... (cached) yes
checking for an ANSI C-conforming const... yes
checking for random... yes
checking for rand... yes
checking for isnan... yes
configure: creating ./config.status
config.status: creating Makefile

make
arch=`./config.guess`; arch=`config.sub $arch`; \
if test "xx86_64-pc-linux-gnu" != "x$arch" ; then \
    make reconfigure; \
fi
/bin/sh: 1: config.sub: not found
make[1]: Entering directory '/home/stephen/Documents/ESFLib/src'
make clean; ./configure
make[2]: Entering directory '/home/stephen/Documents/ESFLib/src'
for n in 1 2 3 ; do \
        make SPDIM=$n ESFLIB_LANG="" clean_${n}d; \
        make SPDIM=$n ESFLIB_LANG=f  clean_${n}d; \
done
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[3]: Entering directory '/home/stephen/Documents/ESFLib/src'
Cleaning build files
make[3]: Leaving directory '/home/stephen/Documents/ESFLib/src'
make[2]: Leaving directory '/home/stephen/Documents/ESFLib/src'
"\n            Note: \n        configure can be run with the option --enable-SECOND_DERIVATIVES=t\n        to build the ESFLIB version which supports second derivatives.\n"
"\n            Note: \n        configure can be run with the option --enable-WRAP_AROUND=t\n        to build the ESFLIB version which supports the wrap-around \n        \(diffraction\) method of weight function smoothing at crack tips.\n"
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for library containing strerror... none required
checking whether ln -s works... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking minix/config.h usability... no
checking minix/config.h presence... no
checking for minix/config.h... no
checking whether it is safe to define __EXTENSIONS__... yes
checking for ranlib... ranlib
checking for gcc... yes
checking compile with prototypes... yes (gcc )
checking preprocessor... gcc  -E
checking for _get_list_next in -lckit... yes
checking ckitcfg.h usability... yes
checking ckitcfg.h presence... yes
checking for ckitcfg.h... yes
checking for LUfactor in -lmeschach... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/x86_64-pc-linux-gnu/meschach.a... checking /home/stephen/Documents/ESFLib/src/../../Meschach/libmeschach.a... no
checking /home/stephen/Documents/ESFLib/src/../../Meschach/meschach.a... yes
checking matrix2.h usability... yes
checking matrix2.h presence... yes
checking for matrix2.h... yes
checking for unistd.h... (cached) yes
checking for ANSI C header files... (cached) yes
checking for an ANSI C-conforming const... yes
checking for random... yes
checking for rand... yes
checking for isnan... yes
configure: creating ./config.status
config.status: creating Makefile
make[1]: Leaving directory '/home/stephen/Documents/ESFLib/src'
Removing dim dependent files
make SPDIM=1 make_1d
make[1]: Entering directory '/home/stephen/Documents/ESFLib/src'
Running make for dim=1
make[2]: Entering directory '/home/stephen/Documents/ESFLib/src'
Creating esflibtop.h from template
Creating esflib1.h
Compiling sf.c
In file included from sf.c:19:0:
esflibpriv.h:1:0: internal compiler error: Segmentation fault
 #ifndef ESFLIBPRIV_H
 ^
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-5/README.Bugs> for instructions.
Makefile:203: recipe for target 'sf.o' failed
make[2]: *** [sf.o] Error 1
make[2]: Leaving directory '/home/stephen/Documents/ESFLib/src'
Makefile:112: recipe for target 'make_c1d' failed
make[1]: *** [make_c1d] Error 2
make[1]: Leaving directory '/home/stephen/Documents/ESFLib/src'
Makefile:100: recipe for target '1d' failed
make: *** [1d] Error 2


问:
Merge vectors with different length into a matrix one after the other
Let's assume that we have the following three vectors.

```<code>L = c("1", "3")
K = c("2", "9", "2:9")
S = c("7")
</code>```

Is there any way to combine them into a matrix that will look like the above ?

```<code>L    K    S
1    0    0
3    0    0
0    2    0
0    9    0
0    2:9  0
0    0    7
</code>```

Thank you.

答:
```<code>library(dplyr)

L = c("1", "3")
K = c("2", "9", "2:9")
S = c("7")

Ltable <- tibble(L=L)
Ktable <- tibble(K=K)
Stable <- tibble(S=S)
JoinedMatrix <- Ltable %>% bind_rows(Ktable) %>% bind_rows(Stable) %>% as.matrix()
JoinedMatrix[which(is.na(JoinedMatrix))] <- "0"
</code>```

bind_rows from dplyr allows you to bind dataframes (or tibbles) together. Since the three tibbles have differently named columns, they are kept as different columns after joining, filling the missing fields with NA. After that we simply replace all NAs with 0 and we're done.

```<code>> JoinedMatrix
     L   K     S
[1,] "1" "0"   "0"
[2,] "3" "0"   "0"
[3,] "0" "2"   "0"
[4,] "0" "9"   "0"
[5,] "0" "2:9" "0"
[6,] "0" "0"   "7"
</code>```

Body:
Let's assume that we have the following three vectors.

L = c("1", "3")
K = c("2", "9", "2:9")
S = c("7")

Is there any way to combine them into a matrix that will look like the above ?

L    K    S
1    0    0
3    0    0
0    2    0
0    9    0
0    2:9  0
0    0    7

Thank you.

Body:
library(dplyr)

L = c("1", "3")
K = c("2", "9", "2:9")
S = c("7")

Ltable <- tibble(L=L)
Ktable <- tibble(K=K)
Stable <- tibble(S=S)
JoinedMatrix <- Ltable %>% bind_rows(Ktable) %>% bind_rows(Stable) %>% as.matrix()
JoinedMatrix[which(is.na(JoinedMatrix))] <- "0"

bind_rows from dplyr allows you to bind dataframes (or tibbles) together. Since the three tibbles have differently named columns, they are kept as different columns after joining, filling the missing fields with NA. After that we simply replace all NAs with 0 and we're done.

> JoinedMatrix
     L   K     S
[1,] "1" "0"   "0"
[2,] "3" "0"   "0"
[3,] "0" "2"   "0"
[4,] "0" "9"   "0"
[5,] "0" "2:9" "0"
[6,] "0" "0"   "7"


问:
Not uploading pictures to Firebase storage
I want to upload pictures to storage. Every time I launch my emulator I get no errors and everything works perfectly except that when I select the pictures in my emulator and upload them it does not show in the Firebase Storage section even after I refresh. Here is my code:</p>

```<code>    package com.safariagaming;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.safariagaming.mtc_project.R;

public class Account_Page extends AppCompatActivity {

    private Button mSelectImage;

    private StorageReference mStorage;

    private static final int GALLERY_INTENT = 2;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account__page);

        mSelectImage = (Button) findViewById(R.id.selectImage_BUTTON);

        mStorage = FirebaseStorage.getInstance().getReference(); //.child at end ifyou want to add an child to it

        mProgressDialog = new ProgressDialog(this);

        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(Intent.ACTION_PICK);

                intent.setType("image/*");

                startActivityForResult(intent, GALLERY_INTENT);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){

            mProgressDialog.setMessage("Uploading...");

            Uri uri = data.getData();

            StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());

            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Toast.makeText(Account_Page.this, "Upload Done", Toast.LENGTH_LONG).show();

                mProgressDialog.dismiss();
                }//you can also add onFaliure listener
            });

        }

    }
}
</code>```

答:
This is how i uploaded a image to storage</p>

```<code>FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl(FILE_STORAGE_PATH);
InputStream stream = null;
try {
    stream = new FileInputStream(new File(uri.getLastPathSegment()));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
StorageReference photoRef = storageRef.child("Photos/" + image_name + ".jpg");
        UploadTask uploadTask = photoRef.putStream(stream);
        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Log.d(TAG, "Success TO UPLOAD IMAGE");

            }
        }).addOnFailureListener(WorkCompletionActivity.this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                //Failure
            }
        });
</code>```

Body:
I want to upload pictures to storage. Every time I launch my emulator I get no errors and everything works perfectly except that when I select the pictures in my emulator and upload them it does not show in the Firebase Storage section even after I refresh. Here is my code:

    package com.safariagaming;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.safariagaming.mtc_project.R;

public class Account_Page extends AppCompatActivity {

    private Button mSelectImage;

    private StorageReference mStorage;

    private static final int GALLERY_INTENT = 2;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account__page);

        mSelectImage = (Button) findViewById(R.id.selectImage_BUTTON);

        mStorage = FirebaseStorage.getInstance().getReference(); //.child at end ifyou want to add an child to it

        mProgressDialog = new ProgressDialog(this);

        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(Intent.ACTION_PICK);

                intent.setType("image/*");

                startActivityForResult(intent, GALLERY_INTENT);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){

            mProgressDialog.setMessage("Uploading...");

            Uri uri = data.getData();

            StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());

            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Toast.makeText(Account_Page.this, "Upload Done", Toast.LENGTH_LONG).show();

                mProgressDialog.dismiss();
                }//you can also add onFaliure listener
            });

        }

    }
}

Body:
This is how i uploaded a image to storage

FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl(FILE_STORAGE_PATH);
InputStream stream = null;
try {
    stream = new FileInputStream(new File(uri.getLastPathSegment()));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
StorageReference photoRef = storageRef.child("Photos/" + image_name + ".jpg");
        UploadTask uploadTask = photoRef.putStream(stream);
        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Log.d(TAG, "Success TO UPLOAD IMAGE");

            }
        }).addOnFailureListener(WorkCompletionActivity.this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                //Failure
            }
        });


问:
Restrict access to apache 2.4 directory but allow certain files
I have an apache 2.4 server which is hosting 2 applications. One of which is freely accessible to the internet and the other is restricted to certain IPs. So within my /etc/apache2.conf file I have the following:

```<code><Directory /var/www/>
   Options FollowSymLinks
   AllowOverride None
   Require all granted
</Directory>

<Directory /var/other/>
   Options FollowSymLinks
   AllowOverride None
   Require ip [ip]
</Directory>
</code>```

This works fine and I get a 403 forbidden when trying to access any page being served from /var/other unless im on the right IP. However, I would now like to make certain pages within the /var/other/ directory freely accessible without the IP restriction. I have tried various combinations such as the following which has a nested <Files> tag to grant all access to a specific file but doesnt seem to work.

```<code><Directory /var/www/>
   Options FollowSymLinks
   AllowOverride None
   Require all granted
</Directory>

<Directory /var/other/>
   Options FollowSymLinks
   AllowOverride None
   Require ip [ip]
   <Files "/var/other/page.php">
      Require all granted
   </Files>
</Directory>
</code>```

Ive tried putting the <Files> tag before the "Require ip [ip]" as well as before and after the <Directory> tag but also dont seem to work. Does anyone know if this is possible and how I would go about implementing it?

答:
You should not have the directory, just the filename, in the Files section:</p>

```<code>   <Files "page.php">
</code>```

Body:
I have an apache 2.4 server which is hosting 2 applications. One of which is freely accessible to the internet and the other is restricted to certain IPs. So within my /etc/apache2.conf file I have the following:

<Directory /var/www/>
   Options FollowSymLinks
   AllowOverride None
   Require all granted
</Directory>

<Directory /var/other/>
   Options FollowSymLinks
   AllowOverride None
   Require ip [ip]
</Directory>

This works fine and I get a 403 forbidden when trying to access any page being served from /var/other unless im on the right IP. However, I would now like to make certain pages within the /var/other/ directory freely accessible without the IP restriction. I have tried various combinations such as the following which has a nested <Files> tag to grant all access to a specific file but doesnt seem to work.

<Directory /var/www/>
   Options FollowSymLinks
   AllowOverride None
   Require all granted
</Directory>

<Directory /var/other/>
   Options FollowSymLinks
   AllowOverride None
   Require ip [ip]
   <Files "/var/other/page.php">
      Require all granted
   </Files>
</Directory>

Ive tried putting the <Files> tag before the "Require ip [ip]" as well as before and after the <Directory> tag but also dont seem to work. Does anyone know if this is possible and how I would go about implementing it?

Body:
You should not have the directory, just the filename, in the Files section:

   <Files "page.php">


问:
What are some of Drupal's shortcomings?
Drupal is very much a "Do Everything" CMS. There are modules that allow you to add almost any functionality, which is great. However, it feels like a lot of the features (v5 and v6) seem scattered around and unintuitive for the user. As a developer, I'm left with the feeling of having patched a site together using bubble gum and string.

For example, to add text to the default search box (that disappears when clicked), you have to either add some jQuery code OR override the theme. I've also found the menu system more complicated than it should be.

Am I the only one with this opinion? What things (if any) would you change about Drupal's core?

答: It has a seemingly bad security record: http://secunia.com/advisories/search/?search=Drupal</p>

OwnerDisplayName: Matt

Title: What are some of Drupal's shortcomings?

LastEditorDisplayName: Matt

OwnerDisplayName: stesch

LastEditorDisplayName: stesch


问:
How does ::selection's specificity work against type selectors?
Some questions about using CSS to specify the color of selected text:

Imagine that a rule like the following exists in the default CSS that's implemented by the browser:

```<code>::selection { background-color: Highlight; color: HighlightText; }
</code>```

Further imagine that a rule like the following is defined in any site-specific authored stylesheet:

```<code>body { background-color: white }
</code>```

Given these rules, what would the background-color of the selected body text be? Would it be white, or Highlight?

Perhaps the rule in the author stylesheet should override the default rule: because according to specificity, body is just as specific as ::selection and is specified later (and should therefore override the previous entry).

On the other hand, that would result in text being invisible when it's selected (because if Highlight is blue and HighlightText is white so that selected text is white-on-blue, then overriding the background-color of selected text so that it's white would result in its being white-on-white).

Assuming that the behaviour in step 2 is undesirable, how to avoid it?

Say that it's a bug in the user stylesheet, which shouldn't ever specify background-color without also specifying color?

Say that body isn't a match for selected body text except when the ::selection pseudo-element is specified as part of the selector?

答:
Why was it removed?

Well that would be a question you would have to ask of the W3C committee that removed it from the draft. My understanding is there has been a lot of internal turmoil within the W3C community since they began writing the HTML5 and CSS3 drafts. Certain individuals that run projects developing the browsers (and I wont go into names) wanted it done one way, and developers be damned. The developer community wanted it done another way, and so began feud over who should control the W3C.

Given these rules, what would the background color of selected body text be: would it be white, or Highlight?

Sarfraz hit it on the head here, the :selection pseudo-class will only effect selected text. So in your example when you highlight something the background color changes to Highlight, when it is unselected it returns to white.

I haven't tested this particular example but here is what I understand of it

ContentLicense: CC BY-SA 4.0

Body:
Some questions about using CSS to specify the color of selected text:

Imagine that a rule like the following exists in the default CSS that's implemented by the browser:

::selection { background-color: Highlight; color: HighlightText; }

Further imagine that a rule like the following is defined in any site-specific authored stylesheet:

body { background-color: white }

Given these rules, what would the background-color of the selected body text be? Would it be white, or Highlight?

Perhaps the rule in the author stylesheet should override the default rule: because according to specificity, body is just as specific as ::selection and is specified later (and should therefore override the previous entry).

On the other hand, that would result in text being invisible when it's selected (because if Highlight is blue and HighlightText is white so that selected text is white-on-blue, then overriding the background-color of selected text so that it's white would result in its being white-on-white).

Assuming that the behaviour in step 2 is undesirable, how to avoid it?

Say that it's a bug in the user stylesheet, which shouldn't ever specify background-color without also specifying color?

Say that body isn't a match for selected body text except when the ::selection pseudo-element is specified as part of the selector?


问:
How to separate words from a row individually using php and mysql
I have a mysql database with a table called keywords -- see below

**** As you can see the row has more than one word listed inside.

MY QUESTION
Is there a way to separate each word on it's own using mysql and php. Right now it combines all the words as one instead of individually.

The picture below is showing you words but one button may contain 3 or more words.

I need for the words to be unique and on their own. Can this be done in MYSQL? If so can you please provide the php coding, thank you.

答:
the best choice is to use explode function ,
the link below is the reference of explode in php website :
http://php.net/manual/en/function.explode.php</p>


问:
SELECT * INTO another database on a different SQL instance running older SQL Server
I need to copy some tables from a SQL Server 2016 instance to a SQL Server 2008 instance like

```<code>select *
into [sql8].[DatabaseA].[dbo].[Customers]
from [DatabaseA].[dbo].[Customers]
</code>```

but I get an error:

Msg 117, Level 15, State 1, Line 9

  The object name 'sql8.DatabaseA.dbo.Customers' contains more than the maximum number of prefixes. The maximum is 2.

I have tried generating a script of the data but my machine runs out of memory during SQLCMD execution from the command line.

Looking for recommendations / pointer.

Thanks

答:
I'm guessing you may need to set up the sql8 server as a linked server from the Server holding the DB you're trying to get the data into. In the image I would be trying to get the data into a db on the MJAYWCO1 server.  [sql8] would be the server you want to create a link "to".  "[sql8].[DatabaseA].[dbo].[Customers]"

To Do this from the ssms GUI goto Server.ServerObjects.LinkedServers:

Another possibility:  Have you tried to import it directly to the new DB?  Assuming you can connect to the old database from the new database with creds...

If this doesn't work, you can use the Export Data from the DB you are trying to get the data (under Import data in the second Image) from the "old DB" to create an XML or .CSV file, or whatever might be an applicable format.  Use this and the Import Wizard from the "new DB"

Please forgive me if I misunderstood the question as English is my first language and I went to government schools.

Body:
I need to copy some tables from a SQL Server 2016 instance to a SQL Server 2008 instance like

select *
into [sql8].[DatabaseA].[dbo].[Customers]
from [DatabaseA].[dbo].[Customers]

but I get an error:

Msg 117, Level 15, State 1, Line 9

  The object name 'sql8.DatabaseA.dbo.Customers' contains more than the maximum number of prefixes. The maximum is 2.

I have tried generating a script of the data but my machine runs out of memory during SQLCMD execution from the command line.

Looking for recommendations / pointer.

Thanks


问:
Devise_token_auth and Devise login with username and email
I continuously get errors when trying to add token authentication to my existing rails application and it's stemming from the devise authentication_keys. In my rails 4 app I allow users to login with either a username or email and I'd like to provide the same functionality for the API.

The error I'm getting when logging in from the API is as follows

```<code>Started POST "/api/v1/auth/sign_in" for 127.0.0.1 at 2016-04-19 23:40:26 -0400
Processing by DeviseTokenAuth::SessionsController#create as JSON
Parameters: {"login"=>"email@example.com", "password"=>"[FILTERED]", "session"=>{"login"=>"email@example.com", "password"=>"[FILTERED]"}}
Can't verify CSRF token authenticity
Geokit is using the domain: localhost
User Load (1.3ms)  SELECT  "users".* FROM "users" WHERE (login = 'email@example.com' AND provider='email')  ORDER BY "users"."id" ASC LIMIT 1
SQLite3::SQLException: no such column: login: SELECT  "users".* FROM "users" WHERE (login = 'email@example.com' AND provider='email')  ORDER BY "users"."id" ASC LIMIT 1
Completed 500 Internal Server Error in 5ms

SQLite3::SQLException - no such column: login:
</code>```

The code for the user model is below. The problem is stemming from the User load as it is not converting the login parameter to search via the email (or username). But the code below works totally fine for regular devise logins.

```<code>#User.rb
devise :database_authenticatable, :registerable, :confirmable,
     :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
include DeviseTokenAuth::Concerns::User

def self.find_for_database_authentication(warden_conditions)
  conditions = warden_conditions.dup
  if login = conditions.delete(:login)
    where(conditions.to_h).where(['lower(username) = :value OR lower(email) = :value', { :value => login.downcase }]).first
  else
    where(conditions.to_h).first
  end
end
</code>```

Thanks for any help or guidance!

EDIT
When sending the params as email and password there is also an error.

```<code>Processing by DeviseTokenAuth::SessionsController#create as JSON
Parameters: {"email"=>"email@example.com", "password"=>"[FILTERED]", "session"=>{"email"=>"email@example.com", "password"=>"[FILTERED]"}}
Can't verify CSRF token authenticity
Unpermitted parameters: email, format, session
Completed 401 Unauthorized in 49ms (Views: 0.3ms | ActiveRecord: 0.0ms | Solr: 0.0ms)
</code>```

答:
From the Devise doc, you need to do the following:

app/models/user.rb

```<code>attr_accessor :login
</code>```

config/initializers/devise.rb

```<code>Devise.setup do |config|
   config.authentication_keys = [:login]
   config.case_insensitive_keys = [:login]
end
</code>```

devise_token_auth is unmaintained (cf unmerged PR) and therefore out-of-sync with Devise, which is why you need to override SessionsController:

config/routes.rb

```<code>Rails.application.routes.draw do
  namespace :api do
    scope module: :v4  do
      mount_devise_token_auth_for "User", at: "auth", controllers: {
        sessions: "api/v4/devise_token_auth/sessions"
      }
    end
  end
end
</code>```

app/controllers/api/v4/devise_token_auth/sessions_controller.rb

```<code>module Api
  module V4
    module DeviseTokenAuth
      class SessionsController < ::DeviseTokenAuth::SessionsController
        def create
          # Check
          field = (resource_params.keys.map(&:to_sym) & resource_class.authentication_keys).first

          @resource = nil
          if field
            q_value = resource_params[field]

            if resource_class.case_insensitive_keys.include?(field)
              q_value.downcase!
            end

            q = "#{field.to_s} = ? AND provider='email'"

            if ActiveRecord::Base.connection.adapter_name.downcase.starts_with? "mysql"
              q = "BINARY " + q
            end

            # LOG IN BY EMAIL AND USERNAME
            if field == :login
              @resource = resource_class.where("email = ? OR username = ?", q_value, q_value).first
            else
              @resource = resource_class.where(q, q_value).first
            end
            # LOG IN BY EMAIL AND USERNAME END
          end

          if @resource && valid_params?(field, q_value) && (!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?)
            valid_password = @resource.valid_password?(resource_params[:password])
            if (@resource.respond_to?(:valid_for_authentication?) && !@resource.valid_for_authentication? { valid_password }) || !valid_password
              render_create_error_bad_credentials
              return
            end
            # create client id
            @client_id = SecureRandom.urlsafe_base64(nil, false)
            @token     = SecureRandom.urlsafe_base64(nil, false)

            @resource.tokens[@client_id] = {
              token: BCrypt::Password.create(@token),
              expiry: (Time.now + ::DeviseTokenAuth.token_lifespan).to_i
            }
            @resource.save

            sign_in(:user, @resource, store: false, bypass: false)

            yield @resource if block_given?

            render_create_success
          elsif @resource && !(!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?)
            render_create_error_not_confirmed
          else
            render_create_error_bad_credentials
          end
        end
      end
    end
  end
end
</code>```

Test example

```<code>resource "User sign in" do

  let(:user) { build(:user) }

  before(:each) do
    user.create_new_auth_token
  end

  post "/api/auth/sign_in" do
    parameter :email, "Email address"
    parameter :password, "Password for user"

    it "fails with incorrect login and password" do
      do_request(login: "user.does.not@exist.com", password: "wrong_password")
      expect(status).to eq(401)
      expect(JSON.parse(response_body)["errors"])
        .to include("Invalid login credentials. Please try again.")
    end

    it "logs in with correct username and password" do
      user.save!
      do_request(login: user.username, password: user.password)
      expect(status).to eq(200)
      expect(JSON.parse(response_body)["data"]["email"]).to include(user.email)
    end

    it "logs in with correct email and password" do
      user.save!
      do_request(login: user.email, password: user.password)
      expect(status).to eq(200)
      expect(JSON.parse(response_body)["data"]["email"]).to include(user.email)
    end
  end
end
</code>```

Body:
I continuously get errors when trying to add token authentication to my existing rails application and it's stemming from the devise authentication_keys. In my rails 4 app I allow users to login with either a username or email and I'd like to provide the same functionality for the API.

The error I'm getting when logging in from the API is as follows

Started POST "/api/v1/auth/sign_in" for 127.0.0.1 at 2016-04-19 23:40:26 -0400
Processing by DeviseTokenAuth::SessionsController#create as JSON
Parameters: {"login"=>"email@example.com", "password"=>"[FILTERED]", "session"=>{"login"=>"email@example.com", "password"=>"[FILTERED]"}}
Can't verify CSRF token authenticity
Geokit is using the domain: localhost
User Load (1.3ms)  SELECT  "users".* FROM "users" WHERE (login = 'email@example.com' AND provider='email')  ORDER BY "users"."id" ASC LIMIT 1
SQLite3::SQLException: no such column: login: SELECT  "users".* FROM "users" WHERE (login = 'email@example.com' AND provider='email')  ORDER BY "users"."id" ASC LIMIT 1
Completed 500 Internal Server Error in 5ms

SQLite3::SQLException - no such column: login:

The code for the user model is below. The problem is stemming from the User load as it is not converting the login parameter to search via the email (or username). But the code below works totally fine for regular devise logins.

#User.rb
devise :database_authenticatable, :registerable, :confirmable,
     :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
include DeviseTokenAuth::Concerns::User

def self.find_for_database_authentication(warden_conditions)
  conditions = warden_conditions.dup
  if login = conditions.delete(:login)
    where(conditions.to_h).where(['lower(username) = :value OR lower(email) = :value', { :value => login.downcase }]).first
  else
    where(conditions.to_h).first
  end
end

Thanks for any help or guidance!

EDIT
When sending the params as email and password there is also an error.

Processing by DeviseTokenAuth::SessionsController#create as JSON
Parameters: {"email"=>"email@example.com", "password"=>"[FILTERED]", "session"=>{"email"=>"email@example.com", "password"=>"[FILTERED]"}}
Can't verify CSRF token authenticity
Unpermitted parameters: email, format, session
Completed 401 Unauthorized in 49ms (Views: 0.3ms | ActiveRecord: 0.0ms | Solr: 0.0ms)

Body:
From the Devise doc, you need to do the following:

app/models/user.rb

attr_accessor :login

config/initializers/devise.rb

Devise.setup do |config|
   config.authentication_keys = [:login]
   config.case_insensitive_keys = [:login]
end

devise_token_auth is unmaintained (cf unmerged PR) and therefore out-of-sync with Devise, which is why you need to override SessionsController:

config/routes.rb

Rails.application.routes.draw do
  namespace :api do
    scope module: :v4  do
      mount_devise_token_auth_for "User", at: "auth", controllers: {
        sessions: "api/v4/devise_token_auth/sessions"
      }
    end
  end
end

app/controllers/api/v4/devise_token_auth/sessions_controller.rb

module Api
  module V4
    module DeviseTokenAuth
      class SessionsController < ::DeviseTokenAuth::SessionsController
        def create
          # Check
          field = (resource_params.keys.map(&:to_sym) & resource_class.authentication_keys).first

          @resource = nil
          if field
            q_value = resource_params[field]

            if resource_class.case_insensitive_keys.include?(field)
              q_value.downcase!
            end

            q = "#{field.to_s} = ? AND provider='email'"

            if ActiveRecord::Base.connection.adapter_name.downcase.starts_with? "mysql"
              q = "BINARY " + q
            end

            # LOG IN BY EMAIL AND USERNAME
            if field == :login
              @resource = resource_class.where("email = ? OR username = ?", q_value, q_value).first
            else
              @resource = resource_class.where(q, q_value).first
            end
            # LOG IN BY EMAIL AND USERNAME END
          end

          if @resource && valid_params?(field, q_value) && (!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?)
            valid_password = @resource.valid_password?(resource_params[:password])
            if (@resource.respond_to?(:valid_for_authentication?) && !@resource.valid_for_authentication? { valid_password }) || !valid_password
              render_create_error_bad_credentials
              return
            end
            # create client id
            @client_id = SecureRandom.urlsafe_base64(nil, false)
            @token     = SecureRandom.urlsafe_base64(nil, false)

            @resource.tokens[@client_id] = {
              token: BCrypt::Password.create(@token),
              expiry: (Time.now + ::DeviseTokenAuth.token_lifespan).to_i
            }
            @resource.save

            sign_in(:user, @resource, store: false, bypass: false)

            yield @resource if block_given?

            render_create_success
          elsif @resource && !(!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?)
            render_create_error_not_confirmed
          else
            render_create_error_bad_credentials
          end
        end
      end
    end
  end
end

Test example

resource "User sign in" do

  let(:user) { build(:user) }

  before(:each) do
    user.create_new_auth_token
  end

  post "/api/auth/sign_in" do
    parameter :email, "Email address"
    parameter :password, "Password for user"

    it "fails with incorrect login and password" do
      do_request(login: "user.does.not@exist.com", password: "wrong_password")
      expect(status).to eq(401)
      expect(JSON.parse(response_body)["errors"])
        .to include("Invalid login credentials. Please try again.")
    end

    it "logs in with correct username and password" do
      user.save!
      do_request(login: user.username, password: user.password)
      expect(status).to eq(200)
      expect(JSON.parse(response_body)["data"]["email"]).to include(user.email)
    end

    it "logs in with correct email and password" do
      user.save!
      do_request(login: user.email, password: user.password)
      expect(status).to eq(200)
      expect(JSON.parse(response_body)["data"]["email"]).to include(user.email)
    end
  end
end


问:
Htc Vive + leap motion as controller
I'm trying to implement a feature similar to HTC Vive's controller with the leap motion on my Unity project. I wanted to generate a laser pointer from the index finger and teleport the Vive's room on the position of the laser (as it's done with the controller). The problem is the latest leap motion (orion) documentation, it's unclear. Any ideas how to do that? More in general, we thought about using HandController but we don't understand where to add the script component.
Thanks!</p>

答:
It's unclear to me whether the problem you're having is getting hand data in your scene at all, or using that hand data.

If you're just trying to get hand data in your scene, you can copy a prefab from one of the Unity SDK's example scenes. If you're trying to integrate Leap into an existing scene that already has a VR rig set up, check out the documentation on the core Leap components to understand what pieces need to be in place for you to start getting Hand data. LeapServiceProvider has to be somewhere in your scene to receive hand data.

As long as you have a LeapServiceProvider somewhere, you can access hands from the Leap Motion from any script, anywhere. So for getting a ray from the index fingertip, just pop this script any old place:

```<code>using Leap;
using Leap.Unity;
using UnityEngine;

public class IndexRay : MonoBehaviour {
  void Update() {
    Hand rightHand = Hands.Right;
    Vector3 indexTipPosition = rightHand.Fingers[1].TipPosition.ToVector3();
    Vector3 indexTipDirection = rightHand.Fingers[1].bones[3].Direction.ToVector3();
    // You can try using other bones in the index finger for direction as well;
    // bones[3] is the last bone; bones[1] is the bone extending from the knuckle;
    // bones[0] is the index metacarpal bone.

    Debug.DrawRay(indexTipPosition, indexTipDirection, Color.cyan);
  }
}
</code>```

For what it's worth, the index fingertip direction is probably not going to be stable enough to do what you want. A more reliable strategy is to cast a line from the camera (or a theoretical "shoulder position" at a constant offset from the camera) through the index knuckle bone of the hand:

```<code>using Leap;
using Leap.Unity;
using UnityEngine;

public class ProjectiveRay : MonoBehaviour {

  // To find an approximate shoulder, let's try 12 cm right, 15 cm down, and 4 cm back relative to the camera.
  [Tooltip("An approximation for the shoulder position relative to the VR camera in the camera's (non-scaled) local space.")]
  public Vector3 cameraShoulderOffset = new Vector3(0.12F, -0.15F, -0.04F);

  public Transform shoulderTransform;

  void Update() {
    Hand rightHand = Hands.Right;
    Vector3 cameraPosition = Camera.main.transform.position;
    Vector3 shoulderPosition = cameraPosition + Camera.main.transform.rotation * cameraShoulderOffset;

    Vector3 indexKnucklePosition = rightHand.Fingers[1].bones[1].PrevJoint.ToVector3();
    Vector3 dirFromShoulder = (indexKnucklePosition - shoulderPosition).normalized;

    Debug.DrawRay(indexKnucklePosition, dirFromShoulder, Color.white);

    Debug.DrawLine(shoulderPosition, indexKnucklePosition, Color.red);
  }
}
</code>```

Title: Htc Vive + leap motion as controller

Body:
It's unclear to me whether the problem you're having is getting hand data in your scene at all, or using that hand data.

If you're just trying to get hand data in your scene, you can copy a prefab from one of the Unity SDK's example scenes. If you're trying to integrate Leap into an existing scene that already has a VR rig set up, check out the documentation on the core Leap components to understand what pieces need to be in place for you to start getting Hand data. LeapServiceProvider has to be somewhere in your scene to receive hand data.

As long as you have a LeapServiceProvider somewhere, you can access hands from the Leap Motion from any script, anywhere. So for getting a ray from the index fingertip, just pop this script any old place:

using Leap;
using Leap.Unity;
using UnityEngine;

public class IndexRay : MonoBehaviour {
  void Update() {
    Hand rightHand = Hands.Right;
    Vector3 indexTipPosition = rightHand.Fingers[1].TipPosition.ToVector3();
    Vector3 indexTipDirection = rightHand.Fingers[1].bones[3].Direction.ToVector3();
    // You can try using other bones in the index finger for direction as well;
    // bones[3] is the last bone; bones[1] is the bone extending from the knuckle;
    // bones[0] is the index metacarpal bone.

    Debug.DrawRay(indexTipPosition, indexTipDirection, Color.cyan);
  }
}

For what it's worth, the index fingertip direction is probably not going to be stable enough to do what you want. A more reliable strategy is to cast a line from the camera (or a theoretical "shoulder position" at a constant offset from the camera) through the index knuckle bone of the hand:

using Leap;
using Leap.Unity;
using UnityEngine;

public class ProjectiveRay : MonoBehaviour {

  // To find an approximate shoulder, let's try 12 cm right, 15 cm down, and 4 cm back relative to the camera.
  [Tooltip("An approximation for the shoulder position relative to the VR camera in the camera's (non-scaled) local space.")]
  public Vector3 cameraShoulderOffset = new Vector3(0.12F, -0.15F, -0.04F);

  public Transform shoulderTransform;

  void Update() {
    Hand rightHand = Hands.Right;
    Vector3 cameraPosition = Camera.main.transform.position;
    Vector3 shoulderPosition = cameraPosition + Camera.main.transform.rotation * cameraShoulderOffset;

    Vector3 indexKnucklePosition = rightHand.Fingers[1].bones[1].PrevJoint.ToVector3();
    Vector3 dirFromShoulder = (indexKnucklePosition - shoulderPosition).normalized;

    Debug.DrawRay(indexKnucklePosition, dirFromShoulder, Color.white);

    Debug.DrawLine(shoulderPosition, indexKnucklePosition, Color.red);
  }
}


问:
How can I download curses python3.4?
I've installed pip and updated it to the latest version however when I type "pip install curses" into the command prompt I get an reply stating "Could not find a version that satisfies the requirement curses (from versions: )
No matching distribution found for curses"

Can anyone help me please?

答:
```<code>pip install http://www.lfd.uci.edu/~gohlke/pythonlibs/vu4hx7yr/curses-2.2-cp34-none-win_amd64.whl
</code>```

See http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses for other versions. Heed the warning: «Unicode characters are not supported.»

Title: How can I download curses python3.4?

Body:
pip install http://www.lfd.uci.edu/~gohlke/pythonlibs/vu4hx7yr/curses-2.2-cp34-none-win_amd64.whl

See http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses for other versions. Heed the warning: «Unicode characters are not supported.»


问:
Why am I getting an is not defined error?
I'm trying to make a program that allows two people to play tic tac toe. They should select a row and then a column, then the token should be placed in that location. I'm new to multidimensional lists and i'm struggling a bit. This is what I have so far:

```<code>def showBoard():
    board = [[0,0,0,],
             [0,0,0],
             [0,0,0]]

    print("-------------")
    print('|',board[0][0], '|',board[0][1], '|',board[0][2],'|')
    print("|---+---+---|")
    print ('|',board[1][0], '|',board[1][1], '|',board[1][2],'|')
    print("|---+---+---|")
    print ('|',board[2][0], '|',board[2][1], '|',board[2][2],'|')
    print("-------------")

def playerX():

    row = input("Enter a row (0, 1, or 2) for player X: ")
    column = input("Enter a column (0 , 1, or 2) for player X: ")
    board[row][column] = "X"

def main():

    showBoard()
    playerX()

main()
</code>```

But then it always throws the error builtins.NameError: name 'board' is not defined.
Can I do it using similar code to what I have? Or will I need to use the append() somehow?

答:
Your problem is you're defining board inside drawBoard, then trying to use it in playerX. Variables defined inside a scope (like a function) can't be used outside of that scope. If you need to use the variable elsewhere, define it globally, or better yet, pass it in as an argument:

```<code>def newBoard():
    # Create a new board, then return it
    #  so it can be used elsewhere.
    return [[0,0,0],
            [0,0,0],
            [0,0,0]]

def showBoard(board):
    print("-------------")
    print('|',board[0][0], '|',board[0][1], '|',board[0][2],'|')
    print("|---+---+---|")
    print ('|',board[1][0], '|',board[1][1], '|',board[1][2],'|')
    print("|---+---+---|")
    print ('|',board[2][0], '|',board[2][1], '|',board[2][2],'|')
    print("-------------")

def playerX(board):
    row = int(input("Enter a row (0, 1, or 2) for player X: "))
    column = int(input("Enter a column (0 , 1, or 2) for player X: "))

    board[row][column] = "X"

def main():
    board = newBoard()

    showBoard(board)
    playerX(board)

main()
</code>```

What I changed:

I created a newBoard function that creates a new board. I then used it in main to create a board.

I made drawBoard and playerX accept the board as arguments. I then passed the board I created in main into each.

I made it so inputs are converted to numbers before they're used for indexing.

Body:
I'm trying to make a program that allows two people to play tic tac toe. They should select a row and then a column, then the token should be placed in that location. I'm new to multidimensional lists and i'm struggling a bit. This is what I have so far:

def showBoard():
    board = [[0,0,0,],
             [0,0,0],
             [0,0,0]]

    print("-------------")
    print('|',board[0][0], '|',board[0][1], '|',board[0][2],'|')
    print("|---+---+---|")
    print ('|',board[1][0], '|',board[1][1], '|',board[1][2],'|')
    print("|---+---+---|")
    print ('|',board[2][0], '|',board[2][1], '|',board[2][2],'|')
    print("-------------")

def playerX():

    row = input("Enter a row (0, 1, or 2) for player X: ")
    column = input("Enter a column (0 , 1, or 2) for player X: ")
    board[row][column] = "X"

def main():

    showBoard()
    playerX()

main()

But then it always throws the error builtins.NameError: name 'board' is not defined.
Can I do it using similar code to what I have? Or will I need to use the append() somehow?

Body:
Your problem is you're defining board inside drawBoard, then trying to use it in playerX. Variables defined inside a scope (like a function) can't be used outside of that scope. If you need to use the variable elsewhere, define it globally, or better yet, pass it in as an argument:

def newBoard():
    # Create a new board, then return it
    #  so it can be used elsewhere.
    return [[0,0,0],
            [0,0,0],
            [0,0,0]]

def showBoard(board):
    print("-------------")
    print('|',board[0][0], '|',board[0][1], '|',board[0][2],'|')
    print("|---+---+---|")
    print ('|',board[1][0], '|',board[1][1], '|',board[1][2],'|')
    print("|---+---+---|")
    print ('|',board[2][0], '|',board[2][1], '|',board[2][2],'|')
    print("-------------")

def playerX(board):
    row = int(input("Enter a row (0, 1, or 2) for player X: "))
    column = int(input("Enter a column (0 , 1, or 2) for player X: "))

    board[row][column] = "X"

def main():
    board = newBoard()

    showBoard(board)
    playerX(board)

main()

What I changed:

I created a newBoard function that creates a new board. I then used it in main to create a board.

I made drawBoard and playerX accept the board as arguments. I then passed the board I created in main into each.

I made it so inputs are converted to numbers before they're used for indexing.


问:
ignore_const_cols missing values
In the h2o models that have the "ignore_const_cols" parameter, how is "constant" determined with respect to missing values?

i.e if a column has only one unique non-missing value and also some missing values, and "ignore_const_cols" is selected, will no splits occur on this column to separate the missing values from the one constant value?

答:
It's easy enough to test this

R code:

```<code>library(h2o)
h2o.init()
iris_data<-as.data.frame(iris)
iris_data$Petal.Width<-1
iris_data[iris_data$Species=='setosa','Petal.Width']<-NA
iris_h2o<-as.h2o(iris_data)
h2o.gbm(training_frame=iris_h2o,y='Species')
iris_data$Petal.Width<-as.factor(iris_data$Petal.Width)
iris_h2o<-as.h2o(iris_data)
h2o.gbm(training_frame=iris_h2o,y='Species')
</code>```

Regardless of if the constant column with missing values is numeric or factor, the same warning is given:

```<code>Warning message:
In .h2o.startModelJob(algo, params, h2oRestApiVersion) :
  Dropping constant columns: [Petal.Width].
</code>```

Therefore the answer to your question appears to be that h2o ignores missing values when determining if a column is constant

Title: ignore_const_cols missing values

Body:
It's easy enough to test this

R code:

library(h2o)
h2o.init()
iris_data<-as.data.frame(iris)
iris_data$Petal.Width<-1
iris_data[iris_data$Species=='setosa','Petal.Width']<-NA
iris_h2o<-as.h2o(iris_data)
h2o.gbm(training_frame=iris_h2o,y='Species')
iris_data$Petal.Width<-as.factor(iris_data$Petal.Width)
iris_h2o<-as.h2o(iris_data)
h2o.gbm(training_frame=iris_h2o,y='Species')

Regardless of if the constant column with missing values is numeric or factor, the same warning is given:

Warning message:
In .h2o.startModelJob(algo, params, h2oRestApiVersion) :
  Dropping constant columns: [Petal.Width].

Therefore the answer to your question appears to be that h2o ignores missing values when determining if a column is constant


问:
Dropdown List is not Updating the Selected Value (SemanticUI)
I am using SemanticUI for a dropdown list

```<code><div class="ui dropdown">
  <input type="hidden" name="gender">
  <i class="dropdown icon"></i>
  <div class="default text">Gender</div>
  <div class="menu">
    <div class="item" data-value="male">Male</div>
    <div class="item" data-value="female">Female</div>
  </div>
</div>
</code>```

in the bottom of my page, I am initializing it as

```<code>jQuery(document).ready(function($) {
    $('.ui.dropdown')
  .dropdown()
;
});
</code>```

The problem is that when a user selects an item, it does not update and it keeps showing the default value as selected.
But when I go to Chrome Console and execute the above code JQuery(document)..., then it works fine.

I am assuming it is due to that the initialization needs to execute after page loads completely. So, What I did is the following instead of the above:

```<code>window.addEventListener("load", function(){
jQuery(document).ready(function($) {

    $('.ui.dropdown')
  .dropdown()
;
});
});;
</code>```

It worked. Dropdown list updates selection immediatly. However, when I click on Submit, I and page reloads, the selection is lost.
The drop down is being used as a filter to table. Having the selection gets lost on submit, makes filter unusable.

What is the best way to go around this.

答:
  <select>
    <option value="male">Male</option>
    <option value="female">Female</option>
</select>```

no extra js, css required,

edit: autocomplete attribute is not required because it is the default

Body:
I am using SemanticUI for a dropdown list

  <input type="hidden" name="gender">

Gender

Male

Female

in the bottom of my page, I am initializing it as

jQuery(document).ready(function($) {
    $('.ui.dropdown')
  .dropdown()
;
});

The problem is that when a user selects an item, it does not update and it keeps showing the default value as selected.
But when I go to Chrome Console and execute the above code JQuery(document)..., then it works fine.

I am assuming it is due to that the initialization needs to execute after page loads completely. So, What I did is the following instead of the above:

window.addEventListener("load", function(){
jQuery(document).ready(function($) {

    $('.ui.dropdown')
  .dropdown()
;
});
});;

It worked. Dropdown list updates selection immediatly. However, when I click on Submit, I and page reloads, the selection is lost.
The drop down is being used as a filter to table. Having the selection gets lost on submit, makes filter unusable.

What is the best way to go around this.

Body:
  <select>
    <option value="male">Male</option>
    <option value="female">Female</option>
</select>

no extra js, css required,

edit: autocomplete attribute is not required because it is the default


问:
How to write the result of a function in a slice
In the example, everything works fine. But they do not use the variable a and immediately display it https://play.golang.org/p/O0XwtQJRej

But I have a problem:

```<code>package main
import (
    "fmt"
    "strings"
)

func main() {
    str := "fulltext"
    var slice []string
    slice = strings.Split(str , "")

    fmt.Printf("anwer: ", slice)
}
</code>```

Whence in the answer there are superfluous characters, for example

%! (EXTRA [] string =

P.S. I know that I need to use append to add elements to the slice, but now I do not understand how to apply append here.

UP:
Now I have the answer:

anwer: %!(EXTRA []string=[f u l l t e x t])

But I need just:

[f u l l t e x t]

But I do not understand how I should change my code?

答:
Give to printf the expected format, in most cases, %v is fine.

```<code>package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "fulltext"
    var slice []string
    slice = strings.Split(str, "")

    fmt.Printf("anwer: %v", slice)
}
</code>```

see https://golang.org/pkg/fmt/ for more info.

Body:
In the example, everything works fine. But they do not use the variable a and immediately display it https://play.golang.org/p/O0XwtQJRej

But I have a problem:

package main
import (
    "fmt"
    "strings"
)

func main() {
    str := "fulltext"
    var slice []string
    slice = strings.Split(str , "")

    fmt.Printf("anwer: ", slice)
}

Whence in the answer there are superfluous characters, for example

%! (EXTRA [] string =

P.S. I know that I need to use append to add elements to the slice, but now I do not understand how to apply append here.

UP:
Now I have the answer:

anwer: %!(EXTRA []string=[f u l l t e x t])

But I need just:

[f u l l t e x t]

But I do not understand how I should change my code?

Body:
Give to printf the expected format, in most cases, %v is fine.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "fulltext"
    var slice []string
    slice = strings.Split(str, "")

    fmt.Printf("anwer: %v", slice)
}

see https://golang.org/pkg/fmt/ for more info.