问:
Digging down json file
I have been trying in many ways (and by many questions in stackoverflow) to normalize a deep json file.
I have tried with .apply(pd.Series), not great with many levels of dictionary.

I am currently trying with json_normalize and it has given some results. I think I know how the function works and that my problem is that I don't know how to navigate through a dictionary.

So far, I have been able to dig into 2 levels.

```<code>import json
import pandas as pd
from pandas.io.json import json_normalize
raw = json.load(open('authors.json'))
raw2 = json_normalize(raw['hits']['hits'])
</code>```

And it gives me what I need (at least the first levels). But I don't know how to go deeper.

I've tried:

```<code>raw2 = json_normalize(raw['hits']['hits'][0])
raw2 = json_normalize(raw['hits']['hits']['_source.authors'])
TypeError: string indices must be integers
</code>```

And many more, but just randomly trying stuff without understanding is not the right way. I guess my questions are:

How do I know how to include the next level ({} vs [] in the json)?

Is there any visual way to represent this?

It is weird that this topic is not developed more online. Day by day I work more and more with json data.

```<code>_id _index  _score  _source.authors _source.deleted _source.description _source.doi _source.is_valid    _source.issue   _source.journal ... _source.rating_versatility_weighted _source.review_count    _source.tag _source.title   _source.userAvg _source.user_id _source.venue_name  _source.views_count _source.volume  _type
0   7CB3F2AD    scibase_listings    1   None    0   None        1   None    Physical Review Letters ... 0   0   [mass spectra, elementary particles, bound sta...   Evidence for a new meson: A quasinuclear NN-ba...   0   None    Physical Review Letters 0   None    listing
1   7AF8EBC3    scibase_listings    1   [{'affiliations': ['Punjabi University'], 'aut...   0   None        1   None    Journal of Industrial Microbiology & Biotechno...   ... 0   0   [flow rate, operant conditioning, packed bed r...   Development of a stable continuous flow immobi...   0   None    Journal of Industrial Microbiology & Biotechno...   0   None    listing
2   7521A721    scibase_listings    1   [{'author_id': '7FF872BC', 'author_name': 'bar...   0   None        1   None    The American Historical Review  ... 0   0   [social movements]  Feminism and the women's movement : dynamics o...   0   None    The American Historical Review  0   None    listing
</code>```

This is a chunk of the file (this is level 3, level 1 and 2 are, hits, hits).

```<code>{
"_shards": {
    "failed": 0,
    "successful": 5,
    "total": 5
},
"hits": {
    "hits": [{
            "_id": "7CB3F2AD",
            "_index": "scibase_listings",
            "_type": "listing",
            "_score": 1,
            "_source": {
                "userAvg": 0,
                "meta_keywords": null,
                "views_count": 0,
                "rating_reproducability": 0,
                "rating_versatility": 0,
                "rating_innovation": 0,
                "tag": null,
                "rating_reproducibility_weighted": 0,
                "meta_description": null,
                "review_count": 0,
                "rating_avg_weighted": 0,
                "venue_name": "The American Historical Review",
                "rating_num_weighted": 0,
                "is_valid": 1,
                "normalized_venue_name": "american historical review",
                "rating_clarity": 0,
                "description": null,
                "deleted": 0,
                "journal": "The American Historical Review",
                "volume": null,
                "link": null,
                "authors": [{
                        "author_id": "166468F4",
                        "author_name": "a bowdoin van riper"
                    },
                    {
                        "author_id": "81070854",
                        "author_name": "jeffrey h schwartz"
                    }
                ],
                "user_id": null,
                "pub_date": "1994-01-01 00:00:00",
                "pages": null,
                "doi": "",
                "issue": null,
                "rating_versatility_weighted": 0,
                "pubtype": null,
                "title": "Men Among the Mammoths: Victorian Science and the Discovery of Human Prehistory",
                "rating_clarity_weighted": 0,
                "rating_innovation_weighted": 0
            }
        },
        {
            "_index": "scibase_listings",
            "_type": "listing",
            "_id": "7538108B",
            "_score": 1,
            "_source": {
                "userAvg": 0,
                "meta_keywords": null,
                "views_count": 0,
                "rating_reproducability": 0,
                "rating_versatility": 0,
                "rating_innovation": 0,
                "tag": null,
                "rating_reproducibility_weighted": 0,
                "meta_description": null,
                "review_count": 0,
                "rating_avg_weighted": 0,
                "venue_name": "The American Historical Review",
                "rating_num_weighted": 0,
                "is_valid": 1,
                "normalized_venue_name": "american historical review",
                "rating_clarity": 0,
                "description": null,
                "deleted": 0,
                "journal": "The American Historical Review",
                "volume": null,
                "link": null,
                "authors": [{
                    "affiliations": [
                        "Pennsylvania State University"
                    ],
                    "author_id": "7E15BDFA",
                    "author_name": "roger l geiger"
                }],
                "user_id": null,
                "pub_date": "2013-06-01 00:00:00",
                "pages": null,
                "doi": "10.1093/ahr/118.3.896a",
                "issue": null,
                "rating_versatility_weighted": 0,
                "pubtype": null,
                "title": "Elizabeth Popp Berman. Creating the Market University: How Academic Science Became an Economic Engine.",
                "rating_clarity_weighted": 0,
                "rating_innovation_weighted": 0
            }
        }
    ]
}
</code>```

}

答:
I guess I figured out how to 'dig' through a json. It will depend if the next level is a list or a dict.

In my case I was able to dig until the end with below. I still need to find out how to use the full list (maybe loop) so I can have all values and not just [0] or [1].

```<code>raw['hits']['hits'][1]['_source']['authors'][0]['affiliations']
</code>```

Title: Digging down json file

Body:
I have been trying in many ways (and by many questions in stackoverflow) to normalize a deep json file.
I have tried with .apply(pd.Series), not great with many levels of dictionary.

I am currently trying with json_normalize and it has given some results. I think I know how the function works and that my problem is that I don't know how to navigate through a dictionary.

So far, I have been able to dig into 2 levels.

import json
import pandas as pd
from pandas.io.json import json_normalize
raw = json.load(open('authors.json'))
raw2 = json_normalize(raw['hits']['hits'])

And it gives me what I need (at least the first levels). But I don't know how to go deeper.

I've tried:

raw2 = json_normalize(raw['hits']['hits'][0])
raw2 = json_normalize(raw['hits']['hits']['_source.authors'])
TypeError: string indices must be integers

And many more, but just randomly trying stuff without understanding is not the right way. I guess my questions are:

How do I know how to include the next level ({} vs [] in the json)?

Is there any visual way to represent this?

It is weird that this topic is not developed more online. Day by day I work more and more with json data.

