问:
Swift 4 program showing data after downloading images but data is not related
I am making a swift app where i am downloading data from API. which gives a JSON.And from there i am putting image url in an imageArray and movieTiteUrl in movieTitleArray. but when i am showing them to collection view they are showing data but that data is not related. To download images i am using AlamofireImage Below code will help you to understand my problem better.

inside ViewDidLoad

```<code>var imageUrlArray = [String]()
var imageArray = [UIImage]()
var movieTitleArray = [String]()
</code>```

UICollectionViewDelegate

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCell", for: indexPath) as? MovieCell else { return UICollectionViewCell() }
    cell.movieName.image = imageArray[indexPath.row]
    cell.movieNameLbl.text = movieTitleArray[indexPath.row]

    return cell
}
</code>```

An extension which download data and download images

```<code>func downloadImages(handler: @escaping (_ status: Bool)-> ()){
    imageArray = []
    movieTitleArray = []
    for url in imageUrlArray{
        Alamofire.request(url).responseImage(completionHandler: { (response) in
            guard let image = response.result.value else { return }
            self.imageArray.append(image)

            if self.imageArray.count == self.imageUrlArray.count {
                handler(true)
            }

        })
    }
}

func retriveData(handler : @escaping (_ status: Bool) -> ()){
    print(getPopularMovies(pageNumber: 1))
    Alamofire.request(getPopularMovies(pageNumber: 1)).responseJSON { (response) in

        guard let json = response.result.value as? Dictionary<String, AnyObject> else { return }
        let dataDictArray = json["results"] as! [Dictionary<String, AnyObject>]

        for data in dataDictArray {

            guard let imageUrl = data["poster_path"] as? String else { return }
            guard let name = data["original_title"] as? String else { return }
            let updatedImageUrl = getFullImageUrl(imageUrl: imageUrl)
            self.imageUrlArray.append(updatedImageUrl)
            self.movieTitleArray.append(name)

        }
        handler(true)
    }
}

func updateDataToCollectionView(){
    retriveData{(finished) in
        if finished{
            self.downloadImages(handler: { (finishedDownloadingImage) in
                if finishedDownloadingImage{
                    self.movieCollectionView.reloadData()
                }
            })
        }
    }
}
</code>```

答:
I have found two observation ( problems ).

As you are using Async request to download the images, it is not guaranteed that you will get the response in the requested order. for example, if you request movie1Image,movie2Image....it is not guarntee that first you will receive movie1Image and the movie2Image in the same order. So definitely it is not reliable. use Dictionary to solve this. [String:Data] string -> ImageUrl, Data -> ImageData

Why did you wait till all images get downloaded? any specific scenario or any business requirement. Ideally, for a greater User Experience and for interaction, it is not recommended to wait till all the images get downloaded.

Body:
I am making a swift app where i am downloading data from API. which gives a JSON.And from there i am putting image url in an imageArray and movieTiteUrl in movieTitleArray. but when i am showing them to collection view they are showing data but that data is not related. To download images i am using AlamofireImage Below code will help you to understand my problem better.

inside ViewDidLoad

var imageUrlArray = [String]()
var imageArray = [UIImage]()
var movieTitleArray = [String]()

UICollectionViewDelegate

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCell", for: indexPath) as? MovieCell else { return UICollectionViewCell() }
    cell.movieName.image = imageArray[indexPath.row]
    cell.movieNameLbl.text = movieTitleArray[indexPath.row]

    return cell
}

An extension which download data and download images

func downloadImages(handler: @escaping (_ status: Bool)-> ()){
    imageArray = []
    movieTitleArray = []
    for url in imageUrlArray{
        Alamofire.request(url).responseImage(completionHandler: { (response) in
            guard let image = response.result.value else { return }
            self.imageArray.append(image)

            if self.imageArray.count == self.imageUrlArray.count {
                handler(true)
            }

        })
    }
}

func retriveData(handler : @escaping (_ status: Bool) -> ()){
    print(getPopularMovies(pageNumber: 1))
    Alamofire.request(getPopularMovies(pageNumber: 1)).responseJSON { (response) in

        guard let json = response.result.value as? Dictionary<String, AnyObject> else { return }
        let dataDictArray = json["results"] as! [Dictionary<String, AnyObject>]

        for data in dataDictArray {

            guard let imageUrl = data["poster_path"] as? String else { return }
            guard let name = data["original_title"] as? String else { return }
            let updatedImageUrl = getFullImageUrl(imageUrl: imageUrl)
            self.imageUrlArray.append(updatedImageUrl)
            self.movieTitleArray.append(name)

        }
        handler(true)
    }
}

func updateDataToCollectionView(){
    retriveData{(finished) in
        if finished{
            self.downloadImages(handler: { (finishedDownloadingImage) in
                if finishedDownloadingImage{
                    self.movieCollectionView.reloadData()
                }
            })
        }
    }
}


来源: stackexchange

问:
Currying for templates in C++ metaprogramming
This is more of a conceptual question. I'm trying to find the easiest way of converting a two-arg template (the arguments being types) into a one-arg template. I.e., binding one of the types.

This would be the meta-programming equivalent of bind in boost/std. My example includes a possible use-case, which is, passing std::is_same as template argument to a template that takes a one-arg template template argument (std::is_same being a two-arg template), i.e. to TypeList::FindIf. The TypeList is not fully implemented here, neither is FindIf, but you get the idea. It takes a "unary predicate" and returns the type for which that predicate is true, or void if not such type.

I have 2 working variants but the first is not a one-liner and the 2nd uses a rather verbose BindFirst contraption, that would not work for non-type template arguments. Is there a simple way to write such a one-liner? I believe the procedure I'm looking for is called currying.

```<code>#include <iostream>

template<template<typename, typename> class Function, typename FirstArg>
struct BindFirst
{
    template<typename SecondArg>
    using Result = Function<FirstArg, SecondArg>;
};

//template<typename Type> using IsInt = BindFirst<_EqualTypes, int>::Result<Type>;
template<typename Type> using IsInt = std::is_same<int, Type>;

struct TypeList
{
    template<template<typename> class Predicate>
    struct FindIf
    {
        // this needs to be implemented, return void for now
        typedef void Result;
    };
};