_id _index  _score  _source.authors _source.deleted _source.description _source.doi _source.is_valid    _source.issue   _source.journal ... _source.rating_versatility_weighted _source.review_count    _source.tag _source.title   _source.userAvg _source.user_id _source.venue_name  _source.views_count _source.volume  _type
0   7CB3F2AD    scibase_listings    1   None    0   None        1   None    Physical Review Letters ... 0   0   [mass spectra, elementary particles, bound sta...   Evidence for a new meson: A quasinuclear NN-ba...   0   None    Physical Review Letters 0   None    listing
1   7AF8EBC3    scibase_listings    1   [{'affiliations': ['Punjabi University'], 'aut...   0   None        1   None    Journal of Industrial Microbiology & Biotechno...   ... 0   0   [flow rate, operant conditioning, packed bed r...   Development of a stable continuous flow immobi...   0   None    Journal of Industrial Microbiology & Biotechno...   0   None    listing
2   7521A721    scibase_listings    1   [{'author_id': '7FF872BC', 'author_name': 'bar...   0   None        1   None    The American Historical Review  ... 0   0   [social movements]  Feminism and the women's movement : dynamics o...   0   None    The American Historical Review  0   None    listing

This is a chunk of the file (this is level 3, level 1 and 2 are, hits, hits).

{
"_shards": {
    "failed": 0,
    "successful": 5,
    "total": 5
},
"hits": {
    "hits": [{
            "_id": "7CB3F2AD",
            "_index": "scibase_listings",
            "_type": "listing",
            "_score": 1,
            "_source": {
                "userAvg": 0,
                "meta_keywords": null,
                "views_count": 0,
                "rating_reproducability": 0,
                "rating_versatility": 0,
                "rating_innovation": 0,
                "tag": null,
                "rating_reproducibility_weighted": 0,
                "meta_description": null,
                "review_count": 0,
                "rating_avg_weighted": 0,
                "venue_name": "The American Historical Review",
                "rating_num_weighted": 0,
                "is_valid": 1,
                "normalized_venue_name": "american historical review",
                "rating_clarity": 0,
                "description": null,
                "deleted": 0,
                "journal": "The American Historical Review",
                "volume": null,
                "link": null,
                "authors": [{
                        "author_id": "166468F4",
                        "author_name": "a bowdoin van riper"
                    },
                    {
                        "author_id": "81070854",
                        "author_name": "jeffrey h schwartz"
                    }
                ],
                "user_id": null,
                "pub_date": "1994-01-01 00:00:00",
                "pages": null,
                "doi": "",
                "issue": null,
                "rating_versatility_weighted": 0,
                "pubtype": null,
                "title": "Men Among the Mammoths: Victorian Science and the Discovery of Human Prehistory",
                "rating_clarity_weighted": 0,
                "rating_innovation_weighted": 0
            }
        },
        {
            "_index": "scibase_listings",
            "_type": "listing",
            "_id": "7538108B",
            "_score": 1,
            "_source": {
                "userAvg": 0,
                "meta_keywords": null,
                "views_count": 0,
                "rating_reproducability": 0,
                "rating_versatility": 0,
                "rating_innovation": 0,
                "tag": null,
                "rating_reproducibility_weighted": 0,
                "meta_description": null,
                "review_count": 0,
                "rating_avg_weighted": 0,
                "venue_name": "The American Historical Review",
                "rating_num_weighted": 0,
                "is_valid": 1,
                "normalized_venue_name": "american historical review",
                "rating_clarity": 0,
                "description": null,
                "deleted": 0,
                "journal": "The American Historical Review",
                "volume": null,
                "link": null,
                "authors": [{
                    "affiliations": [
                        "Pennsylvania State University"
                    ],
                    "author_id": "7E15BDFA",
                    "author_name": "roger l geiger"
                }],
                "user_id": null,
                "pub_date": "2013-06-01 00:00:00",
                "pages": null,
                "doi": "10.1093/ahr/118.3.896a",
                "issue": null,
                "rating_versatility_weighted": 0,
                "pubtype": null,
                "title": "Elizabeth Popp Berman. Creating the Market University: How Academic Science Became an Economic Engine.",
                "rating_clarity_weighted": 0,
                "rating_innovation_weighted": 0
            }
        }
    ]
}

}

Body:
I guess I figured out how to 'dig' through a json. It will depend if the next level is a list or a dict.

In my case I was able to dig until the end with below. I still need to find out how to use the full list (maybe loop) so I can have all values and not just [0] or [1].

raw['hits']['hits'][1]['_source']['authors'][0]['affiliations']


来源: stackexchange

问:
Benefit of using forEachOrdered with Parallel streams
The official Oracle documentation says:

Note that you may lose the benefits of parallelism if you use
  operations like forEachOrdered with parallel streams.
  Oracle - Parallelism

Why would anyone use forEachOrdered with parallel stream if we are losing parallelism?

答: I don't really get the question here. Why? because you simply have no alternative - you have so much data that parallel streams will help you (this still needs to be proven); but yet you still need to preserve the order - thus forEachOrdered. Notice that the documentation says may and not will lose that for sure - you would have to measure and see.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How to make the web site design more flexible
I wanna to ask the following question about the design of any web application.

When maximizing ,, minimizing , zooming the browser ,, i note many problems happen to my web application design for example the horizontal menu like the one exists in SO site when minimizing the window  the items of the menu in my website go down the other .. and other things make the site sucks and distracts the design .. how to make the design more flexible with the changes in monitor size , the preferences of the browser , maximizing ,and minimizing the browser ,, how to make the site design more flexible about all those issues .

Please any instructions , advice should i take care to reduce these errors.

答:
Try use something like Less Framework( http://lessframework.com/ )

Make sure you resize your browser when you visit the site!

ContentLicense: CC BY-SA 2.5


问:
How to update LiveData value?
I am using the new paging library for my data. Everything works fine when the ViewModel is created and live data is first initialized. Problem is that I can not update the value of my live data when for example I click on menu Item and want to update it with a different set of data. Then onChanged method in my fragment does not get called. I have read about MutableLiveData and methods like setValue and postValue which can update the live data, but in my case, I am using LivePagedListProvider and cannot return MutableLiveData from a database.

Dao:

```<code>@Query("SELECT * FROM teams ORDER BY name ASC")
LivePagedListProvider<Integer, Team> getAllTeams();
</code>```

Fragment:

```<code>mTeamViewModel.mTeamsList.observe(this, new Observer<PagedList<Team>>() {
        @Override
        public void onChanged(@Nullable PagedList<Team> teams) {
            mTeamAdapter.setList(teams);
        }
});
</code>```

ViewModel:

```<code>public LiveData<PagedList<Team>> mTeamsList;

@Inject
DatabaseManager mDatabaseManager;

void setTeamViewModel(final DatabaseManager databaseManager) {
    mDatabaseManager = databaseManager;

    mTeamsList = mDatabaseManager.getAllTeams().create(
            0,
            new PagedList.Config.Builder()
                    .setPageSize(50)
                    .setPrefetchDistance(50)
                    .setEnablePlaceholders(true)
                    .build());

}

boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_favorite:
            mTeamsList = mDatabaseManager.getFavoriteTeams().create(
                    0,
                    new PagedList.Config.Builder()
                            .setPageSize(50)
                            .setPrefetchDistance(50)
                            .build());
            return true;
        default: return false;
    }
}
</code>```

答:
Create a isFavourite column in your model. Then:

```<code>@Query("SELECT * FROM teams WHERE isFavourite = true")
LivePagedListProvider<Integer, Team> getFavouriteTeams();
</code>```

Then you should have a ViewModel with a function/field that returns a MutableLiveData<PagedList<Team>> and in the Fragment/Activity you observe to that field. In your Fragment/Activity you tell the ViewModel every change you need to do to de list showed. Then in the ViewModel you assign different values to the live data list.

Title: How to update LiveData value?

Body:
I am using the new paging library for my data. Everything works fine when the ViewModel is created and live data is first initialized. Problem is that I can not update the value of my live data when for example I click on menu Item and want to update it with a different set of data. Then onChanged method in my fragment does not get called. I have read about MutableLiveData and methods like setValue and postValue which can update the live data, but in my case, I am using LivePagedListProvider and cannot return MutableLiveData from a database.

Dao:

@Query("SELECT * FROM teams ORDER BY name ASC")
LivePagedListProvider<Integer, Team> getAllTeams();

Fragment:

mTeamViewModel.mTeamsList.observe(this, new Observer<PagedList<Team>>() {
        @Override
        public void onChanged(@Nullable PagedList<Team> teams) {
            mTeamAdapter.setList(teams);
        }
});

ViewModel:

public LiveData<PagedList<Team>> mTeamsList;

@Inject
DatabaseManager mDatabaseManager;

void setTeamViewModel(final DatabaseManager databaseManager) {
    mDatabaseManager = databaseManager;

    mTeamsList = mDatabaseManager.getAllTeams().create(
            0,
            new PagedList.Config.Builder()
                    .setPageSize(50)
                    .setPrefetchDistance(50)
                    .setEnablePlaceholders(true)
                    .build());

}

boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_favorite:
            mTeamsList = mDatabaseManager.getFavoriteTeams().create(
                    0,
                    new PagedList.Config.Builder()
                            .setPageSize(50)
                            .setPrefetchDistance(50)
                            .build());
            return true;
        default: return false;
    }
}

Body:
Create a isFavourite column in your model. Then:

@Query("SELECT * FROM teams WHERE isFavourite = true")
LivePagedListProvider<Integer, Team> getFavouriteTeams();

Then you should have a ViewModel with a function/field that returns a MutableLiveData<PagedList<Team>> and in the Fragment/Activity you observe to that field. In your Fragment/Activity you tell the ViewModel every change you need to do to de list showed. Then in the ViewModel you assign different values to the live data list.


问:
C++ cout wrong number in array
I am learning C++ and I find a weird result when I run code below:

```<code>#include <iostream>
using namespace std;

int* arrayTest(){
  int arr[3] = {1, 2, 3};
  int * poi = arr;
  return poi;
}

int main(){
  int* arr = arrayTest();
  for (int i = 0; i <3; i++){
    cout << *(arr+i) << endl;
 }
 return 0;
}
</code>```

result is:

```<code>./a.out
1
0
167772160
</code>```

What's wrong with this code?

g++ --version
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.2.0

Thank you.

答:
There's an issue with the design of this function:

```<code>int* arrayTest() {
  int arr[3] = {1, 2, 3};
  int * poi = arr;
  return poi;
}
</code>```

The variable arr is a local variable (in official C-speak, it has "automatic storage duration"). This means that as soon as the function returns, the memory associated with that array is reclaimed and recycled for future use.

The problem here is that you've made a pointer (poi) to the array. When you return that pointer, it points back to where arr used to be in memory, except that, alas, upon returning from the function arr has shuffled off this mortal coil and no longer exists. You now have a dangling pointer, which means that it's pointing at whatever unfortunate object happens to get placed in memory where arr used to be. This leads to undefined behavior, meaning that anything can happen (in your case, the program prints garbage values.)

Title: C++ cout wrong number in array

Body:
I am learning C++ and I find a weird result when I run code below:

#include <iostream>
using namespace std;

int* arrayTest(){
  int arr[3] = {1, 2, 3};
  int * poi = arr;
  return poi;
}

int main(){
  int* arr = arrayTest();
  for (int i = 0; i <3; i++){
    cout << *(arr+i) << endl;
 }
 return 0;
}

result is:

./a.out
1
0
167772160

What's wrong with this code?

g++ --version
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.2.0

Thank you.

Body:
There's an issue with the design of this function:

int* arrayTest() {
  int arr[3] = {1, 2, 3};
  int * poi = arr;
  return poi;
}

The variable arr is a local variable (in official C-speak, it has "automatic storage duration"). This means that as soon as the function returns, the memory associated with that array is reclaimed and recycled for future use.

The problem here is that you've made a pointer (poi) to the array. When you return that pointer, it points back to where arr used to be in memory, except that, alas, upon returning from the function arr has shuffled off this mortal coil and no longer exists. You now have a dangling pointer, which means that it's pointing at whatever unfortunate object happens to get placed in memory where arr used to be. This leads to undefined behavior, meaning that anything can happen (in your case, the program prints garbage values.)


问:
GridView getChildAt returning null for visible children
I have a grid of images that were taken from a custom camera activity.
On other activity I load the images into a grid.
I have a method that turn on & off a checkbox on each Image.
While trying to move through all the images, I'm getting some strange behavior:
GridView.getCount() returns the correct number of images in the GridView, but GridView.getChildAt() method returned only part of the images.
so, when I try to do so, I get a null Exception.

The GridView Adapter:

```<code>public class PhotoGalleryAdapter extends ArrayAdapter {

    // Declare variables
    private Activity adapterActivity;
    private int layoutResourceId;
    private ArrayList gridItemsArray;
    private static LayoutInflater inflater = null;

    public PhotoGalleryAdapter(Activity a, int layoutResourceId, ArrayList fGridItemArray) {
        super(a, layoutResourceId, fGridItemArray);
        this.layoutResourceId = layoutResourceId;
        this.adapterActivity = a;
        this.gridItemsArray = fGridItemArray;
    }

    public int getCount() {
        return gridItemsArray.size();
    }

    public Object getItem(int position) {
        return gridItemsArray.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        HolderViewRow holderRow = null;
        View rowView = (View) convertView;

        if (rowView == null){
            LayoutInflater inflater = adapterActivity.getLayoutInflater();

            rowView = inflater.inflate(layoutResourceId, parent, false);

            holderRow = new HolderViewRow();

            holderRow.imageFileBMP = (ImageView) rowView.findViewById(R.id.imageObject);

            holderRow.checkBox = (CheckBox) rowView.findViewById(R.id.itemCheckBox);
            holderRow.checkBoxImage = (ImageView) rowView.findViewById(R.id.itemImageCheckBox);

            rowView.setTag(holderRow);
        }
        else
        {
            holderRow = (HolderViewRow) rowView.getTag();
        }

        PhotoGalleryItem item = (PhotoGalleryItem) gridItemsArray.get(position);

        // Set the decoded bitmap iitemnto ImageView
        holderRow.imageFileBMP.setImageBitmap(item.getImageBMP());
        holderRow.imageFilePath = item.getImagePath();

        return rowView;
    }

    static class HolderViewRow {
        ImageView imageFileBMP;
        String imageFilePath;
        CheckBox checkBox;
        ImageView checkBoxImage;
    }
}

public class PhotoGalleryItem {
    private Bitmap imageBMP;
    private String imagePath;
    private CheckBox checkBox;
    private ImageView checkBoxImage;

    public PhotoGalleryItem(Bitmap imageBMP, String imagePath) {
        super();
        this.imageBMP = imageBMP;
        this.imagePath = imagePath;
    }

    public Bitmap getImageBMP() {
        return imageBMP;
    }

    public void setImageBMP(Bitmap imageBMP) {
        this.imageBMP = imageBMP;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }
}
</code>```

The Grid Activity:

```<code>        private void RenderGridAndSetImages() {
            // Locate the GridView in gridView_PhotoDisplay.xml
            gridView = (GridView) findViewById(R.id.gridView_PhotoDisplay);
            // Pass String arrays to Adapter Class
            imageAdapter = new PhotoGalleryAdapter(this, R.layout.gridview_photo_item, GridItemArrayList);
            gridView.setAdapter(imageAdapter);
    }
</code>```

And the function that has the problem:

```<code>    public void SetVisibilityCheckBox_OnGrid (boolean checkBoxVisibility) {
        // Handle item selection On GRIDVIEW ImageItem
        final int size = gridView.getCount();
        try {
            ImageView imageCB;
            int cbVisibility;

            if (checkBoxVisibility)
                cbVisibility = View.VISIBLE;
            else
                cbVisibility = View.INVISIBLE;

            for(int i = 0; i < size; i++) {
                View viewItem = (View) gridView.getChildAt(i);
                if (viewItem != null) {
                    imageCB = (ImageView) viewItem.findViewById(R.id.itemImageCheckBox);
                    imageCB.setVisibility(cbVisibility);
                }
            }
        }
        catch (Exception ex) {
            // Error occurred while SetSelectCheckBoxOnGrid
            Log.e(PACKAGE_NAME, ACTIVITY_NAME + ".SetVisibilityCheckBox_OnGrid\n" + ex.getMessage());
        }
    }
</code>```

The GridView Layout:

```<code><RelativeLayout
    android:id="@+id/layout_Holder"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@color/activityBackground"
    tools:context="com.mountain.saymera.PhotoGalleryActivity">

    <!-- Image view: layout_GridView -->
    <RelativeLayout
        android:id="@+id/layout_PhotoGridDisplay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal"
        android:background="@color/activityBackground"
        android:padding="1dp">

        <GridView
            android:id="@+id/gridView_PhotoDisplay"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:columnWidth="100dp"
            android:drawSelectorOnTop="true"
            android:numColumns="auto_fit"
            android:verticalSpacing="1dp"
            android:horizontalSpacing="1dp"
            android:stretchMode="columnWidth"
            android:gravity="center"
            android:focusable="true"
            android:clickable="true"/>

        <TextView
            android:id="@+id/textView_NoImages"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/gallery_no_images"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:background="#00000000"
            android:textColor="@color/MenuButtonTint"
            android:textStyle="bold" />
    </RelativeLayout>
</RelativeLayout>
</code>```

The GridView Item Layout:

```<code><RelativeLayout
    android:id="@+id/layout_Holder"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/single_photo_frame_on_grid">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:background="@color/Grid_ItemFrame"
        android:padding="0.3dp">

        <com.mountain.saymera.SquareImageView
            android:id="@+id/imageObject"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"/>
    </LinearLayout>

    <CheckBox
        android:id="@+id/itemCheckBox"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible"
        android:tint="@color/Grid_ItemCheckbox"/>

    <ImageView
        android:id="@+id/itemImageCheckBox"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible"
        android:background="#00000000"
        android:src="@mipmap/ic_crop_square_black_24dp"
        android:tint="@color/MenuCheckboxTint"/>

</RelativeLayout>
</code>```

Need some help, Thanks

答:
I have faced the same issue with programatically added ImageViews in a LinearLayout. Unfortunately, this method seems to be buggy at the moment, so I had to help myself by finding an alternative.
As a workaround, I saved the references of my ImageViews in a List and worked with them.</p>

Body:
I have a grid of images that were taken from a custom camera activity.
On other activity I load the images into a grid.
I have a method that turn on & off a checkbox on each Image.
While trying to move through all the images, I'm getting some strange behavior:
GridView.getCount() returns the correct number of images in the GridView, but GridView.getChildAt() method returned only part of the images.
so, when I try to do so, I get a null Exception.

The GridView Adapter:

public class PhotoGalleryAdapter extends ArrayAdapter {

    // Declare variables
    private Activity adapterActivity;
    private int layoutResourceId;
    private ArrayList gridItemsArray;
    private static LayoutInflater inflater = null;

    public PhotoGalleryAdapter(Activity a, int layoutResourceId, ArrayList fGridItemArray) {
        super(a, layoutResourceId, fGridItemArray);
        this.layoutResourceId = layoutResourceId;
        this.adapterActivity = a;
        this.gridItemsArray = fGridItemArray;
    }

    public int getCount() {
        return gridItemsArray.size();
    }

    public Object getItem(int position) {
        return gridItemsArray.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        HolderViewRow holderRow = null;
        View rowView = (View) convertView;

        if (rowView == null){
            LayoutInflater inflater = adapterActivity.getLayoutInflater();

            rowView = inflater.inflate(layoutResourceId, parent, false);

            holderRow = new HolderViewRow();

            holderRow.imageFileBMP = (ImageView) rowView.findViewById(R.id.imageObject);

            holderRow.checkBox = (CheckBox) rowView.findViewById(R.id.itemCheckBox);
            holderRow.checkBoxImage = (ImageView) rowView.findViewById(R.id.itemImageCheckBox);

            rowView.setTag(holderRow);
        }
        else
        {
            holderRow = (HolderViewRow) rowView.getTag();
        }

        PhotoGalleryItem item = (PhotoGalleryItem) gridItemsArray.get(position);

        // Set the decoded bitmap iitemnto ImageView
        holderRow.imageFileBMP.setImageBitmap(item.getImageBMP());
        holderRow.imageFilePath = item.getImagePath();

        return rowView;
    }

    static class HolderViewRow {
        ImageView imageFileBMP;
        String imageFilePath;
        CheckBox checkBox;
        ImageView checkBoxImage;
    }
}

public class PhotoGalleryItem {
    private Bitmap imageBMP;
    private String imagePath;
    private CheckBox checkBox;
    private ImageView checkBoxImage;

    public PhotoGalleryItem(Bitmap imageBMP, String imagePath) {
        super();
        this.imageBMP = imageBMP;
        this.imagePath = imagePath;
    }

    public Bitmap getImageBMP() {
        return imageBMP;
    }

    public void setImageBMP(Bitmap imageBMP) {
        this.imageBMP = imageBMP;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }
}

The Grid Activity:

        private void RenderGridAndSetImages() {
            // Locate the GridView in gridView_PhotoDisplay.xml
            gridView = (GridView) findViewById(R.id.gridView_PhotoDisplay);
            // Pass String arrays to Adapter Class
            imageAdapter = new PhotoGalleryAdapter(this, R.layout.gridview_photo_item, GridItemArrayList);
            gridView.setAdapter(imageAdapter);
    }

And the function that has the problem:

    public void SetVisibilityCheckBox_OnGrid (boolean checkBoxVisibility) {
        // Handle item selection On GRIDVIEW ImageItem
        final int size = gridView.getCount();
        try {
            ImageView imageCB;
            int cbVisibility;

            if (checkBoxVisibility)
                cbVisibility = View.VISIBLE;
            else
                cbVisibility = View.INVISIBLE;

            for(int i = 0; i < size; i++) {
                View viewItem = (View) gridView.getChildAt(i);
                if (viewItem != null) {
                    imageCB = (ImageView) viewItem.findViewById(R.id.itemImageCheckBox);
                    imageCB.setVisibility(cbVisibility);
                }
            }
        }
        catch (Exception ex) {
            // Error occurred while SetSelectCheckBoxOnGrid
            Log.e(PACKAGE_NAME, ACTIVITY_NAME + ".SetVisibilityCheckBox_OnGrid\n" + ex.getMessage());
        }
    }

The GridView Layout:

<RelativeLayout
    android:id="@+id/layout_Holder"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@color/activityBackground"
    tools:context="com.mountain.saymera.PhotoGalleryActivity">

    <RelativeLayout
        android:id="@+id/layout_PhotoGridDisplay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal"
        android:background="@color/activityBackground"
        android:padding="1dp">

        <GridView
            android:id="@+id/gridView_PhotoDisplay"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:columnWidth="100dp"
            android:drawSelectorOnTop="true"
            android:numColumns="auto_fit"
            android:verticalSpacing="1dp"
            android:horizontalSpacing="1dp"
            android:stretchMode="columnWidth"
            android:gravity="center"
            android:focusable="true"
            android:clickable="true"/>

        <TextView
            android:id="@+id/textView_NoImages"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/gallery_no_images"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:background="#00000000"
            android:textColor="@color/MenuButtonTint"
            android:textStyle="bold" />
    </RelativeLayout>
</RelativeLayout>

The GridView Item Layout:

<RelativeLayout
    android:id="@+id/layout_Holder"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/single_photo_frame_on_grid">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:background="@color/Grid_ItemFrame"
        android:padding="0.3dp">

        <com.mountain.saymera.SquareImageView
            android:id="@+id/imageObject"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"/>
    </LinearLayout>

    <CheckBox
        android:id="@+id/itemCheckBox"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible"
        android:tint="@color/Grid_ItemCheckbox"/>

    <ImageView
        android:id="@+id/itemImageCheckBox"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible"
        android:background="#00000000"
        android:src="@mipmap/ic_crop_square_black_24dp"
        android:tint="@color/MenuCheckboxTint"/>

</RelativeLayout>

Need some help, Thanks


问:
The most efficient way to determine the presence of repeated values in a 2D array, arranged like a table (with some starting ideas)
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

```<code> 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0
</code>```

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

答:
You will need to check each cell for a match by checking all surrounding cells (if they exist) for a total of 8 checks per cell. This is the basic idea of what you will want to do. I wrote the first condition to give you the idea.</p>

```<code>bool checkBoard(int[,] boardArray) {
    for (int i = 0; i < boardArray.GetLength(0); i++) {
        for (int j = 0; j < boardArray.GetLength(1); j++) {
            // Above
            if ((j+1) < boardArray.GetLength(1) && boardArray[i][j] == boardArray[i][j+1])
                return true;
            // Above Right
            if ()
                return true;
            // Right
            if ()
                return true;
            // Below Right
            if ()
                return true;
            // Below
            if ()
                return true;
            // Below Left
            if ()
                return true;
            // Left
            if ()
                return true;
            // Above Left
            if ()
                return true;
        }
    }
    return false;
}
</code>```

Body:
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

Body:
You will need to check each cell for a match by checking all surrounding cells (if they exist) for a total of 8 checks per cell. This is the basic idea of what you will want to do. I wrote the first condition to give you the idea.

bool checkBoard(int[,] boardArray) {
    for (int i = 0; i < boardArray.GetLength(0); i++) {
        for (int j = 0; j < boardArray.GetLength(1); j++) {
            // Above
            if ((j+1) < boardArray.GetLength(1) && boardArray[i][j] == boardArray[i][j+1])
                return true;
            // Above Right
            if ()
                return true;
            // Right
            if ()
                return true;
            // Below Right
            if ()
                return true;
            // Below
            if ()
                return true;
            // Below Left
            if ()
                return true;
            // Left
            if ()
                return true;
            // Above Left
            if ()
                return true;
        }
    }
    return false;
}


问:
Special characters are properly displayed in Eclipse but not in .jar file
This is my very first question on Stackoverflow.

I have developed a tool in Eclipse that receives an Excel file (.xls) and adds the content of some cells to a JList. The problem is when exporting the project to a Runnable JAR file, as all the special characters are shown as "�" in the JList. However, they are properly displayed when running the application from the IDE. Please help ^^

OS: macOS High Sierra (v.10.13.1)
Eclipse: Mars.1 Release (4.5.1)

答:
So far I have tried the following -

Run - Run Configurations - Common - Encoding - ISO-8859-1

Run - Debug Configurations -  Common - Encoding - ISO-8859-1

Eclipse - Preferences - General - Workspace - Text file encoding - ISO-8859-1

Even I went to the Eclipse folder and modified the file called "eclipse.ini"


问:
Create a column based on other columns value
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

```<code>WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |
</code>```

To this:

```<code>WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |
</code>```

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?

答:
Similar strategy as in @Gregor's dplyr solution, but using data.table:

```<code>library(data.table)
setDT(d)
d[order(SCORE), Name := tail(WORD, 1), Cluster]
</code>```

Body:
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |

To this:

WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?

Body:
Similar strategy as in @Gregor's dplyr solution, but using data.table:

library(data.table)
setDT(d)
d[order(SCORE), Name := tail(WORD, 1), Cluster]


问:
Shorter version of string match in Scala
I have the following code:

```<code>if (element.matches("class Int"))
      true
    else
      false
</code>```

Is it possible to use a function like the *.getOrElse for Sets to have cleaner code?

答:
```<code>if(condition) true else false
</code>```

is equivalent to just condition, so you can remove the if statement in your code and just use

```<code>element.matches("class Int")
</code>```

Also note that your pattern doesn't actually contain any regex operators and String.matches matches the whole string, so the whole thing is equivalent to checking whether element is equal to "class Int". So you don't actually need to use matches at all.

Body:
I have the following code:

if (element.matches("class Int"))
      true
    else
      false

Is it possible to use a function like the *.getOrElse for Sets to have cleaner code?

Body:
if(condition) true else false

is equivalent to just condition, so you can remove the if statement in your code and just use

element.matches("class Int")

Also note that your pattern doesn't actually contain any regex operators and String.matches matches the whole string, so the whole thing is equivalent to checking whether element is equal to "class Int". So you don't actually need to use matches at all.


问:
Outputting filenames in the same order as in directory - Python
I am trying to create a .txt file that reads all the filenames in a given directory and outputs the names without file extension onto a new .txt file. For ex: if my /images directory has img_1.jpg, img_2.jpg, img_4.jpg, img_4.jpg then this script will create a txt file with having img1, img2, img3, img4
I have a script that does a good job at creating the txt file, but the order in which the names are output is different from the order in which the images in my directory are placed.

```<code>import os
files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)]

with open('trainval.txt', 'w') as f:
    for s in files_no_ext:
        f.write("%s\n" % s)
</code>```

the image directory has images in the following order:

```<code>banana-0.jpg
banana-1.jpg
banana-2.jpg
.
.
banana-1000.jpg
</code>```

But the output in the .txt file is:

```<code>banana-0
banana-1
banana-10
banana-100
banana-1000
banana-1001
banana-1002
banana-1003
banana-1004
banana-1005
banana-1006
banana-1007
banana-1008
banana-1009
</code>```

How can I ensure that the output is in the same order as the order of images in the directory?

答:
listdir() preserves the order of your file system.

See:

Python - order of os.listdir

Nonalphanumeric list order from os.listdir() in Python

To sort your list based the numeric value in the file names:

Use sorted and regex to sort on the numeric value of the file name.

```<code>import re
import os

files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)]

files_no_ext = sorted(files_no_ext , key=lambda x: (x, int(re.sub('\D','', x)), x))

with open('trainval.txt', 'w') as f:
    for s in files_no_ext:
        f.write("%s\n" % s)
   # Could also do: f.write("\n".join(files_no_ext))
</code>```

Using mode="a" on open() is also probably better (mode="a" means append)

Body:
I am trying to create a .txt file that reads all the filenames in a given directory and outputs the names without file extension onto a new .txt file. For ex: if my /images directory has img_1.jpg, img_2.jpg, img_4.jpg, img_4.jpg then this script will create a txt file with having img1, img2, img3, img4
I have a script that does a good job at creating the txt file, but the order in which the names are output is different from the order in which the images in my directory are placed.

import os
files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)]

with open('trainval.txt', 'w') as f:
    for s in files_no_ext:
        f.write("%s\n" % s)

the image directory has images in the following order:

banana-0.jpg
banana-1.jpg
banana-2.jpg
.
.
banana-1000.jpg

But the output in the .txt file is:

banana-0
banana-1
banana-10
banana-100
banana-1000
banana-1001
banana-1002
banana-1003
banana-1004
banana-1005
banana-1006
banana-1007
banana-1008
banana-1009

How can I ensure that the output is in the same order as the order of images in the directory?

Body:
listdir() preserves the order of your file system.

See:

Python - order of os.listdir

Nonalphanumeric list order from os.listdir() in Python

To sort your list based the numeric value in the file names:

Use sorted and regex to sort on the numeric value of the file name.

import re
import os

files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)]