int main()
{

  static_assert(IsInt<int>::value, "");
  static_assert(!IsInt<float>::value, "");

  // variant #1: using the predefined parameterized type alias as predicate
  typedef TypeList::FindIf<IsInt>::Result Result1;

  // variant #2: one-liner, using BindFirst and std::is_same directly
  typedef TypeList::FindIf< BindFirst<std::is_same, int>::Result>::Result Result2;

  // variant #3: one-liner, using currying?
  //typedef TypeList::FindIf<std::is_same<int, _>>::Result Result2;

  return 0;
}
</code>```

Click here for code in online compiler GodBolt.

答:
Yeah, I had this issue to.  It took a few iterations to figure out a decent way to do this.  Basically, to do this, we need to specify a reasonable representation of what we want and need.  I borrowed some aspects from std::bind() in that I want to specify the template that I wish to bind and the parameters that I want to bind to it.  Then, within that type, there should be a template that will allow you to pass a set of types.

So our interface will look like this:

```<code>template <template <typename...> class OP, typename...Ts>
struct tbind;
</code>```

Now our implementation will have those parameters plus a container of types that will be applied at the end:

```<code>template <template <typename...> class OP, typename PARAMS, typename...Ts>
struct tbind_impl;
</code>```

Our base case will give us a template type, which I'll call ttype, that'll return a template of the contained types:

```<code>template <template <typename...> class OP, typename...Ss>
struct tbind_impl<OP, std::tuple<Ss...>>
{
    template<typename...Us>
    using ttype = OP<Ss...>;
};
</code>```

Then we have the case of moving the next type into the container and having ttype refer to the ttype in the slightly simpler base case:

```<code>template <template <typename...> class OP, typename T, typename...Ts, typename...Ss>
struct tbind_impl<OP, std::tuple<Ss...>, T, Ts...>
{
    template<typename...Us>
    using ttype = typename tbind_impl<
          OP
        , std::tuple<Ss..., T>
        , Ts...
    >::template ttype<Us...>;
};
</code>```

And finally, we need a remap of the templates that will be passed to ttype:

```<code>template <template <typename...> class OP, size_t I, typename...Ts, typename...Ss>
struct tbind_impl<OP, std::tuple<Ss...>, std::integral_constant<size_t, I>, Ts...>
{
    template<typename...Us>
    using ttype = typename tbind_impl<
          OP
        , typename std::tuple<
              Ss...
            , typename std::tuple_element<
                  I
                , typename std::tuple<Us...>
              >::type
          >
        , Ts...
    >::template ttype<Us...>;
</code>```

Now, since programmers are lazy, and don't want to type std::integral_constant<size_t, N> for each parameter to remap, we specify some aliases:

```<code>using t0 = std::integral_constant<size_t, 0>;
using t1 = std::integral_constant<size_t, 1>;
using t2 = std::integral_constant<size_t, 2>;
...
</code>```

Oh, almost forgot the implementation of our interface:

```<code>template <template <typename...> class OP, typename...Ts>
struct tbind : detail::tbind_impl<OP, std::tuple<>, Ts...>
{};
</code>```

Note that tbind_impl was placed in a detail namespace.

And voila, tbind!

Unfortunately, there is a defect prior to c++17. If you pass tbind<parms>::ttype to a template that expects a template with a particular number of parameters, you will get an error as the number of parameters don't match (specific number doesn't match any number).  This complicates things slightly requiring an additional level of indirection. :(

```<code>template <template <typename...> class OP, size_t N>
struct any_to_specific;

template <template <typename...> class OP>
struct any_to_specific<OP, 1>
{
    template <typename T0>
    using ttype = OP<T0>;
};

template <template <typename...> class OP>
struct any_to_specific<OP, 2>
{
    template <typename T0, typename T1>
    using ttype = OP<T0, T1>;
};
...
</code>```

Using that to wrap tbind will force the compiler to recognize the template having the specified number of parameters.

Example usage:

```<code>static_assert(!tbind<std::is_same, float, t0>::ttype<int>::value, "failed");

static_assert( tbind<std::is_same, int  , t0>::ttype<int>::value, "failed");

static_assert(!any_to_specific<
      tbind<std::is_same, float, t0>::ttype
    , 1
>::ttype<int>::value, "failed");

static_assert( any_to_specific<
      tbind<std::is_same, int  , t0>::ttype
    , 1
 >::ttype<int>::value, "failed");
</code>```

All of which succeed.

ContentLicense: CC BY-SA 3.0

Body:
This is more of a conceptual question. I'm trying to find the easiest way of converting a two-arg template (the arguments being types) into a one-arg template. I.e., binding one of the types.

This would be the meta-programming equivalent of bind in boost/std. My example includes a possible use-case, which is, passing std::is_same as template argument to a template that takes a one-arg template template argument (std::is_same being a two-arg template), i.e. to TypeList::FindIf. The TypeList is not fully implemented here, neither is FindIf, but you get the idea. It takes a "unary predicate" and returns the type for which that predicate is true, or void if not such type.

I have 2 working variants but the first is not a one-liner and the 2nd uses a rather verbose BindFirst contraption, that would not work for non-type template arguments. Is there a simple way to write such a one-liner? I believe the procedure I'm looking for is called currying.

#include <iostream>

template<template<typename, typename> class Function, typename FirstArg>
struct BindFirst
{
    template<typename SecondArg>
    using Result = Function<FirstArg, SecondArg>;
};

//template<typename Type> using IsInt = BindFirst<_EqualTypes, int>::Result<Type>;
template<typename Type> using IsInt = std::is_same<int, Type>;

struct TypeList
{
    template<template<typename> class Predicate>
    struct FindIf
    {
        // this needs to be implemented, return void for now
        typedef void Result;
    };
};

int main()
{

  static_assert(IsInt<int>::value, "");
  static_assert(!IsInt<float>::value, "");

  // variant #1: using the predefined parameterized type alias as predicate
  typedef TypeList::FindIf<IsInt>::Result Result1;

  // variant #2: one-liner, using BindFirst and std::is_same directly
  typedef TypeList::FindIf< BindFirst<std::is_same, int>::Result>::Result Result2;

  // variant #3: one-liner, using currying?
  //typedef TypeList::FindIf<std::is_same<int, _>>::Result Result2;

  return 0;
}

Click here for code in online compiler GodBolt.

Body:
Yeah, I had this issue to.  It took a few iterations to figure out a decent way to do this.  Basically, to do this, we need to specify a reasonable representation of what we want and need.  I borrowed some aspects from std::bind() in that I want to specify the template that I wish to bind and the parameters that I want to bind to it.  Then, within that type, there should be a template that will allow you to pass a set of types.

So our interface will look like this:

template <template <typename...> class OP, typename...Ts>
struct tbind;

Now our implementation will have those parameters plus a container of types that will be applied at the end:

template <template <typename...> class OP, typename PARAMS, typename...Ts>
struct tbind_impl;

Our base case will give us a template type, which I'll call ttype, that'll return a template of the contained types:

template <template <typename...> class OP, typename...Ss>
struct tbind_impl<OP, std::tuple<Ss...>>
{
    template<typename...Us>
    using ttype = OP<Ss...>;
};

Then we have the case of moving the next type into the container and having ttype refer to the ttype in the slightly simpler base case:

template <template <typename...> class OP, typename T, typename...Ts, typename...Ss>
struct tbind_impl<OP, std::tuple<Ss...>, T, Ts...>
{
    template<typename...Us>
    using ttype = typename tbind_impl<
          OP
        , std::tuple<Ss..., T>
        , Ts...
    >::template ttype<Us...>;
};

And finally, we need a remap of the templates that will be passed to ttype:

template <template <typename...> class OP, size_t I, typename...Ts, typename...Ss>
struct tbind_impl<OP, std::tuple<Ss...>, std::integral_constant<size_t, I>, Ts...>
{
    template<typename...Us>
    using ttype = typename tbind_impl<
          OP
        , typename std::tuple<
              Ss...
            , typename std::tuple_element<
                  I
                , typename std::tuple<Us...>
              >::type
          >
        , Ts...
    >::template ttype<Us...>;

Now, since programmers are lazy, and don't want to type std::integral_constant<size_t, N> for each parameter to remap, we specify some aliases:

using t0 = std::integral_constant<size_t, 0>;
using t1 = std::integral_constant<size_t, 1>;
using t2 = std::integral_constant<size_t, 2>;
...

Oh, almost forgot the implementation of our interface:

template <template <typename...> class OP, typename...Ts>
struct tbind : detail::tbind_impl<OP, std::tuple<>, Ts...>
{};

Note that tbind_impl was placed in a detail namespace.

And voila, tbind!

Unfortunately, there is a defect prior to c++17. If you pass tbind<parms>::ttype to a template that expects a template with a particular number of parameters, you will get an error as the number of parameters don't match (specific number doesn't match any number).  This complicates things slightly requiring an additional level of indirection. :(

template <template <typename...> class OP, size_t N>
struct any_to_specific;

template <template <typename...> class OP>
struct any_to_specific<OP, 1>
{
    template <typename T0>
    using ttype = OP<T0>;
};

template <template <typename...> class OP>
struct any_to_specific<OP, 2>
{
    template <typename T0, typename T1>
    using ttype = OP<T0, T1>;
};
...

Using that to wrap tbind will force the compiler to recognize the template having the specified number of parameters.

Example usage:

static_assert(!tbind<std::is_same, float, t0>::ttype<int>::value, "failed");

static_assert( tbind<std::is_same, int  , t0>::ttype<int>::value, "failed");

static_assert(!any_to_specific<
      tbind<std::is_same, float, t0>::ttype
    , 1
>::ttype<int>::value, "failed");

static_assert( any_to_specific<
      tbind<std::is_same, int  , t0>::ttype
    , 1
 >::ttype<int>::value, "failed");

All of which succeed.


问:
Picking a picture either from photos or multimedia, but not by recent images
I would like to pick picture similar to whatsapp:

Code:

```<code>   public void pickImage()
    {
        if (Build.VERSION.SDK_INT <19)
        {
            Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, KITKAT_SELECT_PICTURE);

        }
    }

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

        if (resultCode != Activity.RESULT_OK) return;
        if (null == data) return;
        Uri originalUri = null;
        if (requestCode == SELECT_PICTURE)
        {
            originalUri = data.getData();
        }
        else if (requestCode == KITKAT_SELECT_PICTURE)
        {
            originalUri = data.getData();
            final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
        }
    }
</code>```

Question:

The above can pick pictures and then showing pic properly in an imageview. However, during the picking process, it messes up the pictures photoed by camera (called album) and pictures in other media, and is sorted by most recent images.

How could i make it similar to whatsapp, picking image from a folder containing only but all images taken from camera, or a folder containing all other multimedia, INSTEAD OF messing up camera photos and mutimedia pictures by most recently added?

Thank you.

答: Use MediaStore.Images.Media.query function with order by set DSC DATE_ADDED field. You can set content URI for internal/external storage based on your requirement. </p>

Body:
I would like to pick picture similar to whatsapp:

Code:

   public void pickImage()
    {
        if (Build.VERSION.SDK_INT <19)
        {
            Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, KITKAT_SELECT_PICTURE);

        }
    }

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

        if (resultCode != Activity.RESULT_OK) return;
        if (null == data) return;
        Uri originalUri = null;
        if (requestCode == SELECT_PICTURE)
        {
            originalUri = data.getData();
        }
        else if (requestCode == KITKAT_SELECT_PICTURE)
        {
            originalUri = data.getData();
            final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
        }
    }

Question:

The above can pick pictures and then showing pic properly in an imageview. However, during the picking process, it messes up the pictures photoed by camera (called album) and pictures in other media, and is sorted by most recent images.

How could i make it similar to whatsapp, picking image from a folder containing only but all images taken from camera, or a folder containing all other multimedia, INSTEAD OF messing up camera photos and mutimedia pictures by most recently added?

Thank you.


问:
Is using the Boost Endian Arithmetic types considered good practice?
I'm fairly new at a company as embedded software engineer and I have to deal with networking quite a lot. I have to program in C++ all the time and using the code of my colleagues I noticed they use structs to build up packets to send over a network using TCP/UDP. For this, because the machines we are using are little-endian, everything has to be converted to big-endian. So the moment the data has to be sent they use the known functions as htons, ntohs, etc.

So I was looking up on how to make my code portable so the programmer does not have to care about the endianness of his machine and I stumbled upon the Endian Arithmetic types of the Boost library with which you, the programmer, can decide how your integer types are stored in memory. They seem very nice in the context I would use them but they are mentioned barely anywhere. Stackoverflow only has posts on how the endianness problem can not be handled in a proper way but these Arithmetic types seem like a nice portable solution to me. Why is it these types are barely mentioned anywhere and are never a proposed solution? Is there something wrong with them or are they just too new?

答:
It depends on where. Of course, using them throughout your whole codebase is a design trade-off.

The endian types are not a zero-cost abstraction. Using them for anything else than passive storage can hurt performance. (Imagine doing number crunching on non-native endian numbers. The processor could be spending more time dancing around with high-order/low-order bytes and words as needed than on the actual calculations).

If your application is typical, you will have POD transmission buffers that do not contain many "live" data elements, and the sheer benefit of automatic endianness conversions under the hood could well be worth any overhead.

I know about Boost Endian types and would prefer them over repeatedly writing ntoh and friends in a heartbeat.

In reality, though I've written generic serialization helpers (where the use of ntoh/hton is isolated to a handful primitive functions), or used existing libraries (such as protobuf). So the irony is that, me too, I haven't use Boost Endian extensively for any production code.

Perhaps this pattern goes for many developers, explaining not a lot of examples around Boost Endian?


问:
Clarification on Indexes
To illustrate my question, I will use the following example:

```<code>CREATE INDEX supplier_idx
  ON supplier (supplier_name);
</code>```

Will the searching on this table only be sped up if the supplier_name column is specified in the SELECT clause? What if we select the supplier_name column as well as other columns in the SELECT clause? Is searching sped up if this column is used in a WHERE clause, even if it is not in the SELECT clause?

Do the same rules apply to the following index as well:

```<code>CREATE INDEX supplier_idx
  ON supplier (supplier_name, city);
</code>```

答:
Indexes can be complex, so a full explanation would take a lot of writing.  There are many resources on the internet.  (Helpful link here to Oracle indexes)

However, I can just answer your questions simply.

```<code>CREATE INDEX supplier_idx
  ON supplier (supplier_name);
</code>```

This means that any joins (and similar) using the col supplier_name and using the col supplier_name in a WHERE clause will benefit from an index.

For example

```<code>SELECT * FROM SomeTable
WHERE supplier_name = 'Smith'
</code>```

But simply using the supplier_name column in a SELECT clause will not benefit from having an index (unless you add complexity to the SELECT clause, which I will cover...).  For example - this will not benefit from an Index on supplier_name

```<code>SELECT
supplier_name
FROM SomeTable WHERE ID = 1
</code>```

However, if you added some complexity to your SELECT statement, your index could indeed speed it up...For example:

```<code>SELECT
supplier_name   -- no index benefit
,(SELECT TOP 1 somedata FROM Table2 WHERE supplier_name = Table2.name) AS SomeValue
-- the line above uses the index as supplier_name is used in WHERE
, CASE WHEN supplier_name = 'Best Supplier'
  THEN 'Best'
  ELSE 'Worst'
  END AS FindBestSupplier
--  Also the CASE statement will use the index on supplier_name
FROM SomeTable WHERE ID = 1
</code>```

(The 'complexity' above still basically shows that if the field 'supplier_name' is used in CASE, or WHERE aswell as JOINS and aggregations, then the INDEX is very beneficial...This example above is a combination of many clauses wrapped into one SELECT statement)

But your composite index

```<code>CREATE INDEX supplier_idx
  ON supplier (supplier_name, city);