files_no_ext = sorted(files_no_ext , key=lambda x: (x, int(re.sub('\D','', x)), x))

with open('trainval.txt', 'w') as f:
    for s in files_no_ext:
        f.write("%s\n" % s)
   # Could also do: f.write("\n".join(files_no_ext))

Using mode="a" on open() is also probably better (mode="a" means append)


问:
Does function with empty body take place in memory in JavaScript?
I have just come across this question, and i think the answer should be yes but not sure</p>

答:
Yes.

JavaScript interpreters will either need to create a new object representing the function or at least a reference to a singleton instance of the identity function, both of which consume memory.


问:
How to find if a JSON object contains numbers and return them?
Lets say I have a jsonobject and this is coming from a random dataset dynamically. I would like to search through the jsonand do some manipulation on the number values of that jsonobject if there are any. I could loop through the Object by using a simple for..of and get the whole key but I am not sure how to go through every key value pair in the object and return the numbers. The following gives an example:

```<code>var obj = {
  "a0": {
    "count": 41,
    "name": "Park",

  },
  "a1": {
    "count": 52,
    "name": "Greg",

  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  },
  "a3": {
    "count": 276,
    "name": "Macho",

  },
  "a4": {
    "count": 36,
    "name": "Mariam",

  },
  "a5": {
    "count": 39,
    "name": "Blanca",

  }

}
</code>```