</code>```

would be beneficial in specific and important cases (Eg: where the city is in the SELECT clause and the supplier_name is used in the WHERE clause), for example

```<code>SELECT
city
FROM SomeTable WHERE supplier_name = 'Smith'
</code>```

The reason is that city is stored alongside the supplier_name index values, so when the index finds the supplier_name value, it immediately has a copy of the city value (stored in the index) and does not need to hit the database files to find any more data.  (If city was not in the index, it would have to hit the database to pull the city value out, as it does with most data required in the SELECT statement usually)

The joins will benefit from an index also, with the example:

```<code>SELECT
* FROM SomeTable T1
LEFT JOIN AnotherTable T2
ON T1.supplier_name = T2.supplier_name_2
AND T1.city = T2.city_2
</code>```

So in summary, if you use the field in any comparison expression like a WHERE clause or a JOIN , or a GROUP BY clause (and the aggregations SUM, MIN, MAX etc)...then an Index is very beneficial for Tables with over a few thousand rows...
(Usually only makes a big difference when you have at least 10,000 rows in a Table, but this can vary depending on your complexity)

SQL Server (for example) always creates any missing indexes that it needs (and then discards them)..So if you do not create the correct indexes manually - the system can slow down as it creates the missing indexes on the fly each time it needs them.  (SQL Server will show you hints on what indexes it thinks you need for a certain query)

Indexes can slow down UPDATES or INSERTS, so they must be used with a little wisdom and balance...(Sometimes indexes are deleted before a batch of UPDATEs is performed and then the index re-created again, although this is kinda extreme)

Title: Clarification on Indexes

Body:
To illustrate my question, I will use the following example:

CREATE INDEX supplier_idx
  ON supplier (supplier_name);

Will the searching on this table only be sped up if the supplier_name column is specified in the SELECT clause? What if we select the supplier_name column as well as other columns in the SELECT clause? Is searching sped up if this column is used in a WHERE clause, even if it is not in the SELECT clause?

Do the same rules apply to the following index as well:

CREATE INDEX supplier_idx
  ON supplier (supplier_name, city);

Body:
Indexes can be complex, so a full explanation would take a lot of writing.  There are many resources on the internet.  (Helpful link here to Oracle indexes)

However, I can just answer your questions simply.

CREATE INDEX supplier_idx
  ON supplier (supplier_name);

This means that any joins (and similar) using the col supplier_name and using the col supplier_name in a WHERE clause will benefit from an index.

For example

SELECT * FROM SomeTable
WHERE supplier_name = 'Smith'

But simply using the supplier_name column in a SELECT clause will not benefit from having an index (unless you add complexity to the SELECT clause, which I will cover...).  For example - this will not benefit from an Index on supplier_name

SELECT
supplier_name
FROM SomeTable WHERE ID = 1

However, if you added some complexity to your SELECT statement, your index could indeed speed it up...For example:

SELECT
supplier_name   -- no index benefit
,(SELECT TOP 1 somedata FROM Table2 WHERE supplier_name = Table2.name) AS SomeValue
-- the line above uses the index as supplier_name is used in WHERE
, CASE WHEN supplier_name = 'Best Supplier'
  THEN 'Best'
  ELSE 'Worst'
  END AS FindBestSupplier
--  Also the CASE statement will use the index on supplier_name
FROM SomeTable WHERE ID = 1

(The 'complexity' above still basically shows that if the field 'supplier_name' is used in CASE, or WHERE aswell as JOINS and aggregations, then the INDEX is very beneficial...This example above is a combination of many clauses wrapped into one SELECT statement)

But your composite index

CREATE INDEX supplier_idx
  ON supplier (supplier_name, city);

would be beneficial in specific and important cases (Eg: where the city is in the SELECT clause and the supplier_name is used in the WHERE clause), for example

SELECT
city
FROM SomeTable WHERE supplier_name = 'Smith'

The reason is that city is stored alongside the supplier_name index values, so when the index finds the supplier_name value, it immediately has a copy of the city value (stored in the index) and does not need to hit the database files to find any more data.  (If city was not in the index, it would have to hit the database to pull the city value out, as it does with most data required in the SELECT statement usually)

The joins will benefit from an index also, with the example:

SELECT
* FROM SomeTable T1
LEFT JOIN AnotherTable T2
ON T1.supplier_name = T2.supplier_name_2
AND T1.city = T2.city_2

So in summary, if you use the field in any comparison expression like a WHERE clause or a JOIN , or a GROUP BY clause (and the aggregations SUM, MIN, MAX etc)...then an Index is very beneficial for Tables with over a few thousand rows...
(Usually only makes a big difference when you have at least 10,000 rows in a Table, but this can vary depending on your complexity)

SQL Server (for example) always creates any missing indexes that it needs (and then discards them)..So if you do not create the correct indexes manually - the system can slow down as it creates the missing indexes on the fly each time it needs them.  (SQL Server will show you hints on what indexes it thinks you need for a certain query)

Indexes can slow down UPDATES or INSERTS, so they must be used with a little wisdom and balance...(Sometimes indexes are deleted before a batch of UPDATEs is performed and then the index re-created again, although this is kinda extreme)


答:
You are close, yo can use ast.literal_eval to interpret the rest:

```<code>import ast
d = {}
with open("output.txt") as f:
   for line in f:
      d_line = line.rstrip('\n').split(':')
      d[int(d_line[0])] = ast.literal_eval(d_line[1])

print(d)
</code>```

Or in one line:

```<code>new_d = {int(key):ast.literal_eval(values) for key, values in [i.strip('\n').split(':') for i in open('output.txt')]}
</code>```

Title: Python: Reading in Dictionary from Textfile

Body:
I have an ugly problem I've come across. I'm being fed the following text file, which is output from another Python file. From that previous file, it's a dictionary that was spit out into this text file.

Text file (named 'output.txt'):

0:[([(11, 191), (11, 170), (14, 170), (11, 188)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]
90:[([(95, 170), (95, 2), (119, 2), (95, 146)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]
180:[([(182, 2), (182, 23), (179, 23), (182, 5)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]
270:[([(98, 23), (98, 191), (74, 191), (98, 47)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]

I'm fairly familiar with reading in text files, but this one has me stumped. The silly thing about this whole problem is that I actually need the file to be given to me in a dictionary format, so I'm basically just trying to read in the file as it was given to me. The problem is when reading it in, Python doesn't know it's a dictionary and instead gives me strings. Is there anyway to have the values of the dictionary read in as a list of lists instead of just a string (shown below)? Thanks very much!

d = {}
with open("output.txt") as f:
    for line in f:
        d_line = line.rstrip('\n').split(':')
        d[int(d_line[0])] = d_line[1]

print(d)

{0: '[([(11, 191), (11, 170), (14, 170), (11, 188)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]', 90: '[([(95, 170), (95, 2), (119, 2), (95, 146)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]', 180: '[([(182, 2), (182, 23), (179, 23), (182, 5)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]', 270: '[([(98, 23), (98, 191), (74, 191), (98, 47)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]'}

Body:
You are close, yo can use ast.literal_eval to interpret the rest:

import ast
d = {}
with open("output.txt") as f:
   for line in f:
      d_line = line.rstrip('\n').split(':')
      d[int(d_line[0])] = ast.literal_eval(d_line[1])

print(d)

Or in one line:

new_d = {int(key):ast.literal_eval(values) for key, values in [i.strip('\n').split(':') for i in open('output.txt')]}


问:
Plus between digits in order to make a true statement
I need to put pluses (+) between digits of a large number, and to move over the all options, in order to get a true expression or a true statement: (C#)

Example:

  if I have---> 130=1612345

  I need it to be---> 130=1+61+23+45

I tried it with arrays, fors, and so..

[I don't care about efficiency]

答:
This is not really a C# related question, but your looking for an algorithm. In your example the '1612345' contains 7 digits, this means that in between there are 6 places where a + can possibly be present. So for N digits, N-1 possible plusses, and to count them all you have 2^(N-1) possibilities.

So make a for loop which counts from 0 (no plusses) to 2^(N-1)-1 (all plusses present). For each plus to test if it is present you do a bit-test on the for-loop variable (each plus corresponds with a bit-position of the for-loop variable). Then you can check if the current combination gives a valid sum.


问:
Browserless JavaScript
I talked to the Team Lead at Snap-On Tools once, and she told they used an "implementation of JavaScript" for their server-side coding. It's been a while, but I was thinking, WTF is she talking about? Are there interpreters for JavaScript besides those implemented in browsers?

How can you create a program or code, especially server-side, using JavaScript that doesn't execute in the context of a browser? What the hell is server-side about JavaScript if it's not generating content after the browser has loaded it? Can "server-side" JavaScript generate content before the HTTP response is deliver—and if so, how does that work/is set up?

I have many issues with JavaScript, but first-class functions are so sexy. And JavaScript Object Notation is so pure; I couldn't imagine an easier way to define data structures. Plus, you can hack out some code pretty quickly with dynamic typing if you're not writing something that's mission critical.

As a side question, given the last paragraph, have any suggestions about a good language to learn (comments will suffice)?

答:
JavaScript does not have to be run in a browser if you use an ECMAScript engine. Actually, both SpiderMonkey and Rhino are ECMAScript engines.

Flash's ActionScript is another ECMAScript derived language that doesn't have to run in a browser.

Edit - Wow, a lot has changed in three years. For your server-side needs, I now recommend node.js.

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Title: Browserless JavaScript

LastEditorDisplayName: Chris

OwnerDisplayName: David Thomas Garcia

LastEditorDisplayName: David Thomas Garcia


问:
Apple Push Certificates
My app has 3 provisioning profiles:

Ios development

Beta

Release

First one is used for development, second for test flight and third for the app store.
Also there are 2 App IDs

com.sansasystem.dribble

com.sansasystem.dribble-dev

Ios development and Beta profiles both use com.sansasystem.dribble-dev.
I enabled push notifications capability and generated sandbox APNS certificate.
However, pushes do come when I sign the app with Ios Development profile, but don't when signed with Beta.
Is it something I did wrong?

答:
You need to compile the app and also use the same cert & prov-profile to sign with "com.sansasystem.dribble-dev" for the beta app.

The push notification and cert is tied to the single bundle ID and the app compiled and bundled profile. If you are looking in bundle settings for XCode project, do check that the Automatic provisioning is not selected. Mostly due to this the profile may get auto-generated and not with APNS.

Also, check the Beta Target "Capabilities" tab is enabled for Push notification button turned on.

Lastly, check the Profile used by the actual beta target. Go to Project Build Settings --> General tab --> in that there is a profile drop down and next to that the (i) button, click that and you will be able to read the profile details and info related to the prov-file used.

If that is not same as the one you have created then I suggest use the Manual signing way and untick the automatic provisioning profile check box to make life more specific to get the error.

Title: Apple Push Certificates


问:
Firebase Firestore - get synchronization status on Android
I had started using Firebase Firestore database in my Android app. The main usecase of Firestore implementation is to create a bunch of documents in offline mode and then upload them when the device gets online. The problem is that "device online time" is limited, thus I need to provide the synchronization status indicator to the user.</p>

答:
Response from Firebase Support

When you write to Firestore while using offline data, the listener will be triggered when the data is stored locally and then again when it is stored on the server as mentioned here. A probably solution could be to show the user the current status of the data or a percentage of the items that were pushed to the server.

It's not a straightforward solution, but it works.

```<code>firestore.collection(COLLECTION)
.whereEqualTo(KEY, VALUE) // select documents created by particular device
    .addSnapshotListener((querySnapshot, e) -> {
        if (e != null) {
            // ERROR
            return;
        }

        boolean fromCache = querySnapshot.getMetadata().isFromCache();
        if (!fromCache) {
            // SYNC DONE
        } else {
            int connectivityStatus = NetworkUtil.getConnectivityStatus(getApplicationContext());
            if (connectivityStatus == NetworkUtil.TYPE_NOT_CONNECTED) {
                // WAITING ON CONNECTION...
            } else {
                // SYNCING...
            }
        }

    });
</code>```

Body:
Response from Firebase Support

When you write to Firestore while using offline data, the listener will be triggered when the data is stored locally and then again when it is stored on the server as mentioned here. A probably solution could be to show the user the current status of the data or a percentage of the items that were pushed to the server.

It's not a straightforward solution, but it works.

firestore.collection(COLLECTION)
.whereEqualTo(KEY, VALUE) // select documents created by particular device
    .addSnapshotListener((querySnapshot, e) -> {
        if (e != null) {
            // ERROR
            return;
        }

        boolean fromCache = querySnapshot.getMetadata().isFromCache();
        if (!fromCache) {
            // SYNC DONE
        } else {
            int connectivityStatus = NetworkUtil.getConnectivityStatus(getApplicationContext());
            if (connectivityStatus == NetworkUtil.TYPE_NOT_CONNECTED) {
                // WAITING ON CONNECTION...
            } else {
                // SYNCING...
            }
        }

    });


问:
Send Email Intent
```<code>Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, "emailaddress@emailaddress.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));
</code>```

The above code opens a dialog showing the following apps:- Bluetooth, Google Docs, Yahoo Mail, Gmail, Orkut, Skype, etc.

Actually, I want to filter these list options. I want to show only email-related apps e.g. Gmail, and Yahoo Mail. How to do it?

I've seen such an example on the 'Android Market application.

Open the Android Market app

Open any application where the developer has specified his/her email address. (If you can't find such an app just open my app:- market://details?id=com.becomputer06.vehicle.diary.free, OR search by 'Vehicle Diary')

Scroll down to 'DEVELOPER'

Click on 'Send Email'

The dialog shows only email Apps e.g. Gmail, Yahoo Mail, etc. It does not show Bluetooth, Orkut, etc. What code produces such dialog?

答:
```<code>Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", email, null));
if (emailIntent.resolveActivity(context.getPackageManager()) != null) {
    context.startActivity(Intent.createChooser(emailIntent, "Send Email..."));
} else {
    Toast.makeText(context, "No apps can perform this action.", Toast.LENGTH_SHORT).show();
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Send Email Intent

Body:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, "emailaddress@emailaddress.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));

The above code opens a dialog showing the following apps:- Bluetooth, Google Docs, Yahoo Mail, Gmail, Orkut, Skype, etc.

Actually, I want to filter these list options. I want to show only email-related apps e.g. Gmail, and Yahoo Mail. How to do it?

I've seen such an example on the 'Android Market application.

Open the Android Market app

Open any application where the developer has specified his/her email address. (If you can't find such an app just open my app:- market://details?id=com.becomputer06.vehicle.diary.free, OR search by 'Vehicle Diary')

Scroll down to 'DEVELOPER'

Click on 'Send Email'

The dialog shows only email Apps e.g. Gmail, Yahoo Mail, etc. It does not show Bluetooth, Orkut, etc. What code produces such dialog?


问:
Removing Duplicate Rows in a google Spreadsheet from the end row
i find this code for remove duplicate row in google spraedsheet:
from this url:
https://developers.google.com/apps-script/articles/removing_duplicates

```<code>function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();
  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
</code>```

but this function start removing duplicate row from the first row, i want to start removing from the end row of sheet.
How can i do this?

答:
Try the JavaScript array reverse() method. It is used twice below:

```<code>function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();

  data.reverse(); //reverses the row order.

  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }

  newData.reverse(); // reverses your data back to its original order.

  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
</code>```

Please let me know if it works out.

Body:
i find this code for remove duplicate row in google spraedsheet:
from this url:
https://developers.google.com/apps-script/articles/removing_duplicates

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();
  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

but this function start removing duplicate row from the first row, i want to start removing from the end row of sheet.
How can i do this?

Body:
Try the JavaScript array reverse() method. It is used twice below:

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();

  data.reverse(); //reverses the row order.

  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }

  newData.reverse(); // reverses your data back to its original order.

  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

Please let me know if it works out.


问:
What is a possible alternative to these static variables?
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

```<code>class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}
</code>```

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

答:
Pass the instance of Game into the constructor of the other classes and save it in a local variable. That way you can access Game and all its members from almost anywhere, but still can have multiple instances of game.

You can automate that by using Dependency Injection.

In some situation thread-static variables are an alternative, but I don't think yours is one of those.

Body:
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).


问:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'payments' already exists (SQL: create table `payments`
When I migrate a table I see this error,

SQLSTATE[42S01]: Base table or view already exists: 1050 Table
  'payments' already exists (SQL: create table payments

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePaymentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('resnumber');
            $table->string('course_id')->default('vip');
            $table->string('price');
            $table->boolean('payment')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('payments');
    }
}
</code>```

Error

答: If you are on Laravel 5.5 you can do php artisan migrate:fresh. This command will drop all tables und then create them again. I hope it helps.

Body:
When I migrate a table I see this error,

SQLSTATE[42S01]: Base table or view already exists: 1050 Table
  'payments' already exists (SQL: create table payments

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePaymentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('resnumber');
            $table->string('course_id')->default('vip');
            $table->string('price');
            $table->boolean('payment')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('payments');
    }
}

Error


问:
How to use scientific notation in seaborn heatmap labels?
I'm trying to get a heatmap using seaborn in python. Unfortunately it is not using scientific notation even though the numbers are very large. I was wondering if there's any simple way to convert to scientific notation or any other reasonable format. Here's a piece of code that shows the problem:

```<code>import seaborn as sns
import numpy as np
C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
score = np.random.rand(len(g_vals), len(C_vals))
sns.heatmap(score, xticklabels=C_vals, yticklabels=g_vals)
</code>```

The resulting plot is the following

答:
The heatmap allows to create its labels from the input to the xticklabels/yticklabels command. Those are then put along the axes, so there is no numeric format to change their appearance.

An option is to format the labels prior to supplying them to the heatmap. To this end a matplotlib ScalarFormatter can be (mis)used, which allows to automatically generate a MathText string from a float number. The following would be an example:

```<code>import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
import numpy as np

C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
score = np.random.rand(len(g_vals),len(C_vals))