I can loop through it as follows:

```<code>for (let i of Object.keys(obj)) {
  console.log(obj[i]);
}
</code>```

I couldn't find any other properties on the Object other than hasOwnProperty and keys which could actually give me the values. I could simply access the values of the count by doing obj[i].count, but I wouldn't know if it has count. I am looking for a generic way to get the values and check for its type and return them as an array or do some manipulation with the number values.

Edit: I am looking to extract the properties which have numeric values in the object.

Could any one help me with this.

Thank you.

答:
const obj = {"a0":{"count":41,"name":"Park"},"a1":{"count":52,"name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

var newArray = [];
for (var key in obj) {
newArray.push(obj[key].count)
}
console.log(newArray);```

Body:
Lets say I have a jsonobject and this is coming from a random dataset dynamically. I would like to search through the jsonand do some manipulation on the number values of that jsonobject if there are any. I could loop through the Object by using a simple for..of and get the whole key but I am not sure how to go through every key value pair in the object and return the numbers. The following gives an example:

var obj = {
  "a0": {
    "count": 41,
    "name": "Park",

  },
  "a1": {
    "count": 52,
    "name": "Greg",

  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  },
  "a3": {
    "count": 276,
    "name": "Macho",

  },
  "a4": {
    "count": 36,
    "name": "Mariam",

  },
  "a5": {
    "count": 39,
    "name": "Blanca",

  }

}

I can loop through it as follows:

for (let i of Object.keys(obj)) {
  console.log(obj[i]);
}

I couldn't find any other properties on the Object other than hasOwnProperty and keys which could actually give me the values. I could simply access the values of the count by doing obj[i].count, but I wouldn't know if it has count. I am looking for a generic way to get the values and check for its type and return them as an array or do some manipulation with the number values.

Edit: I am looking to extract the properties which have numeric values in the object.

Could any one help me with this.

Thank you.


问:
Elasticsearch: Does edgeNGram token filter work on non english tokens?
I am trying to setup a new mapping for an index. Which is going to support partial keyword search and auto-complete requests powered by ES.

edgeNGram token filter with whitespace tokeniser seems a way to go. Till now my setting looks something like this:

```<code>curl -XPUT 'localhost:9200/test_ngram_2?pretty' -H 'Content-Type: application/json' -d'{
"settings": {
    "index": {
        "analysis": {
            "analyzer": {
                "customNgram": {
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": ["lowercase", "customNgram"]
                }
            },
            "filter": {
                "customNgram": {
                    "type": "edgeNGram",
                    "min_gram": "3",
                    "max_gram": "18",
                    "side": "front"
                }
            }
        }
    }
}
}'
</code>```

The problem is with Japanese words! Does NGrams work on japanese letters?
For e.g.:
【11月13日13時まで、フォロー&RTで応募！】

There is no whitespace in this - The document is not searchable with partial keywords, is that expected?

答:
You might want to look at the icu_tokenizer which adds support for foreign languages https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis-icu-tokenizer.html

Tokenizes text into words on word boundaries, as defined in UAX #29:
  Unicode Text Segmentation. It behaves much like the standard
  tokenizer, but adds better support for some Asian languages by using a
  dictionary-based approach to identify words in Thai, Lao, Chinese,
  Japanese, and Korean, and using custom rules to break Myanmar and
  Khmer text into syllables.

PUT icu_sample

```<code>{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "my_icu_analyzer": {
            "tokenizer": "icu_tokenizer"
          }
        }
      }
    }
  }
}
</code>```

Note that to use it in your index you need to install the appropriate plugin:

bin/elasticsearch-plugin install analysis-icu

Adding this to your code:

```<code>curl -XPUT 'localhost:9200/test_ngram_2?pretty' -H 'Content-Type: application/json' -d'{
"settings": {
    "index": {
        "analysis": {
            "analyzer": {
                "customNgram": {
                    "type": "custom",
                    "tokenizer": "icu_tokenizer",
                    "filter": ["lowercase", "customNgram"]
                }
            },
            "filter": {
                "customNgram": {
                    "type": "edgeNGram",
                    "min_gram": "3",
                    "max_gram": "18",
                    "side": "front"
                }
            }
        }
    }
}
}'
</code>```

Normally you would search an autocomplete like this using the standard analyzer, instead add an analyzer to your mapping also with the icu_tokenizer (but not the edgeNGram filter) and apply this to your query at search time, or explicitly set it as the search_analyzer for the field you apply customNgram to.

Body:
I am trying to setup a new mapping for an index. Which is going to support partial keyword search and auto-complete requests powered by ES.

edgeNGram token filter with whitespace tokeniser seems a way to go. Till now my setting looks something like this:

curl -XPUT 'localhost:9200/test_ngram_2?pretty' -H 'Content-Type: application/json' -d'{
"settings": {
    "index": {
        "analysis": {
            "analyzer": {
                "customNgram": {
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": ["lowercase", "customNgram"]
                }
            },
            "filter": {
                "customNgram": {
                    "type": "edgeNGram",
                    "min_gram": "3",
                    "max_gram": "18",
                    "side": "front"
                }
            }
        }
    }
}
}'

The problem is with Japanese words! Does NGrams work on japanese letters?
For e.g.:
【11月13日13時まで、フォロー&RTで応募！】

There is no whitespace in this - The document is not searchable with partial keywords, is that expected?

Body:
You might want to look at the icu_tokenizer which adds support for foreign languages https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis-icu-tokenizer.html

Tokenizes text into words on word boundaries, as defined in UAX #29:
  Unicode Text Segmentation. It behaves much like the standard
  tokenizer, but adds better support for some Asian languages by using a
  dictionary-based approach to identify words in Thai, Lao, Chinese,
  Japanese, and Korean, and using custom rules to break Myanmar and
  Khmer text into syllables.

PUT icu_sample

{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "my_icu_analyzer": {
            "tokenizer": "icu_tokenizer"
          }
        }
      }
    }
  }
}

Note that to use it in your index you need to install the appropriate plugin:

bin/elasticsearch-plugin install analysis-icu

Adding this to your code:

curl -XPUT 'localhost:9200/test_ngram_2?pretty' -H 'Content-Type: application/json' -d'{
"settings": {
    "index": {
        "analysis": {
            "analyzer": {
                "customNgram": {
                    "type": "custom",
                    "tokenizer": "icu_tokenizer",
                    "filter": ["lowercase", "customNgram"]
                }
            },
            "filter": {
                "customNgram": {
                    "type": "edgeNGram",
                    "min_gram": "3",
                    "max_gram": "18",
                    "side": "front"
                }
            }
        }
    }
}
}'

Normally you would search an autocomplete like this using the standard analyzer, instead add an analyzer to your mapping also with the icu_tokenizer (but not the edgeNGram filter) and apply this to your query at search time, or explicitly set it as the search_analyzer for the field you apply customNgram to.


问:
Why is the address of a variable defined inside a loop unchanged on each iteration?
```<code>for(int i=0; i<10;i++){
    int j = i;
    cout << &j << endl;
}
</code>```

This will output the same address of j in each iteration.  I also noticed the same behavior in C.  Shouldn't it be a different address for different iteration ?

In python different address is printed, couldn't verify it in java

```<code>for i in range(10):
    j = i
    print(hex(id(j)))
</code>```

c++ -v on my system returns this

Using built-in specs.
COLLECT_GCC=c++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.2.0-8ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3)
```

答:
The address of a local variable is an implementation detail of the compiler.

When a local comes into scope like this, the compiler might reuse the same address it had before, or it might not.  You shouldn't depend on it either way.

In practice, with optimizations turned off, it's most likely simpler for the compiler to use the same address each time.  In fact, if function a were to call function b multiple times, the local variables of function b will most likely be in the same place each time the function is called.

But again, this is an implementation detail.  There's no guarantee this will be the case across different compilers, or on the same compiler with different optimization settings.

Body:
for(int i=0; i<10;i++){
    int j = i;
    cout << &j << endl;
}

This will output the same address of j in each iteration.  I also noticed the same behavior in C.  Shouldn't it be a different address for different iteration ?

In python different address is printed, couldn't verify it in java

for i in range(10):
    j = i
    print(hex(id(j)))

c++ -v on my system returns this

Using built-in specs.
COLLECT_GCC=c++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.2.0-8ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3)


问:
Automating Chrome
I've seen some wild things happen when I paste some urlencoded Javascript into a URL on Firefox and Chrome. Is it possible to use this technique to tell Chrome to visit a URL and then save it as a file? I'm trying to automate Chrome, and Selenium looked extremely daunting.