tick = ticker.ScalarFormatter(useOffset=False, useMathText=True)
tick.set_powerlimits((0,0))

tc = [u"${}$".format(tick.format_data(x)) for x in C_vals]
tg = [u"${}$".format(tick.format_data(x)) for x in g_vals]

sns.heatmap(score, xticklabels=tc, yticklabels=tg)

plt.show()
</code>```

Body:
I'm trying to get a heatmap using seaborn in python. Unfortunately it is not using scientific notation even though the numbers are very large. I was wondering if there's any simple way to convert to scientific notation or any other reasonable format. Here's a piece of code that shows the problem:

import seaborn as sns
import numpy as np
C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
score = np.random.rand(len(g_vals), len(C_vals))
sns.heatmap(score, xticklabels=C_vals, yticklabels=g_vals)

The resulting plot is the following

Body:
The heatmap allows to create its labels from the input to the xticklabels/yticklabels command. Those are then put along the axes, so there is no numeric format to change their appearance.

An option is to format the labels prior to supplying them to the heatmap. To this end a matplotlib ScalarFormatter can be (mis)used, which allows to automatically generate a MathText string from a float number. The following would be an example:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
import numpy as np

C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
score = np.random.rand(len(g_vals),len(C_vals))

tick = ticker.ScalarFormatter(useOffset=False, useMathText=True)
tick.set_powerlimits((0,0))

tc = [u"${}$".format(tick.format_data(x)) for x in C_vals]
tg = [u"${}$".format(tick.format_data(x)) for x in g_vals]

sns.heatmap(score, xticklabels=tc, yticklabels=tg)

plt.show()


问:
Dynamically alloc size of array based on user input in C
I'm new to C so I'm having a little trouble handling everything Java already did for me in the background.
Basically what I would like to achieve is this:

Declare an array of char with no specified size

Ask to the user a string in input (single word or phrase)

Set the previous array of char with size of the length of the input string (dynamically)

Put the inputed string inside the char array

I've tried using scanf but it doesn't seem to handle string as an array of char(?) so I'm not able to work on the variable
I've also read about malloc() functions which dynamically allocates space for an array so I could use it to set the size of the array as the strlen of the string and then put '\0' at the end (just like .asciiz in some assembly language) but I can't figure out how to correlate malloc and input string.
Any help would be appreciated!
Thanks for your attention

答:
C does not provide a way for you to create an array of unspecified size. Generally, to do this sort of thing, you must create an array of some size (e.g., using malloc) and start reading user input. If the user input continues too long, you increase the size of the array (using realloc) and continue reading.

Once you reach the end of whatever the user is inputting, then you can reduce the array to match the actual size (again using realloc) if desired.

A consequence of this is that you cannot read the user input in one go. You must write code that reads portions of specific size, either character-by-character or as many characters as fit in the array you have created so far.


答:
The solution to your problem might be redesign. There is something wrong when you need to

access the gui engine instance not only from the input example, but from tens of other places

This indicates lots of dependencies that might be just wrong.

Title: What is a possible alternative to these static variables?


问:
vuejs FormData doesn't send json
I'm not quite sure what's causing it, but I'm using nuxtjs and attempting to send username and password to my Go server in json form. This is my vue code:

```<code><template>
<div class="container">
  <h1>Login</h1>
   <div>
    <label for="username" >Username</label>
    <input class="input-block" type="text" v-model="username">
  </div>
  <div>
    <label for="password" >Password</label>
    <input class="input-block" type="password" v-model="password">
  </div>
  <div>
    <button v-on:click="login">Login</button>
  </div>
</div>
</template>

<script>
import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)

var loginURL = 'http://localhost:5000/login'

export default {
  data () {
    return {
      username: [],
      password: []
    }
  },
  methods: {
    login: function () {
      NProgress.start()
      var formData = new FormData()
      formData.append('username', this.username)
      formData.append('password', this.password)
      this.$http.post(loginURL, formData, {emulateJSON: true}).then(response => {
        console.log(response)
      }, response => {
        console.log(response)
      })
    }
  }
}
</script>
</code>```

I have also tried to remove {emulateJSON: true} but the result is the same.

The server Go code looks like this:

```<code>func LoginPOST(w http.ResponseWriter, r *http.Request) {
  var loginForm struct {
    Username string `json:"username"`
    Password string `json:"password"`
  }
  body, err := ioutil.ReadAll(r.Body)
  if err != nil {
    // return 422
    return
  }
  fmt.Println("body string:", string(body))
  err = json.Unmarshal(body, &loginForm)
  if err != nil {
    fmt.Println(err)
    // return 422
    return
  }
  ...
}
</code>```

The json.Unmarshal error will print: invalid character '-' in numeric literal, and that's because the r.Body is:

```<code>body string: -----------------------------10632500131211292840295750524
Content-Disposition: form-data; name="username"

MYUSERNAME
-----------------------------10632500131211292840295750524
Content-Disposition: form-data; name="password"

MYPASSWORD
-----------------------------10632500131211292840295750524--
</code>```

I'm quite sure the Go code is correct, but I can't figure out why vue-resource sends the FormData in that way. I'd appreciate if someone could show how to send json and nothing else in the request

答:
```<code>NProgress.start()
      var formData = {
        username: this.username,
        password: this.password
      }
      this.$http.post(loginURL, formData).then(response => {
        console.log(response)
      }, response => {
        console.log(response)
      })
</code>```

A regualr formdata object from the browser is never json encoded as far as i know. So just define a json object and everything should be fine.

Title: vuejs FormData doesn't send json

Body:
I'm not quite sure what's causing it, but I'm using nuxtjs and attempting to send username and password to my Go server in json form. This is my vue code:

<template>

Login

    Username
    <input class="input-block" type="text" v-model="username">

    Password
    <input class="input-block" type="password" v-model="password">

    <button v-on:click="login">Login</button>

</template>

I have also tried to remove {emulateJSON: true} but the result is the same.

The server Go code looks like this:

func LoginPOST(w http.ResponseWriter, r *http.Request) {
  var loginForm struct {
    Username string `json:"username"`
    Password string `json:"password"`
  }
  body, err := ioutil.ReadAll(r.Body)
  if err != nil {
    // return 422
    return
  }
  fmt.Println("body string:", string(body))
  err = json.Unmarshal(body, &loginForm)
  if err != nil {
    fmt.Println(err)
    // return 422
    return
  }
  ...
}

The json.Unmarshal error will print: invalid character '-' in numeric literal, and that's because the r.Body is:

body string: -----------------------------10632500131211292840295750524
Content-Disposition: form-data; name="username"

MYUSERNAME
-----------------------------10632500131211292840295750524
Content-Disposition: form-data; name="password"

MYPASSWORD
-----------------------------10632500131211292840295750524--

I'm quite sure the Go code is correct, but I can't figure out why vue-resource sends the FormData in that way. I'd appreciate if someone could show how to send json and nothing else in the request

Body:
NProgress.start()
      var formData = {
        username: this.username,
        password: this.password
      }
      this.$http.post(loginURL, formData).then(response => {
        console.log(response)
      }, response => {
        console.log(response)
      })

A regualr formdata object from the browser is never json encoded as far as i know. So just define a json object and everything should be fine.


问:
Simple Probability
Five U.S. Senators are selected at random from the 100 U.S. Senators. What is
the probability that at least two of the five selected are from the same state? There are 50 states, each with two senators.</p>

答:
The probability that the second senator selected is not from the same state as the first is 98/99.

The probability that the third senator selected is not from the same states as the first two is 96/98.

The probability that the fourth senator selected is not from the same state as the first three is 94/97.

The probability that the fifth senator selected is not from the same state as the first four is 92/96.

Therefore the probability that all five senators are from different states 98*96*94*92/(99*98*97*96) =~ 0.90. In all other cases you get two or more from the same state, with a probability of ~0.10.

Title: Simple Probability


问:
Filtering JavaScript objects using values from multiple arrays
If I have array of objects.

```<code>var products = [{
       names: ["hammer", "nail", "rubber duck"],
       colors: ["yellow", "red", "pink"]
    },
    {
       names: ["saw", "tractor", "bowling ball"],
       colors: ["gray", "purple", "green"]
    }]