EDIT: Unfortunately, I forgot to be more clear here. Let me explain. Things like wget, curl, etc. won't work because I have to get through logins in some of these scripts. And I've looked at iMacros, but found that I can't get them to run from command line except on Windows, unless I pay for the $499 package. Some other advantages of GCEs are that the dev platform is free and open to some degree, and they are cross-platform. (I use Linux.)

EDIT: At this point, I'm learning about Google Chrome Extensions. It appears they are easy to build and will let me (I think) tell the browser to open a new tab, go to a page, manipulate the DOM on that page (such as populating some fields and logging in), and then manipulate the DOM on the response page. GCEs don't let you do File I/O, so they are not like Firefox Extensions with XPCOM, but you can get around that by using AJAX to send data to a backend script (like a PHP script on a LAMP server) to save that data.

EDIT: By the way, and this is slightly off-topic (but I add to clarify) those "wild things" in Javascript that I mentioned were when you manipulate the DOM creating a URL that looks like so:

```<code>javascript:(function(){...your URL-encoded Javascript here...})();
</code>```

答: The solution appears to be to make one's own Google Chrome Extension (GCE). It is easy to learn within about 4 hours if you know how to do slightly advanced Javascript stuff, and is very powerful. I can use the Tabs API to create a new tab and go to a specific URL. I can then inject jQuery into that URL and make it manipulate the DOM or do anything we normally can do with jQuery. I can't do file I/O, but there are two workarounds. One, I can force the browser to download a file from a remote location, and I can send data from the current page back up to a remote server via jQuery's $.get() or $.post() calls.</p>

Title: Automating Chrome

Body:
I've seen some wild things happen when I paste some urlencoded Javascript into a URL on Firefox and Chrome. Is it possible to use this technique to tell Chrome to visit a URL and then save it as a file? I'm trying to automate Chrome, and Selenium looked extremely daunting.

EDIT: Unfortunately, I forgot to be more clear here. Let me explain. Things like wget, curl, etc. won't work because I have to get through logins in some of these scripts. And I've looked at iMacros, but found that I can't get them to run from command line except on Windows, unless I pay for the $499 package. Some other advantages of GCEs are that the dev platform is free and open to some degree, and they are cross-platform. (I use Linux.)

EDIT: At this point, I'm learning about Google Chrome Extensions. It appears they are easy to build and will let me (I think) tell the browser to open a new tab, go to a page, manipulate the DOM on that page (such as populating some fields and logging in), and then manipulate the DOM on the response page. GCEs don't let you do File I/O, so they are not like Firefox Extensions with XPCOM, but you can get around that by using AJAX to send data to a backend script (like a PHP script on a LAMP server) to save that data.

EDIT: By the way, and this is slightly off-topic (but I add to clarify) those "wild things" in Javascript that I mentioned were when you manipulate the DOM creating a URL that looks like so:

javascript:(function(){...your URL-encoded Javascript here...})();


问:
Bootstrap 4 makes outline not work
How does Bootstrap disable the HTML outline property?
When I add the form control class to my input, "outline: none;" no longer works.

```<code><input class="form-control" style="outline:none;">
</code>```

codepen: https://codepen.io/Eli92/pen/WXXbRa

I can just use my own css class for this input, but I want to know what's happening here, and I'm too much of a beginner to submit a bug report.

The reason I want to remove the outline is to add my own to an outer element, like Youtube and most popular sites do for their search bar.

答:
I dont know what exactly you want to know.

Just hopefully I can answer right.

The outline of the element is the border around it when you click into it. In your codepen you set the outline: none so nothing happens when you click into it. So your outline: none works totally fine.

The border is the the thing you see right there. Bootstrap also sets a border around it so if you set border:none you will get your effect as far as I understood the question.

Title: Bootstrap 4 makes outline not work

Body:
How does Bootstrap disable the HTML outline property?
When I add the form control class to my input, "outline: none;" no longer works.

<input class="form-control" style="outline:none;">

codepen: https://codepen.io/Eli92/pen/WXXbRa

I can just use my own css class for this input, but I want to know what's happening here, and I'm too much of a beginner to submit a bug report.

The reason I want to remove the outline is to add my own to an outer element, like Youtube and most popular sites do for their search bar.


问:
VBA Data validation list not working (Formula1:=)
The following code is a loop that takes the value of a cell (string), and inserts it into another sheet. it then separates the values of the string by a comma delimiter. It all works fine until I try to create a list data validation, where the Formula1:= does not seem to be working properly, however the code looks fine.

It is supposed to copy the current row of the loop all the way to the last column and create a data validation list out of it.

Please help, what am I doing wrong?

```<code>Sub dataVal()

    Dim lrow As Long
    Dim lcol As Long
    Dim i As Long
    Dim counter As Integer
    counter = 1
    lrow = Sheets("LVL & Mapping").Cells(Sheets("LVL & Mapping").Rows.count, "H").End(xlUp).Row
    lcol = Sheets("Sheet7").Cells(counter, Columns.count).End(xlToLeft).Column

    For i = 4 To lrow
      Range("I" & i).Select
      Selection.Copy
      Sheets("Sheet7").Select
      Range("A" & counter).Select
      ActiveSheet.Paste
      Application.CutCopyMode = False
      Selection.TextToColumns Destination:=Range("A" & counter), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), _
        TrailingMinusNumbers:=True
      Sheets("LVL & Mapping").Select
      Range("J" & i).Select
        With Selection.Validation
           .Delete
           .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=Sheets("Sheet7").Range(Cells(counter, 1), Cells(counter, lcol))
           .IgnoreBlank = True
           .InCellDropdown = True
           .InputTitle = ""
           .ErrorTitle = ""
           .InputMessage = ""
           .ErrorMessage = ""
           .ShowInput = True
           .ShowError = True
        End With
      counter = counter + 1
    Next i
End Sub
</code>```

答:
Based on how your code should work, this sub should do what you want.  I just don't understand the last column on Sheet7 (since I do not have your workbook) and why you were trying to do the data validation on each cell in column J, one at a time.
DataValidation lists need to be one column of data or a delimited list, thus I went with column A for Sheet7.</p>