</code>```

Then I have object with arrays of filter values:

```<code>var filters = {names: ["saw", "bowling ball"], colors:["purple"]}
</code>```

I need to filter the objects so that if I've got no filters I get all objects back. If I've got any filter values in "names" I get objects back with matching names. If I've got any filter values in both "names" and "colors" I get objects back with matching values on both.

For example:

```<code>var filters = {names: ["saw", "bowling ball"], colors:["purple"]}
</code>```

would return

```<code>[{
names: ["saw", "tractor" "bowling ball"],
colors: ["gray", "purple", "green"]
}]
</code>```

答:
```<code>    const filterProducts = (filter, products) => {
        let len=products.length,i=0,
            filteredProducts = [];

        for(;i<len;i++) {
            let product = products[i];
            if(filters.names) {
                let names = getMatch(filters.names, product.names);
                if(names) {
                    if(!filteredProducts[i]) filteredProducts[i] = {};
                    filteredProducts[i].names = names;
                };
            }
            if(filters.colors) {
                let colors = getMatch(filters.colors, product.colors);
                if(colors) {
                    if(!filteredProducts[i]) filteredProducts[i] = {};
                    filteredProducts[i].colors = colors;
                };
            }
        }

        if(filteredProducts.length) return filteredProducts;
        return products;
    }

    const getMatch = (filter, values) => {
        let filterLength = filter.length;
        for(let i=0;i<filterLength;i++) {
            if(values.indexOf(filter[i]) !== -1) return values;
        }
    }

    let filtered = filterProducts(filters, products);
    console.log(filtered);
</code>```

Body:
If I have array of objects.

var products = [{
       names: ["hammer", "nail", "rubber duck"],
       colors: ["yellow", "red", "pink"]
    },
    {
       names: ["saw", "tractor", "bowling ball"],
       colors: ["gray", "purple", "green"]
    }]

Then I have object with arrays of filter values:

var filters = {names: ["saw", "bowling ball"], colors:["purple"]}

I need to filter the objects so that if I've got no filters I get all objects back. If I've got any filter values in "names" I get objects back with matching names. If I've got any filter values in both "names" and "colors" I get objects back with matching values on both.

For example:

var filters = {names: ["saw", "bowling ball"], colors:["purple"]}

would return

[{
names: ["saw", "tractor" "bowling ball"],
colors: ["gray", "purple", "green"]
}]


问:
CTFontDrawGlyphs draws at incorrect position
EDITED: I replaced my original code stub with a self-contained version

I am using Quartz2D to draw musical symbols to a CGContext. I am doing this in a Playground using Swift 4.

Musical Notes are composed of a single CGGlyph for the notehead and a line primitive for the stem. The glyph is taken from the music font "bravura".
The x-position of the notehead glyph is exactly positioned at its left edge. The stem must be aligned perfectly to this origin, therefore its x-position must be the notehead's x-position + the stem's thickness / 2.

I have a function that takes a CGFloat as the x-position and draws the glyph and the stem into the CGContext. This works perfectly fine when the value for x is a rounded value like 30.0. However, when the value is a fractional number like 30.9, the stem gets misaligned:

It is obvious that the line is drawing correctly but the glyph is ignoring the fractional part of the CGFloat. When I raise the x-value further to 31.0 both parts are in sync again.

Here is the simplified Code, which will work in your XCode9 Playground:

```<code>import PlaygroundSupport
import Cocoa

let fontSize = CGFloat(64)

// uncomment the next paragraph if you have added the "Bravura" Font to the ressources folder
/*
let fontURL = Bundle.main.url(forResource: "Bravura", withExtension: "otf")
CTFontManagerRegisterFontsForURL(fontURL! as CFURL, CTFontManagerScope.process, nil)
var font = CTFontCreateWithName("Bravura" as CFString, fontSize, nil)
*/

// comment out the next line if you use Bravura
var font = CTFontCreateWithName("Helvetica" as CFString, fontSize, nil)

func drawAtXPosition(_ posX: CGFloat, inContext context: CGContext) {
    // draw font glyph (notehead)
    var glyph = CTFontGetGlyphWithName(font, "uniE0A3" as CFString)
    var notePosition = CGPoint(x: posX, y: 100)
    CTFontDrawGlyphs(font, &glyph, &notePosition, 1, context)

    // draw line (note stem)
    let stemThickness = CGFloat(fontSize/4*0.12)
    let x: CGFloat = posX + stemThickness / 2
    let y: CGFloat = 100 - (0.168 * fontSize / 4)
    let stemBegin = CGPoint(x:x, y:y)
    let stemEnd = CGPoint(x:x, y: y - (3.5 * fontSize / 4))

    context.setLineWidth(stemThickness)
    context.strokeLineSegments(between: [stemBegin, stemEnd])
}

class MyView: NSView {
    override func draw(_ rect: CGRect) {
        let context = NSGraphicsContext.current!.cgContext
        context.setStrokeColor(CGColor.black)
        context.setFillColor(CGColor.black)

        drawAtXPosition(100, inContext: context)    // this draws as expected

        drawAtXPosition(200.99, inContext: context) // here the glyph is drawn at x=200, while the line is correctly drawn at 200.99
    }
}

var myView = MyView(frame: CGRect(x: 0, y: 0, width: 500, height: 200))
let myViewController = NSViewController()
myViewController.view = myView
PlaygroundPage.current.liveView = myViewController
</code>```

You can download the music font "Bravura" from...

https://www.smufl.org/fonts/

... but I rewrote the code so it uses Helvetica per default, which also works for demonstration.

As a workaround in my original code I have implemented the .rounded() method of Foundation before passing the x-values to the drawing function. This works, but I'm afraid that at small font sizes (the whole code is written so that everything scales around the font size) the inaccuracy will be noticable.

I came across the methods setShouldSubpixelPositionFonts and setAllowsFontSubpixelPositioning of CGContext, but setting them to true does not do any change.

So, is there a way to draw the font objects just as precisely as the primitives (there must be one)? Or is my concern about rounding the CGFloats to Ints unjustified?

答:
After endless digging I found the solution:

It is not sufficient to set

```<code>context.setShouldSubpixelPositionFonts(true)
</code>```

You also have to set

```<code>context.setShouldSubpixelQuantizeFonts(false)
</code>```

as the latter seems to override the former.

Body:
EDITED: I replaced my original code stub with a self-contained version

I am using Quartz2D to draw musical symbols to a CGContext. I am doing this in a Playground using Swift 4.

Musical Notes are composed of a single CGGlyph for the notehead and a line primitive for the stem. The glyph is taken from the music font "bravura".
The x-position of the notehead glyph is exactly positioned at its left edge. The stem must be aligned perfectly to this origin, therefore its x-position must be the notehead's x-position + the stem's thickness / 2.

I have a function that takes a CGFloat as the x-position and draws the glyph and the stem into the CGContext. This works perfectly fine when the value for x is a rounded value like 30.0. However, when the value is a fractional number like 30.9, the stem gets misaligned:

It is obvious that the line is drawing correctly but the glyph is ignoring the fractional part of the CGFloat. When I raise the x-value further to 31.0 both parts are in sync again.

Here is the simplified Code, which will work in your XCode9 Playground:

import PlaygroundSupport
import Cocoa

let fontSize = CGFloat(64)

// uncomment the next paragraph if you have added the "Bravura" Font to the ressources folder
/*
let fontURL = Bundle.main.url(forResource: "Bravura", withExtension: "otf")
CTFontManagerRegisterFontsForURL(fontURL! as CFURL, CTFontManagerScope.process, nil)
var font = CTFontCreateWithName("Bravura" as CFString, fontSize, nil)
*/

// comment out the next line if you use Bravura
var font = CTFontCreateWithName("Helvetica" as CFString, fontSize, nil)

func drawAtXPosition(_ posX: CGFloat, inContext context: CGContext) {
    // draw font glyph (notehead)
    var glyph = CTFontGetGlyphWithName(font, "uniE0A3" as CFString)
    var notePosition = CGPoint(x: posX, y: 100)
    CTFontDrawGlyphs(font, &glyph, &notePosition, 1, context)

    // draw line (note stem)
    let stemThickness = CGFloat(fontSize/4*0.12)
    let x: CGFloat = posX + stemThickness / 2
    let y: CGFloat = 100 - (0.168 * fontSize / 4)
    let stemBegin = CGPoint(x:x, y:y)
    let stemEnd = CGPoint(x:x, y: y - (3.5 * fontSize / 4))

    context.setLineWidth(stemThickness)
    context.strokeLineSegments(between: [stemBegin, stemEnd])
}

class MyView: NSView {
    override func draw(_ rect: CGRect) {
        let context = NSGraphicsContext.current!.cgContext
        context.setStrokeColor(CGColor.black)
        context.setFillColor(CGColor.black)

        drawAtXPosition(100, inContext: context)    // this draws as expected

        drawAtXPosition(200.99, inContext: context) // here the glyph is drawn at x=200, while the line is correctly drawn at 200.99
    }
}

var myView = MyView(frame: CGRect(x: 0, y: 0, width: 500, height: 200))
let myViewController = NSViewController()
myViewController.view = myView
PlaygroundPage.current.liveView = myViewController

You can download the music font "Bravura" from...

https://www.smufl.org/fonts/

... but I rewrote the code so it uses Helvetica per default, which also works for demonstration.

As a workaround in my original code I have implemented the .rounded() method of Foundation before passing the x-values to the drawing function. This works, but I'm afraid that at small font sizes (the whole code is written so that everything scales around the font size) the inaccuracy will be noticable.

I came across the methods setShouldSubpixelPositionFonts and setAllowsFontSubpixelPositioning of CGContext, but setting them to true does not do any change.

So, is there a way to draw the font objects just as precisely as the primitives (there must be one)? Or is my concern about rounding the CGFloats to Ints unjustified?

Body:
After endless digging I found the solution:

It is not sufficient to set

context.setShouldSubpixelPositionFonts(true)

You also have to set

context.setShouldSubpixelQuantizeFonts(false)

as the latter seems to override the former.


问:
RST codeblock with internal indentation
I'm using Sphinx to document methods that return dictionaries.

```<code>def do_stuff(foo, bar):
    """Do some stuff

    :param foo: I'm an argument
    :param bar: So am I

    :return: dict::

        {
          "success": (Boolean) True if stuff was done
          "meta": {
              "aaa": A nested return value
              "bbb": Another nested return value
          }
        }
    """
</code>```

The formatting for the dictionary object looks off:

As best I can tell, the problem is that string literals in RST are expected to be indented at the same level.

Is there a workaround for this?

答:
Indenting the :: and then further indenting the dictionary, got it recognized as a codeblock. This was using .. autofunction:: do_stuff and sphinx 1.5.2.

```<code>def do_stuff(foo, bar):
    """Do some stuff

    :param foo: I'm an argument
    :param bar: So am I

    :return: dict
        ::
            {
              "success": (Boolean) True if stuff was done
              "meta": {
                  "aaa": A nested return value
                  "bbb": Another nested return value
              }
            }
    """
</code>```

When I separated out the dict part, I had to format like so.

```<code>def do_stuff(foo, bar):
    """Do some stuff

    :param foo: I'm an argument
    :param bar: So am I
    :rtype: dict
    :return:
        ::

            {
              "success": (Boolean) True if stuff was done
              "meta": {
                  "aaa": A nested return value
                  "bbb": Another nested return value
              }
            }
    """
</code>```

Title: RST codeblock with internal indentation

Body:
I'm using Sphinx to document methods that return dictionaries.

def do_stuff(foo, bar):
    """Do some stuff

    :param foo: I'm an argument
    :param bar: So am I

    :return: dict::

        {
          "success": (Boolean) True if stuff was done
          "meta": {
              "aaa": A nested return value
              "bbb": Another nested return value
          }
        }
    """

The formatting for the dictionary object looks off:

As best I can tell, the problem is that string literals in RST are expected to be indented at the same level.

Is there a workaround for this?

Body:
Indenting the :: and then further indenting the dictionary, got it recognized as a codeblock. This was using .. autofunction:: do_stuff and sphinx 1.5.2.

def do_stuff(foo, bar):
    """Do some stuff

    :param foo: I'm an argument
    :param bar: So am I

    :return: dict
        ::
            {
              "success": (Boolean) True if stuff was done
              "meta": {
                  "aaa": A nested return value
                  "bbb": Another nested return value
              }
            }
    """

When I separated out the dict part, I had to format like so.

def do_stuff(foo, bar):
    """Do some stuff

    :param foo: I'm an argument
    :param bar: So am I
    :rtype: dict
    :return:
        ::

            {
              "success": (Boolean) True if stuff was done
              "meta": {
                  "aaa": A nested return value
                  "bbb": Another nested return value
              }
            }
    """


问:
How to save an image to FileField from its path?
I have an image stored in my media/logo/ folder and I'd like to save it to my model's FileField from my view. Here's what I tried but I'm getting an encoding error & the file becomes corrupted after I'm trying to save it.

UnicodeDecodeError: 'charmap' codec can't decode byte ...

views.py:

```<code>def save_records(request):
    new_path = os.path.join(settings.MEDIA_ROOT, 'logo', filename)
    same_file = File(new_path, filename)
    Company.objects.create(logo=same_file)
</code>```

I have some trouble understanding how I can save the file in new_path to the FileField, any idea ?

答:
If you want FileField to use an existing file instead of creating a new one.

```<code>def save_records(request):
    c = Company()
    c.logo.name = 'logo/<filename>'  #relative to the media root.
    c.save()
</code>```

And, if you want to modify the filename of an existing record

```<code>old_path = c.logo.path
c.logo.name = 'logo/<new filename>'  #relative to the media root.
new_path = settings.MEDIA_ROOT + c.logo.name
os.rename(old_path, new_path)
c.save()
</code>```

If you want to copy the contents to a new file, then use @Roman Miroshnychenko's solution.

Django's FileField internally uses FileSystemStorage to store and mangae the files, So you can override its behavior. This will make sure Django always uses file name supplied, instead of generating new one.

```<code>from django.core.files.storage import FileSystemStorage

class CustomFileStorage(FileSystemStorage):

    def get_available_name(self, name):
        return name # returns the same name
</code>```

In your models

```<code>from app.storage import CustomFileStorage

fs = CustomFileStorage()

class Company(models.Model):
   logo = model.FileField(storage=fs)
</code>```

Body:
I have an image stored in my media/logo/ folder and I'd like to save it to my model's FileField from my view. Here's what I tried but I'm getting an encoding error & the file becomes corrupted after I'm trying to save it.

UnicodeDecodeError: 'charmap' codec can't decode byte ...

views.py:

def save_records(request):
    new_path = os.path.join(settings.MEDIA_ROOT, 'logo', filename)
    same_file = File(new_path, filename)
    Company.objects.create(logo=same_file)

I have some trouble understanding how I can save the file in new_path to the FileField, any idea ?

Body:
If you want FileField to use an existing file instead of creating a new one.

def save_records(request):
    c = Company()
    c.logo.name = 'logo/<filename>'  #relative to the media root.
    c.save()

And, if you want to modify the filename of an existing record

old_path = c.logo.path
c.logo.name = 'logo/<new filename>'  #relative to the media root.
new_path = settings.MEDIA_ROOT + c.logo.name
os.rename(old_path, new_path)
c.save()

If you want to copy the contents to a new file, then use @Roman Miroshnychenko's solution.

Django's FileField internally uses FileSystemStorage to store and mangae the files, So you can override its behavior. This will make sure Django always uses file name supplied, instead of generating new one.

from django.core.files.storage import FileSystemStorage

class CustomFileStorage(FileSystemStorage):

    def get_available_name(self, name):
        return name # returns the same name

In your models

from app.storage import CustomFileStorage

fs = CustomFileStorage()

class Company(models.Model):
   logo = model.FileField(storage=fs)