```<code>Sub dataVal()

    Dim lrow As Long
    Dim i As Long

    Set shta = Sheets("LVL & Mapping")
    Set shtb = Sheets("Sheet7")
    lrow = Sheets("LVL & Mapping").Cells(Sheets("LVL & Mapping").Rows.Count, "H").End(xlUp).Row

      shta.Range("I4:I" & lrow).Copy shtb.Range("A1")

      Set objRange = shtb.Range("A1").EntireColumn

      objRange.TextToColumns Destination:=objRange, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Comma:=True, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1))

      With shta.Range("J4:J" & lrow).Validation
           .Delete
           .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Sheet1!" & shtb.Range("A1:A" & lrow).address
      End With

End Sub
</code>```

Body:
The following code is a loop that takes the value of a cell (string), and inserts it into another sheet. it then separates the values of the string by a comma delimiter. It all works fine until I try to create a list data validation, where the Formula1:= does not seem to be working properly, however the code looks fine.

It is supposed to copy the current row of the loop all the way to the last column and create a data validation list out of it.

Please help, what am I doing wrong?

Sub dataVal()

    Dim lrow As Long
    Dim lcol As Long
    Dim i As Long
    Dim counter As Integer
    counter = 1
    lrow = Sheets("LVL & Mapping").Cells(Sheets("LVL & Mapping").Rows.count, "H").End(xlUp).Row
    lcol = Sheets("Sheet7").Cells(counter, Columns.count).End(xlToLeft).Column

    For i = 4 To lrow
      Range("I" & i).Select
      Selection.Copy
      Sheets("Sheet7").Select
      Range("A" & counter).Select
      ActiveSheet.Paste
      Application.CutCopyMode = False
      Selection.TextToColumns Destination:=Range("A" & counter), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), _
        TrailingMinusNumbers:=True
      Sheets("LVL & Mapping").Select
      Range("J" & i).Select
        With Selection.Validation
           .Delete
           .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=Sheets("Sheet7").Range(Cells(counter, 1), Cells(counter, lcol))
           .IgnoreBlank = True
           .InCellDropdown = True
           .InputTitle = ""
           .ErrorTitle = ""
           .InputMessage = ""
           .ErrorMessage = ""
           .ShowInput = True
           .ShowError = True
        End With
      counter = counter + 1
    Next i
End Sub

Body:
Based on how your code should work, this sub should do what you want.  I just don't understand the last column on Sheet7 (since I do not have your workbook) and why you were trying to do the data validation on each cell in column J, one at a time.
DataValidation lists need to be one column of data or a delimited list, thus I went with column A for Sheet7.

Sub dataVal()

    Dim lrow As Long
    Dim i As Long

    Set shta = Sheets("LVL & Mapping")
    Set shtb = Sheets("Sheet7")
    lrow = Sheets("LVL & Mapping").Cells(Sheets("LVL & Mapping").Rows.Count, "H").End(xlUp).Row

      shta.Range("I4:I" & lrow).Copy shtb.Range("A1")

      Set objRange = shtb.Range("A1").EntireColumn

      objRange.TextToColumns Destination:=objRange, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Comma:=True, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1))

      With shta.Range("J4:J" & lrow).Validation
           .Delete
           .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Sheet1!" & shtb.Range("A1:A" & lrow).address
      End With

End Sub


问:
IBM Cloud Private 2.1.0 CE - Hostname should be resolved to a valid IP address
I'm trying to install IBM Cloud Private on a VM. I've created master, proxy, and worker nodes and I'm at the last stage installing the ICP. However, I'm having a problem with the hostnames. The errors are shown below:

The error is below:

```<code>TASK [check : Validating Hostname is resolvable]
*******************************************************************
skipping: [172.16.22.190]
fatal: [172.16.22.82] => Hostname should be resolved to a valid IP address
fatal: [172.16.22.81] => Hostname should be resolved to a valid IP address

NO MORE HOSTS LEFT
********************************************************************************

NO MORE HOSTS LEFT
********************************************************************************

PLAY RECAP
********************************************************************************
172.16.22.190              : ok=4    changed=3    unreachable=0    failed=0
172.16.22.81               : ok=4    changed=3    unreachable=0    failed=1
172.16.22.82               : ok=4    changed=3    unreachable=0    failed=1

Playbook run took 0 days, 0 hours, 0 minutes, 4 seconds
</code>```

My /etc/hosts file:

```<code>172.16.22.190   icp
172.16.22.81    proxy
172.16.22.82    worker

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
</code>```

My cluster hosts file:

```<code>[master]
172.16.22.190

[worker]
172.16.22.82

[proxy]
172.16.22.81

#[management]
#4.4.4.4
</code>```

All nodes see and ping each other and I'm using Ubuntu.

答: what about the /etc/hosts file on host 82 and 81?</p>

Body:
I'm trying to install IBM Cloud Private on a VM. I've created master, proxy, and worker nodes and I'm at the last stage installing the ICP. However, I'm having a problem with the hostnames. The errors are shown below:

The error is below:

TASK [check : Validating Hostname is resolvable]
*******************************************************************
skipping: [172.16.22.190]
fatal: [172.16.22.82] => Hostname should be resolved to a valid IP address
fatal: [172.16.22.81] => Hostname should be resolved to a valid IP address

NO MORE HOSTS LEFT
********************************************************************************

NO MORE HOSTS LEFT
********************************************************************************

PLAY RECAP
********************************************************************************
172.16.22.190              : ok=4    changed=3    unreachable=0    failed=0
172.16.22.81               : ok=4    changed=3    unreachable=0    failed=1
172.16.22.82               : ok=4    changed=3    unreachable=0    failed=1

Playbook run took 0 days, 0 hours, 0 minutes, 4 seconds

My /etc/hosts file:

172.16.22.190   icp
172.16.22.81    proxy
172.16.22.82    worker

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

My cluster hosts file:

[master]
172.16.22.190

[worker]
172.16.22.82

[proxy]
172.16.22.81

#[management]
#4.4.4.4

All nodes see and ping each other and I'm using Ubuntu.


问:
How utilize user input later in another method
For the following, I'm having a difficult time understanding how to use my user input from (days) and utilizing it on the last line to calculate the # of hours and minutes based on the user input of (days).</p>

```<code>import java.util.Scanner;

public class LearnScanner {
    public static void main (String[] args) {
        first();
        next();
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you "+name +", where are you travelling to?");
        String destination = input.nextLine();
        System.out.print("Great! "+destination +" sounds like a great trip");
     }
    public static void next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
    }
    public static void third() {
        String days;
        String hours = days * 24;
        String minutes = hours * 60;

        System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }
}
</code>```

答:
Firstly, it seems that the program shouldn't even compile successfully.
The object 'days' in third() is of String type. It isn't possible to multiply a String object with a numeric value 24. Ditto for minutes and hours on the next line as well.

Also, 'days' is being accepted in next() and as such is a local variable. It does not hold any significance in third().

Perhaps this might help.

```<code>import java.util.Scanner;

public class LearnScanner
{
    static String days = null;

    public static void main(String[] args)
    {

        first();
        next();
        third();
    }

    public static void first()
    {

        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you " + name + ", where are you travelling to?");
        String destination = input.nextLine();
        System.out.print("Great! " + destination + " sounds like a great trip");
    }

    public static void next()
    {

        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print(
                "What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
    }

    public static void third()
    {

        String hours = String.valueOf(Integer.valueOf(days) * 24);
        String minutes = String.valueOf(Integer.valueOf(hours) * 60);

        System.out.println(
                "If your are travelling for " + days + " days that is the same as "
                        + hours + " hours or " + minutes + " minutes");
    }

}
</code>```

Body:
For the following, I'm having a difficult time understanding how to use my user input from (days) and utilizing it on the last line to calculate the # of hours and minutes based on the user input of (days).

import java.util.Scanner;

public class LearnScanner {
    public static void main (String[] args) {
        first();
        next();
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you "+name +", where are you travelling to?");
        String destination = input.nextLine();
        System.out.print("Great! "+destination +" sounds like a great trip");
     }
    public static void next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
    }
    public static void third() {
        String days;
        String hours = days * 24;
        String minutes = hours * 60;

        System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }
}

Body:
Firstly, it seems that the program shouldn't even compile successfully.
The object 'days' in third() is of String type. It isn't possible to multiply a String object with a numeric value 24. Ditto for minutes and hours on the next line as well.

Also, 'days' is being accepted in next() and as such is a local variable. It does not hold any significance in third().

Perhaps this might help.

import java.util.Scanner;

public class LearnScanner
{
    static String days = null;

    public static void main(String[] args)
    {

        first();
        next();
        third();
    }

    public static void first()
    {

        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you " + name + ", where are you travelling to?");
        String destination = input.nextLine();
        System.out.print("Great! " + destination + " sounds like a great trip");
    }

    public static void next()
    {

        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print(
                "What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
    }

    public static void third()
    {

        String hours = String.valueOf(Integer.valueOf(days) * 24);
        String minutes = String.valueOf(Integer.valueOf(hours) * 60);

        System.out.println(
                "If your are travelling for " + days + " days that is the same as "
                        + hours + " hours or " + minutes + " minutes");
    }

}


问:
Data on axis is not in expected order
I'm trying to plot some data on a graph, but when I do if I use data_list, it's all wonky.

```<code>import numpy as np
from numpy import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

data_list = [('January', 1645480), ('February', 1608476), ('March', 1557113), ('April', 1391652), ('May', 1090298), ('July', 1150535), ('August', 1125931), ('September', 1158741), ('October', 1305849), ('November', 1407438), ('December', 1501733)]
working_list = [('April', 1391652), ('August', 1125931), ('December', 1501733), ('February', 1608476), ('January', 1645480), ('July', 1150535), ('March', 1557113), ('May', 1090298), ('November', 1407438), ('October', 1305849), ('September', 1158741)]

#### GRAPHING
def create_graph(data):
    x, y = zip(*data)
    plt.plot(x,y)
    axes = plt.gca() # Get the Current Axes
    axes.get_yaxis().get_major_formatter().set_scientific(False)  # Turn off scientific
    # Show data on Y axis points
    for i, j in zip(x,y):
        plt.annotate(str(j),xy=(i,j))
    plt.show()

def main():
## Graphing
    create_graph(working_list)

if __name__ == "__main__":
    main()
</code>```

But if I use working_list, it's correct! (It's in the order of the list. I'm simply trying to get the data to show from Jan - December on X-axis)

I've been staring at this for too long -- the data looks to be the exact same in each list, only data_list has "January" first, through December...I'm not sure why that would throw off the graph like it does.  I did notice that the X-Axis months and the data on the Y axis are correct -- but the line connector is all off, as is the order I expected...

答:
Matplotlib currently (as of version 2.1) has a problem with the order of categories on the axes. It will always sort the categories prior to plotting and you have no chance of changing that order. This will hopefully be fixed for the next release, but until then you would need to stick to plotting numeric values on the axes.

In this case this would mean you plot the data against some index and later set the ticklabes accordingly. Of course you could also use DateTimes, but that seems a bit overkill is you already have a list of the months available.

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

data_list = [('January', 1645480), ('February', 1608476), ('March', 1557113),
             ('April', 1391652), ('May', 1090298), ('July', 1150535),
             ('August', 1125931), ('September', 1158741), ('October', 1305849),
             ('November', 1407438), ('December', 1501733)]

#### GRAPHING
def create_graph(data):
    months, y = zip(*data)
    plt.plot(range(len(months)),y)
    axes = plt.gca() # Get the Current Axes
    axes.get_yaxis().get_major_formatter().set_scientific(False)
    axes.set_xticks(range(len(months)))
    axes.set_xticklabels(months, rotation=45, ha="right")
    # Show data on Y axis points
    for i, j in enumerate(y):
        plt.annotate(str(j),xy=(i,j))
    plt.show()

create_graph(data_list)
</code>```

Title: Data on axis is not in expected order

Body:
I'm trying to plot some data on a graph, but when I do if I use data_list, it's all wonky.

import numpy as np
from numpy import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

data_list = [('January', 1645480), ('February', 1608476), ('March', 1557113), ('April', 1391652), ('May', 1090298), ('July', 1150535), ('August', 1125931), ('September', 1158741), ('October', 1305849), ('November', 1407438), ('December', 1501733)]
working_list = [('April', 1391652), ('August', 1125931), ('December', 1501733), ('February', 1608476), ('January', 1645480), ('July', 1150535), ('March', 1557113), ('May', 1090298), ('November', 1407438), ('October', 1305849), ('September', 1158741)]

#### GRAPHING
def create_graph(data):
    x, y = zip(*data)
    plt.plot(x,y)
    axes = plt.gca() # Get the Current Axes
    axes.get_yaxis().get_major_formatter().set_scientific(False)  # Turn off scientific
    # Show data on Y axis points
    for i, j in zip(x,y):
        plt.annotate(str(j),xy=(i,j))
    plt.show()

def main():
## Graphing
    create_graph(working_list)

if __name__ == "__main__":
    main()

But if I use working_list, it's correct! (It's in the order of the list. I'm simply trying to get the data to show from Jan - December on X-axis)

I've been staring at this for too long -- the data looks to be the exact same in each list, only data_list has "January" first, through December...I'm not sure why that would throw off the graph like it does.  I did notice that the X-Axis months and the data on the Y axis are correct -- but the line connector is all off, as is the order I expected...

Body:
Matplotlib currently (as of version 2.1) has a problem with the order of categories on the axes. It will always sort the categories prior to plotting and you have no chance of changing that order. This will hopefully be fixed for the next release, but until then you would need to stick to plotting numeric values on the axes.

In this case this would mean you plot the data against some index and later set the ticklabes accordingly. Of course you could also use DateTimes, but that seems a bit overkill is you already have a list of the months available.

import numpy as np
import matplotlib.pyplot as plt

data_list = [('January', 1645480), ('February', 1608476), ('March', 1557113),
             ('April', 1391652), ('May', 1090298), ('July', 1150535),
             ('August', 1125931), ('September', 1158741), ('October', 1305849),
             ('November', 1407438), ('December', 1501733)]

#### GRAPHING
def create_graph(data):
    months, y = zip(*data)
    plt.plot(range(len(months)),y)
    axes = plt.gca() # Get the Current Axes
    axes.get_yaxis().get_major_formatter().set_scientific(False)
    axes.set_xticks(range(len(months)))
    axes.set_xticklabels(months, rotation=45, ha="right")
    # Show data on Y axis points
    for i, j in enumerate(y):
        plt.annotate(str(j),xy=(i,j))
    plt.show()

create_graph(data_list)


问:
Count not adding for each item, adding as a total C# console application
trying to get a count of each item in the array, however its adding a total number.

```<code>  Dictionary<string, int> counts = new Dictionary<string, int>() {
          { "HelloWorld", 0},
          { "Hello", 0},
          { "World", 0},
          { "integer", 0},
        };

        foreach (var item in arraylist)
        {
            counts["HelloWorld"] += 1;
            counts["Hello"] += 1;
            counts["World"] += 1;
            counts["integer"] += 1;

        }

        Console.WriteLine("");

        foreach (KeyValuePair<string, int> item in counts)
        {
            Console.WriteLine(item.Key.ToString() + ":" + item.Value.ToString());
        }

        Console.ReadLine();
        }
</code>```

E.g. Input: 1,10

Expected output:

```<code>hello: 3
world: 5
helloworld: 1
integer: 11
</code>```

Run below dotnet fiddle to find issue:

https://dotnetfiddle.net/eKHb5x

答:
Change your array list to a List and do this

```<code>foreach(var item in arrayList)
{
    if(counts.Contains(item))
    {
        counts[item]++;
    }
    else if (int.TryParse(item, out var i)) // this is a newish feature and my syntax might be a bit off
    {
        counts["integer"]++;
    }
}
</code>```

I did this on my phone so sorry if there are any spelling mistakes. I'll check back shortly and correct then on my laptop

Body:
trying to get a count of each item in the array, however its adding a total number.

  Dictionary<string, int> counts = new Dictionary<string, int>() {
          { "HelloWorld", 0},
          { "Hello", 0},
          { "World", 0},
          { "integer", 0},
        };

        foreach (var item in arraylist)
        {
            counts["HelloWorld"] += 1;
            counts["Hello"] += 1;
            counts["World"] += 1;
            counts["integer"] += 1;

        }

        Console.WriteLine("");

        foreach (KeyValuePair<string, int> item in counts)
        {
            Console.WriteLine(item.Key.ToString() + ":" + item.Value.ToString());
        }

        Console.ReadLine();
        }

E.g. Input: 1,10

Expected output:

hello: 3
world: 5
helloworld: 1
integer: 11

Run below dotnet fiddle to find issue:

https://dotnetfiddle.net/eKHb5x

Body:
Change your array list to a List and do this

foreach(var item in arrayList)
{
    if(counts.Contains(item))
    {
        counts[item]++;
    }
    else if (int.TryParse(item, out var i)) // this is a newish feature and my syntax might be a bit off
    {
        counts["integer"]++;
    }
}

I did this on my phone so sorry if there are any spelling mistakes. I'll check back shortly and correct then on my laptop


问:
Subscribe to a group of users
How to subscribe to a group for calendar events in Microsoft Graph API?

We have around 20,000 users and we need to subscribe to each users calendar event.

Is there a way to subscribe to AD group instead of individual users?

Most of examples shows subscription for a single user:

```<code>/v1.0/subscriptions/me/events
/v1.0/subscriptions/users/test@testemail.com/events)
</code>```

答:
Subscriptions are per-calendar, there isn't a subscription model available for multiple multiple calendars across multiple users. </p>

<p>I recommend visiting the UserVoice and adding your suggestion. </p>

Title: Subscribe to a group of users

Body:
How to subscribe to a group for calendar events in Microsoft Graph API?

We have around 20,000 users and we need to subscribe to each users calendar event.

Is there a way to subscribe to AD group instead of individual users?

Most of examples shows subscription for a single user:

/v1.0/subscriptions/me/events
/v1.0/subscriptions/users/test@testemail.com/events)

Body:
Subscriptions are per-calendar, there isn't a subscription model available for multiple multiple calendars across multiple users.

I recommend visiting the UserVoice and adding your suggestion.