问:
Is it possible to create a method using these interfaces as parameters?
I'm not sure how to word my issue so that it's clear. But I'll try my best sorry:

I have 4 interfaces:

```<code>        interface OnGetViewPagerListener {
            void onSuccessViewPager(Response<Feed> response);
            void onFailedViewPager();
        }

        interface OnNextPageViewPagerListener {
            void onSuccessViewPagerNextPage(Response<Feed> response);
            void onFailedViewPagerNextPage();
        }

        interface OnGetGridViewListener{
            void onSuccessGridView(Response<Feed> response);
            void onFailedGridView();
        }

        interface OnNextPageGridViewListener{
            void onSuccessGridViewNextPage(Response<Feed> response);
            void onFailedGridViewNextPage();
        }
</code>```

And I'm implementing these interfaces into my class MainRepo. Inside each of these methods, contains a network call:

Main Repo Class

```<code>@Override
public void getPostsViewPager(OnGetViewPagerListener onGetViewPagerListener, String url) {

        //Network Call

        RetrofitInterfaces.IGetTop service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.IGetTop.class);
        Call<Feed> call = service.listRepos(url);
        call.enqueue(new Callback<Feed>() {
            @Override
            public void onResponse(@NonNull Call<Feed> call, @NonNull Response<Feed> response) {
                onGetViewPagerListener.onSuccessViewPager(response);
            }
            @Override
            public void onFailure(@NonNull Call<Feed> call, @NonNull Throwable t) {
                onGetViewPagerListener.onFailedViewPager();
            }
        });
}
</code>```

Is it possible to create a method with the networkcall, and with parameters where I could use any of the 4 interfaces?

```<code>private makeNetworkCall(interface canUseAnyOfThe4InterfacesHere, String url){
    //Network call
}
</code>```

In case this is confusing, here is my code:

https://pastebin.com/y8kq9ZjQ

And as you can see, I don't want to have to type out each network call every time I use each interface.

答:
Apart from @Sharif ElKhatib's answer, which I think is the best way, another way is to write overloaded methods like this:</p>

```<code>private makeNetworkCall( OnGetViewPagerListener ogvpl, String url){
    actualNetworkCaller(); //This has the actual logic of making the network call
}

private makeNetworkCall( OnNextPageViewPagerListener onpvl, String url){
    actualNetworkCaller(); //This has the actual logic of making the network call
}

// And methods for the other two interfaces

private void actualNetworkCaller(){
    //Network call
}
</code>```

Body:
I'm not sure how to word my issue so that it's clear. But I'll try my best sorry:

I have 4 interfaces:

        interface OnGetViewPagerListener {
            void onSuccessViewPager(Response<Feed> response);
            void onFailedViewPager();
        }

        interface OnNextPageViewPagerListener {
            void onSuccessViewPagerNextPage(Response<Feed> response);
            void onFailedViewPagerNextPage();
        }

        interface OnGetGridViewListener{
            void onSuccessGridView(Response<Feed> response);
            void onFailedGridView();
        }

        interface OnNextPageGridViewListener{
            void onSuccessGridViewNextPage(Response<Feed> response);
            void onFailedGridViewNextPage();
        }

And I'm implementing these interfaces into my class MainRepo. Inside each of these methods, contains a network call:

Main Repo Class

@Override
public void getPostsViewPager(OnGetViewPagerListener onGetViewPagerListener, String url) {

        //Network Call

        RetrofitInterfaces.IGetTop service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.IGetTop.class);
        Call<Feed> call = service.listRepos(url);
        call.enqueue(new Callback<Feed>() {
            @Override
            public void onResponse(@NonNull Call<Feed> call, @NonNull Response<Feed> response) {
                onGetViewPagerListener.onSuccessViewPager(response);
            }
            @Override
            public void onFailure(@NonNull Call<Feed> call, @NonNull Throwable t) {
                onGetViewPagerListener.onFailedViewPager();
            }
        });
}

Is it possible to create a method with the networkcall, and with parameters where I could use any of the 4 interfaces?

private makeNetworkCall(interface canUseAnyOfThe4InterfacesHere, String url){
    //Network call
}

In case this is confusing, here is my code:

https://pastebin.com/y8kq9ZjQ

And as you can see, I don't want to have to type out each network call every time I use each interface.

Body:
Apart from @Sharif ElKhatib's answer, which I think is the best way, another way is to write overloaded methods like this:

private makeNetworkCall( OnGetViewPagerListener ogvpl, String url){
    actualNetworkCaller(); //This has the actual logic of making the network call
}

private makeNetworkCall( OnNextPageViewPagerListener onpvl, String url){
    actualNetworkCaller(); //This has the actual logic of making the network call
}

// And methods for the other two interfaces

private void actualNetworkCaller(){
    //Network call
}


来源: stackexchange

问:
Leiningen: how to exclude dependencies when uberjaring?
When using leiningen to build Clojure applications, how can certain dependencies be excluded from being included in the JAR file when using lein uberjar?

答:
In the project.clj under :dependencies you can add exclusions for specific jars like this:

[test/test-jar "1.0" :exclusions [sample-exclusion/test-exclusions]]

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Add Markers by country name leaflet R
I am on Rstudio, and I want to add a marker based on country name.

The variable that contain the number of occurence per country is cnt_country which is in the table below

```<code>Morocco                            57381
France                             35729
Tunisia                            85563
Saudi Arabia                       10816
Turkey                             6725
</code>```

However, when I use leaflet(cnt_country)%>% addTiles()%>% addMarkers() I get an error: cannot infer lat long information.

Is there a way for leaflet to add markers based on country name?

答:
For leaflet to locate the markers on the map, you'll need to provide geocoordinates. If you don't mind pinning the markers to the capital city of each country, you could get those geocoordinates from the world.cities data frame in the maps package.

```<code>library(dplyr)
library(leaflet)
library(maps)

# ingest your data
cnt_country <- read.table(text = "Morocco,57381\nFrance,35729\nTunisia,85563\nSaudi Arabia,10816\nTurkey,6725",
                          sep = ",",
                          header = FALSE,
                          stringsAsFactors = FALSE,
                          col.names = c("country", "n"))

# import the world.cities data frame from 'maps'
data(world.cities)

# merge the desired cols from that data frame with yours by country
df <- world.cities %>%
    filter(capital == 1) %>%
    dplyr::select(country = country.etc, lat, lng = long) %>%
    left_join(cnt_country, ., by = "country")

# now map the result
leaflet(df)%>%
    addTiles()%>%
    addMarkers(label = ~n)
</code>```

Title: Add Markers by country name leaflet R

Body:
I am on Rstudio, and I want to add a marker based on country name.

The variable that contain the number of occurence per country is cnt_country which is in the table below

Morocco                            57381
France                             35729
Tunisia                            85563
Saudi Arabia                       10816
Turkey                             6725

However, when I use leaflet(cnt_country)%>% addTiles()%>% addMarkers() I get an error: cannot infer lat long information.

Is there a way for leaflet to add markers based on country name?

Body:
For leaflet to locate the markers on the map, you'll need to provide geocoordinates. If you don't mind pinning the markers to the capital city of each country, you could get those geocoordinates from the world.cities data frame in the maps package.

library(dplyr)
library(leaflet)
library(maps)

# ingest your data
cnt_country <- read.table(text = "Morocco,57381\nFrance,35729\nTunisia,85563\nSaudi Arabia,10816\nTurkey,6725",
                          sep = ",",
                          header = FALSE,
                          stringsAsFactors = FALSE,
                          col.names = c("country", "n"))

# import the world.cities data frame from 'maps'
data(world.cities)

# merge the desired cols from that data frame with yours by country
df <- world.cities %>%
    filter(capital == 1) %>%
    dplyr::select(country = country.etc, lat, lng = long) %>%
    left_join(cnt_country, ., by = "country")

# now map the result
leaflet(df)%>%
    addTiles()%>%
    addMarkers(label = ~n)


问:
Isolation Forest for Anomaly Detection
In this example of IsolationForest for Anomaly Detection:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest

rng = np.random.RandomState(42)

# Generate train data
X = 0.3 * rng.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * rng.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = rng.uniform(low=-4, high=4, size=(20, 2))

# fit the model
clf = IsolationForest(max_samples=100, random_state=rng)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)
```

I believe that the outliers in this code were randomly introduced.
But, if I am doing an Anomaly Detection with real-life data, then:

How do I take this forward?

How to identify Anomalies if I have a dataset already?
I'm trying my hands on Combined Cycle Power Plant dataset.
OR, if you have any other good anomaly detection practice datasets drop some links!

答:
If you are asking for the contamination in the dataset. Then you need to check the contamination parameter.

clf = IsolationForest(max_samples=100, random_state=rng, contamination='auto')

It is based on the assumption that data has certain level of contamination.

Title: Isolation Forest for Anomaly Detection

Body:
In this example of IsolationForest for Anomaly Detection:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest

rng = np.random.RandomState(42)

# Generate train data
X = 0.3 * rng.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * rng.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = rng.uniform(low=-4, high=4, size=(20, 2))

# fit the model
clf = IsolationForest(max_samples=100, random_state=rng)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

I believe that the outliers in this code were randomly introduced.
But, if I am doing an Anomaly Detection with real-life data, then:

How do I take this forward?

How to identify Anomalies if I have a dataset already?
I'm trying my hands on Combined Cycle Power Plant dataset.
OR, if you have any other good anomaly detection practice datasets drop some links!


问:
how can I extract text contents from GUI apps  in linux?
I want to  extract text contents from GUI apps,here are 2 examples::

example 1:

Suppose I opened  firefox, and input url : www.google.com

how can I extract the string "www.google.com" from firefox using my own app ?

example 2:

open calculator(using gcalctool),then input 1+1

How can I extract the string "1+1" of calculator from my own program?

in brief ,what I want is to find out whether there is a way to extract the text contents from any widget of an GUI application

Thanks

答:
That sounds difficult. Supposing you're running X11, you can very easily grab a window picture ( see "man xwd"); however there is no easy way to get to the text unless it's selected and therefore copied to the clipboard.

Alternatively, if you only want to capture user input, this is quite easy to do, too, by activation the X11 record extension: put this in your /etc/X11/xorg.conf:

```<code>Section "Module"
        Load  "record"
        #Load other modules you need ...
 EndSection
</code>```

though it may prove difficult to use too, see example code for Xorg/X11 record extension fails

Body:
That sounds difficult. Supposing you're running X11, you can very easily grab a window picture ( see "man xwd"); however there is no easy way to get to the text unless it's selected and therefore copied to the clipboard.

Alternatively, if you only want to capture user input, this is quite easy to do, too, by activation the X11 record extension: put this in your /etc/X11/xorg.conf:

Section "Module"
        Load  "record"
        #Load other modules you need ...
 EndSection

though it may prove difficult to use too, see example code for Xorg/X11 record extension fails


问:
How to completely remove Python from a Windows machine?
I installed both Python 2.7 and Python 2.6.5. I don't know what went wrong, but nothing related to Python seems to work any more. e.g. "setup.py install" for certain packages don't recognize the "install" parameter and other odd phenomena...

I would like to completely remove Python from my system.

I tried running the 2.7 and 2.6 msi files and choosing remove Python and then running only 2.6 and reinstalling it. Still stuff don't work.

How do I completely remove Python - from everything? (!)

I would not like to reinstall my entire machine just because of the Python install...

答:
you can delete it manually.

open Command Prompt

cd C:\Users\<you name>\AppData\Local\Microsoft\WindowsApps

del python.exe

del python3.exe

Now the command prompt won't be showing it anymore

where python --> yields nothing, and you are free to install another version from source / anaconda and (after adding its address to Environment Variables -> Path) you will find that very python you just installed

ContentLicense: CC BY-SA 2.5


问:
ReferenceError: require is not defined @react
I made my own react component npm package and published in npm, now when import and use it in other CRA apps, i get this error when npm start in run in command line .

and in console:

My webpack.config.js file:

```<code>var webpack = require('webpack');
var path = require('path');
var nodeExternals = require('webpack-node-externals');

module.exports = {
    target: 'web',
    entry: './src/index.js',
    output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                include: path.resolve(__dirname, 'src'),
                exclude: /(node_modules|bower_components|build)/,
                use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env']
                }
                }
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url?limit=512&&name=[path][name].[ext]?[hash]'
            }
        ]
    },
    mode: 'development',
    externals: {
        'react': 'commonjs react'
    }
};
</code>```

My package.json file:

```<code>{
  "name": "primetable1",
  "version": "1.0.0",
  "description": "A Datatable for react apps based on Primereact",
  "main": "build/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack --watch",
    "build": "webpack"
  },
  "keywords": [
    "primereact",
    "primeicons"
  ],
  "author": "Anish Arya",
  "license": "ISC",
  "peerDependencies": {
    "react": "^16.4.0",
    "react-dom": "^16.4.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "babel-runtime": "^6.26.0",
    "css-loader": "^3.4.2",
    "file-loader": "^5.0.2",
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "react-hot-loader": "^4.12.19",
    "react-scripts": "3.4.0",
    "style-loader": "^1.1.3",
    "webpack-cli": "^3.3.11",
    "webpack-node-externals": "^1.7.2"
  },
  "dependencies": {
    "classnames": "^2.2.6",
    "primeicons": "^2.0.0",
    "primereact": "^3.4.0",
    "react-transition-group": "^4.3.0"
  }
}
</code>```

My .babelrc file:

```<code>{
    "presets": ["env"],
    "plugins": [
      "transform-object-rest-spread",
      "transform-react-jsx",
      "react-hot-loader/babel"
    ]
  }
</code>```

I followed this article to create and publish npm package:
https://codeburst.io/extracting-a-react-js-component-and-publishing-it-on-npm-2a49096757f5

How to solve this error?

答: The externals configuration seems wrong – you probably only need externals: [nodeExternals()] (from const nodeExternals = require("webpack-node-externals");).

Body:
I made my own react component npm package and published in npm, now when import and use it in other CRA apps, i get this error when npm start in run in command line .

and in console:

My webpack.config.js file:

var webpack = require('webpack');
var path = require('path');
var nodeExternals = require('webpack-node-externals');

module.exports = {
    target: 'web',
    entry: './src/index.js',
    output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                include: path.resolve(__dirname, 'src'),
                exclude: /(node_modules|bower_components|build)/,
                use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env']
                }
                }
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url?limit=512&&name=[path][name].[ext]?[hash]'
            }
        ]
    },
    mode: 'development',
    externals: {
        'react': 'commonjs react'
    }
};

My package.json file:

{
  "name": "primetable1",
  "version": "1.0.0",
  "description": "A Datatable for react apps based on Primereact",
  "main": "build/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack --watch",
    "build": "webpack"
  },
  "keywords": [
    "primereact",
    "primeicons"
  ],
  "author": "Anish Arya",
  "license": "ISC",
  "peerDependencies": {
    "react": "^16.4.0",
    "react-dom": "^16.4.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "babel-runtime": "^6.26.0",
    "css-loader": "^3.4.2",
    "file-loader": "^5.0.2",
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "react-hot-loader": "^4.12.19",
    "react-scripts": "3.4.0",
    "style-loader": "^1.1.3",
    "webpack-cli": "^3.3.11",
    "webpack-node-externals": "^1.7.2"
  },
  "dependencies": {
    "classnames": "^2.2.6",
    "primeicons": "^2.0.0",
    "primereact": "^3.4.0",
    "react-transition-group": "^4.3.0"
  }
}

My .babelrc file:

{
    "presets": ["env"],
    "plugins": [
      "transform-object-rest-spread",
      "transform-react-jsx",
      "react-hot-loader/babel"
    ]
  }

I followed this article to create and publish npm package:
https://codeburst.io/extracting-a-react-js-component-and-publishing-it-on-npm-2a49096757f5

How to solve this error?


问:
Remeshing of a triangular mesh for making high quality Delaunay triangulation?
I have a triangular mesh of the brain surface. I want to remesh it to a high-quality Delaunay triangulation. I'm seeking an easy and straightforward method. </p>

答:
pygalmesh interfaces CGAL and has surface remeshing. Install CGAL, then install pygalmesh with

```<code>pip install pygalmesh
</code>```

Then you can use

```<code>pygalmesh-remesh-surface lion-head.off out.vtu -e 0.025 -a 25 -s 0.1 -d 0.001
</code>```

on the command line.

Body:
pygalmesh interfaces CGAL and has surface remeshing. Install CGAL, then install pygalmesh with

pip install pygalmesh

Then you can use

pygalmesh-remesh-surface lion-head.off out.vtu -e 0.025 -a 25 -s 0.1 -d 0.001

on the command line.


问:
modify width of processing div
I have this div that appears on loading pages:

```<code><div id="divProcessing" style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background-color: transparent;  z-Index: 2000;overflow:hidden; display:none;border:none;"/>
</code>```

My problem is that on a page that has scroll bars the div is not expanded on all the page, only on screen size and i can access the content behind the div if i scroll.

I don't know how to expand or how to calculate the width/height of content page

答:
I would use jquery, and you can get the height of the body element.

```<code>$(body).css('height');
</code>```

So you could then do the following:

```<code>$('#divProcessing').css('height', $(body).css('height') );
</code>```

Which then sets your div's height to the same as the body of your page.

Edit: You mentioned width specifically but I was thinking height, the same will work for width, just replace 'height' with 'width'

Title: modify width of processing div

Body:
I have this div that appears on loading pages:

My problem is that on a page that has scroll bars the div is not expanded on all the page, only on screen size and i can access the content behind the div if i scroll.

I don't know how to expand or how to calculate the width/height of content page

Body:
I would use jquery, and you can get the height of the body element.

$(body).css('height');

So you could then do the following:

$('#divProcessing').css('height', $(body).css('height') );

Which then sets your div's height to the same as the body of your page.

Edit: You mentioned width specifically but I was thinking height, the same will work for width, just replace 'height' with 'width'


问:
keyListener does not recognise input
I have a KeyListener on an editText like so:

```<code>tip = (EditText) findViewById(R.id.tip);
tip.setOnKeyListener(new EditText.OnKeyListener(){
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        Log.i("debug123", "onKeyListener. event.getKeyCode(): " + event.getKeyCode());

        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            checkInput();
            return true;
        }
        return false;
    }
});
</code>```

But no softkeyboard-stroke is recognised.?
Only when I left the Activity with the BACK-Button (HardwareButton) the Listener recognises the action.
But from all that I read, this is the way to go if I want to work with user-input at a EditText.

答:
setOnKeyListener

Register a callback to be invoked when a hardware key is pressed in
this view. Key presses in software input methods will generally not
trigger the methods of this listener.

setOnEditorActionListener

Set a special listener to be called when an action is performed on the
text view.  This will be called when the enter key is pressed, or when
an action supplied to the IME is selected by the user.

To solve your problem using setOnEditorActionListener, please check below:

Add imeOptions and inputType to your EditText

```<code><EditText
    android:id="@+id/tip"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</code>```

Then add setOnEditorActionListener to EditText

```<code>tip.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if ( (actionId == EditorInfo.IME_ACTION_DONE) || (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) ) {
            checkInput();
            return true;
        } else {
            return false;
        }
    }
});
</code>```

Here,

actionId == EditorInfo.IME_ACTION_DONE handle action from Soft Keyboard (IME)

event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN handle enter key from Hardware Keyboard

Title: keyListener does not recognise input

Body:
I have a KeyListener on an editText like so:

tip = (EditText) findViewById(R.id.tip);
tip.setOnKeyListener(new EditText.OnKeyListener(){
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        Log.i("debug123", "onKeyListener. event.getKeyCode(): " + event.getKeyCode());

        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            checkInput();
            return true;
        }
        return false;
    }
});

But no softkeyboard-stroke is recognised.?
Only when I left the Activity with the BACK-Button (HardwareButton) the Listener recognises the action.
But from all that I read, this is the way to go if I want to work with user-input at a EditText.

Body:
setOnKeyListener

Register a callback to be invoked when a hardware key is pressed in
this view. Key presses in software input methods will generally not
trigger the methods of this listener.

setOnEditorActionListener

Set a special listener to be called when an action is performed on the
text view.  This will be called when the enter key is pressed, or when
an action supplied to the IME is selected by the user.

To solve your problem using setOnEditorActionListener, please check below:

Add imeOptions and inputType to your EditText

<EditText
    android:id="@+id/tip"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

Then add setOnEditorActionListener to EditText

tip.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if ( (actionId == EditorInfo.IME_ACTION_DONE) || (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) ) {
            checkInput();
            return true;
        } else {
            return false;
        }
    }
});

Here,

actionId == EditorInfo.IME_ACTION_DONE handle action from Soft Keyboard (IME)

event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN handle enter key from Hardware Keyboard


问:
What is the fastest way to merge N unsorted arrays into 1 sorted array in JavaScript?
I'm having trouble merging N unsorted arrays into 1 sorted array in JavaScript.

I know I can quickly concat then sort, but efficiency is important here.

I have arrays I'm getting back from an api (I can't ensure they arrive sorted) that need to end up in 1 sorted array. My first instinct was to try and not reinvent the wheel and try to find a way to reliably sort these into an output array. I figured I would try to sort each one, and then take advantage of the algorithm on GeeksForGeeks. This requires the arrays to be in sorted order, so I sort the arrays first individually

I haven't spent much time in C++, so I spent some time trying to reimplement this in JavaScript:

const TinyQueue = require('tinyqueue'); // const Heap = require('heap');

//typedef pair<int, pair<int, int> > ppi;
const pair = (val1, val2) => ({ first: val1, second: val2 });
const ppi = (val1, [val2a, val2b]) => pair(val1, pair(val2a, val2b));
//console.log(ppi('a', ['b', 'c'])) -> { first: 'a', second: { first: 'b', second: 'c' } }

// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted. It merges them together and prints
// the final sorted output.
function mergeKArrays(arr) {
  const output = [];
  queue = new TinyQueue();

  for (var i = 0, len = arr.length; i < len; i++) queue.push(ppi(arr[i][0], [i, 0]));

  while(queue.length) {
    let curr = queue.pop();
    // i ==> Array Number
    // j ==> Index in the array number
    let i = curr.second.first;
    let j = curr.second.second;

    output.unshift(curr.first);

    // The next element belongs to same array as current.
    if (j + 1 < arr[i].length) queue.push(ppi( arr[i][j + 1], [ i, j + 1]));
  }

  return output;
}
// -- Test Data --
const unsortedArrays = [
  [12, 2, 6],
  [9, 1],
  [2000, 23, 34, 90]
];
const sortedArrays = unsortedArrays.map(array => array.sort((a,b) => a - b));

console.log(sortedArrays);
const mergedArr = mergeKArrays(sortedArrays);

console.log(mergedArr);
```

The Geeks for Geeks algorithm. This code shared on repl.it.

So the input is [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ]

Expected output is [ 1, 2, 6, 9, 12, 23, 34, 90, 2000 ]

Actual output is [ 9, 2000, 1, 90, 12, 34, 6, 23, 2 ]

What is going wrong here? If this worked, is there a more efficient way to merge N unsorted arrays into 1 sorted one?

答:
V8 uses Timsort, which takes advantage of natural runs. So, you can flat and sort:

const unsortedArrays = [
  [12, 2, 6],
  [9, 1],
  [2000, 23, 34, 90]
];
const sorted = unsortedArrays.flat().sort((a, b) => a - b);
console.info(sorted);```

Body:
I'm having trouble merging N unsorted arrays into 1 sorted array in JavaScript.

I know I can quickly concat then sort, but efficiency is important here.

I have arrays I'm getting back from an api (I can't ensure they arrive sorted) that need to end up in 1 sorted array. My first instinct was to try and not reinvent the wheel and try to find a way to reliably sort these into an output array. I figured I would try to sort each one, and then take advantage of the algorithm on GeeksForGeeks. This requires the arrays to be in sorted order, so I sort the arrays first individually

I haven't spent much time in C++, so I spent some time trying to reimplement this in JavaScript:

const TinyQueue = require('tinyqueue'); // const Heap = require('heap');

//typedef pair<int, pair<int, int> > ppi;
const pair = (val1, val2) => ({ first: val1, second: val2 });
const ppi = (val1, [val2a, val2b]) => pair(val1, pair(val2a, val2b));
//console.log(ppi('a', ['b', 'c'])) -> { first: 'a', second: { first: 'b', second: 'c' } }

// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted. It merges them together and prints
// the final sorted output.
function mergeKArrays(arr) {
  const output = [];
  queue = new TinyQueue();

  for (var i = 0, len = arr.length; i < len; i++) queue.push(ppi(arr[i][0], [i, 0]));

  while(queue.length) {
    let curr = queue.pop();
    // i ==> Array Number
    // j ==> Index in the array number
    let i = curr.second.first;
    let j = curr.second.second;

    output.unshift(curr.first);

    // The next element belongs to same array as current.
    if (j + 1 < arr[i].length) queue.push(ppi( arr[i][j + 1], [ i, j + 1]));
  }

  return output;
}
// -- Test Data --
const unsortedArrays = [
  [12, 2, 6],
  [9, 1],
  [2000, 23, 34, 90]
];
const sortedArrays = unsortedArrays.map(array => array.sort((a,b) => a - b));

console.log(sortedArrays);
const mergedArr = mergeKArrays(sortedArrays);

console.log(mergedArr);

The Geeks for Geeks algorithm. This code shared on repl.it.

So the input is [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ]

Expected output is [ 1, 2, 6, 9, 12, 23, 34, 90, 2000 ]

Actual output is [ 9, 2000, 1, 90, 12, 34, 6, 23, 2 ]

What is going wrong here? If this worked, is there a more efficient way to merge N unsorted arrays into 1 sorted one?


问:
adding two button which shows different messages when pressed ( only in html )
Can someone please help me create a 4 different button which shows the different messages when pressed individually.

However with the below coding I am using now,  when I press the button2 it shows the same message as button1 even thou the Button2 have its own message.

Please note I can only use the HTML codes as I am using this code on html only enabled page. Please help.

答:
Are you expecting something like this ?

.alert {
 display: none;
 padding: 20px;
 background-color: #f44336;
 color: white;
}

.closebtn {
 margin-left: 15px;
 color: white;
 font-weight: bold;
 float: right;
 font-size: 22px;
 line-height: 20px;
 cursor: pointer;
 transition: 0.3s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="document.getElementById('alert1').style.display='block'">Buton1</button>
<div id="alert1" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span> message1
</div>

<button onclick="document.getElementById('alert2').style.display='block'">Buton2</button>
<div id="alert2" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span> message2
</div>

<button onclick="document.getElementById('alert3').style.display='block'">Buton3</button>
<div id="alert3" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span> message3
</div>

<button onclick="document.getElementById('alert4').style.display='block'">Buton4</button>
<div id="alert4" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span> message4
</div></code>```

Create div element with unqiue id and add event listener on them, and add common class to style them

Update

you can also write javascript like below in html file

```<code><html>
 <script>
  console.log('Javascript works here');
 </script>
</html>
</code>```

Update 2

I have created a much cleaner way of your requirement (but using script tag)

.alert {
 display: none;
 padding: 20px;
 background-color: #f44336;
 color: white;
}

.closebtn {
 margin-left: 15px;
 color: white;
 font-weight: bold;
 float: right;
 font-size: 22px;
 line-height: 20px;
 cursor: pointer;
 transition: 0.3s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button data-msg-id="alert1">Buton1</button>
  <button data-msg-id="alert2">Buton2</button>
  <button data-msg-id="alert3">Buton3</button>
  <button data-msg-id="alert4">Buton4</button>

  <div id="alert1" class="alert">
   <span class="closebtn">×</span> message1
  </div>
  <div id="alert2" class="alert">
   <span class="closebtn">×</span> message2
  </div>
  <div id="alert3" class="alert">
   <span class="closebtn">×</span> message3
  </div>
  <div id="alert4" class="alert">
   <span class="closebtn">×</span> message4
  </div>

  <script>
    console.clear();
    const buttonsList = document.querySelectorAll('button'), closeBtnList = document.querySelectorAll('.closebtn');
    buttonsList.forEach(each => each.addEventListener('click', handleBtnClick));
    closeBtnList.forEach(each => each.addEventListener('click', handleCloseBtnClick));

    function handleBtnClick(evt) {
      document.querySelectorAll('.alert').forEach(each => each.style.display = 'none');
      document.querySelector('#'+evt.target.dataset.msgId).style.display = 'block';
    }

    function handleCloseBtnClick(evt) {
      evt.target.parentElement.style.display = 'none';
    }
  </script></code>```

Body:
Are you expecting something like this ?

.alert {
 display: none;
 padding: 20px;
 background-color: #f44336;
 color: white;
}

.closebtn {
 margin-left: 15px;
 color: white;
 font-weight: bold;
 float: right;
 font-size: 22px;
 line-height: 20px;
 cursor: pointer;
 transition: 0.3s;
}

<button onclick="document.getElementById('alert1').style.display='block'">Buton1</button>
<div id="alert1" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> message1
</div>

<button onclick="document.getElementById('alert2').style.display='block'">Buton2</button>
<div id="alert2" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> message2
</div>

<button onclick="document.getElementById('alert3').style.display='block'">Buton3</button>
<div id="alert3" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> message3
</div>

<button onclick="document.getElementById('alert4').style.display='block'">Buton4</button>
<div id="alert4" class="alert">
   <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> message4
</div>

Create div element with unqiue id and add event listener on them, and add common class to style them

Update

you can also write javascript like below in html file

<html>
 <script>
  console.log('Javascript works here');
 </script>
</html>

Update 2

I have created a much cleaner way of your requirement (but using script tag)

.alert {
 display: none;
 padding: 20px;
 background-color: #f44336;
 color: white;
}

.closebtn {
 margin-left: 15px;
 color: white;
 font-weight: bold;
 float: right;
 font-size: 22px;
 line-height: 20px;
 cursor: pointer;
 transition: 0.3s;
}

<button data-msg-id="alert1">Buton1</button>
  <button data-msg-id="alert2">Buton2</button>
  <button data-msg-id="alert3">Buton3</button>
  <button data-msg-id="alert4">Buton4</button>

  <div id="alert1" class="alert">
   <span class="closebtn">&times;</span> message1
  </div>
  <div id="alert2" class="alert">
   <span class="closebtn">&times;</span> message2
  </div>
  <div id="alert3" class="alert">
   <span class="closebtn">&times;</span> message3
  </div>
  <div id="alert4" class="alert">
   <span class="closebtn">&times;</span> message4
  </div>

  <script>
    console.clear();
    const buttonsList = document.querySelectorAll('button'), closeBtnList = document.querySelectorAll('.closebtn');
    buttonsList.forEach(each => each.addEventListener('click', handleBtnClick));
    closeBtnList.forEach(each => each.addEventListener('click', handleCloseBtnClick));

    function handleBtnClick(evt) {
      document.querySelectorAll('.alert').forEach(each => each.style.display = 'none');
      document.querySelector('#'+evt.target.dataset.msgId).style.display = 'block';
    }

    function handleCloseBtnClick(evt) {
      evt.target.parentElement.style.display = 'none';
    }
  </script>


问:
Python/Pandas - Writing empty cells to a csv file (instead of zeros)
Running Python 3.8.1, 64 bit, on Windows 10.

I have a csv file with two columns. The first column does not have numeric values on every row (=empty cells in between cells with values) and second has numeric values on every row.

```<code>column_1 column_2
         200
13       201
         202
         203
         204
         205
129      206
16       207
         208
</code>```

I read the csv file (shown above) with Pandas:

```<code>df = pd.read_csv("old.csv")
</code>```

I make modifications to the Pandas dataframe and write to a new csv file with Pandas without the index column.

```<code>df.to_csv("new.csv", sep=',', encoding='utf-8', index=False)
</code>```

The result is a csv file that has zeros in place of the original empty cells.

```<code>column_1,column_2
0,200
13,201
0,202
0,203
0,204
0,205
129,206
16,207
0,208
</code>```

My question: how to modify my script to write empty cells instead of zeros (0) in the csv file (i.e. the rows where column_2 value is 200, 202, 203, 204, 205 and 208)?

Body:
Running Python 3.8.1, 64 bit, on Windows 10.

I have a csv file with two columns. The first column does not have numeric values on every row (=empty cells in between cells with values) and second has numeric values on every row.

column_1 column_2
         200
13       201
         202
         203
         204
         205
129      206
16       207
         208

I read the csv file (shown above) with Pandas:

df = pd.read_csv("old.csv")

I make modifications to the Pandas dataframe and write to a new csv file with Pandas without the index column.

df.to_csv("new.csv", sep=',', encoding='utf-8', index=False)

The result is a csv file that has zeros in place of the original empty cells.

column_1,column_2
0,200
13,201
0,202
0,203
0,204
0,205
129,206
16,207
0,208

My question: how to modify my script to write empty cells instead of zeros (0) in the csv file (i.e. the rows where column_2 value is 200, 202, 203, 204, 205 and 208)?

Body:
You can set 0 to missing values by Series.mask and for integers, convert the output to Int64, working in pandas 0.24+:

df = pd.DataFrame({'column_1': [0, 13, 0, 0, 0, 0, 129, 16, 0],
                   'column_2': [200, 201, 202, 203, 204, 205, 206, 207, 208]})
print (df)
   column_1  column_2
0         0       200
1        13       201
2         0       202
3         0       203
4         0       204
5         0       205
6       129       206
7        16       207
8         0       208

df['column_1'] = df['column_1'].mask(df['column_1'].eq(0)).astype('Int64')
print (df)
   column_1  column_2
0       NaN       200
1        13       201
2       NaN       202
3       NaN       203
4       NaN       204
5       NaN       205
6       129       206
7        16       207
8       NaN       208

df.to_csv("new.csv", sep=',', encoding='utf-8', index=False)

column_1,column_2
,200
13,201
,202
,203
,204
,205
129,206
16,207
,208

Another idea is to replace the empty strings:

df['column_1'] = df['column_1'].mask(df['column_1'].eq(0), '')
print (df)
  column_1  column_2
0                200
1       13       201
2                202
3                203
4                204
5                205
6      129       206
7       16       207
8                208

df.to_csv("new.csv", sep=',', encoding='utf-8', index=False)

column_1,column_2
,200
13,201
,202
,203
,204
,205
129,206
16,207
,208


问:
Remove duplicates from rows in mydataset
Im having a CSV file which contain 436 columns and 14k rows.
The format of the data inside the cells is string.
For the example it looks like this:

```<code>A,A,A,B,B,C,C,,,,,
D,F,D,F,D,F,H,,,,,
</code>```

My goal is to get every row with its unique values only. Like that:

```<code>A,B,C,,,,,,,,
D,F,H,,,,,,,,
</code>```

The file is on csv/txt file. I can use Jupyter notebook( with Python3 or any other code you guys will provide). But this is my enviorment of work. Any help would be amazing!
I also uploaded the csv as a Dataframe to the notebook. What you guys suggest?

答:
If you have the csv loaded as a dataframe df:

```<code>    0   1   2   3   4   5   6
0   A   A   A   B   B   C   C
1   D   F   D   F   D   F   H
</code>```

Iterate over rows and find the unique values per each row:

```<code>unique_vals = []
for _, row in df.iterrows():
    unique_vals.append(row.unique().tolist())
unique_vals

[['A', 'B', 'C'], ['D', 'F', 'H']]
</code>```

You haven't mentioned the return data type so I've returned a list.

Edit: If the data set is too large, consider using the chunk_size option in read_csv.

Body:
Im having a CSV file which contain 436 columns and 14k rows.
The format of the data inside the cells is string.
For the example it looks like this:

A,A,A,B,B,C,C,,,,,
D,F,D,F,D,F,H,,,,,

My goal is to get every row with its unique values only. Like that:

A,B,C,,,,,,,,
D,F,H,,,,,,,,

The file is on csv/txt file. I can use Jupyter notebook( with Python3 or any other code you guys will provide). But this is my enviorment of work. Any help would be amazing!
I also uploaded the csv as a Dataframe to the notebook. What you guys suggest?

Body:
If you have the csv loaded as a dataframe df:

    0   1   2   3   4   5   6
0   A   A   A   B   B   C   C
1   D   F   D   F   D   F   H

Iterate over rows and find the unique values per each row:

unique_vals = []
for _, row in df.iterrows():
    unique_vals.append(row.unique().tolist())
unique_vals

[['A', 'B', 'C'], ['D', 'F', 'H']]

You haven't mentioned the return data type so I've returned a list.

Edit: If the data set is too large, consider using the chunk_size option in read_csv.


问:
How would I remove non-duplicates from a CSV file in Python?
I have a CSV file with the following format:

```<code>User1, User2
1,2
1,3
2,1
</code>```

I am trying to remove the non-duplicated reverse values, so in this instance I would like to remove 1,3 as it doesn't have a reverse duplicate of 3,1

I currently have this script which removes the duplicate values:

```<code>import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

entries = set()

for row in reader:
   key = (row[0], row[1])
   key = tuple(key)
   if key in entries and key[::-1] in entries:
       writer.writerow(row)
       entries.add(key)
</code>```

How would I edit this script to remove the non-duplicated reverse values? So that I am only left with

```<code>1,2
2,1
</code>```

Thanks

答:
Question: Remove non-duplicates from a CSV file?

First aggregate the data using the sum(...) of the data as key

Loop the aggregated data and write only if more than one aggregated in a specific key.

```<code>reader = [('1','2'), ('1','3'), ('2','1')]
data_counter = {}

for row in reader:
    key = sum([int(v) for v in row])
    data_counter.setdefault(key, []).append(row)

print(data_counter)

for value in data_counter.values():
    if len(value) == 1:
        print('non duplicate {}'.format(value))
    else:
        # writer.writerows(value)
        print('writer.writerows({})'.format(value))
</code>```

Output:

```<code>{3: [('1', '2'), ('2', '1')], 4: [('1', '3')]}

writer.writerows([('1', '2'), ('2', '1')])
non duplicate [('1', '3')]
</code>```

Body:
I have a CSV file with the following format:

User1, User2
1,2
1,3
2,1

I am trying to remove the non-duplicated reverse values, so in this instance I would like to remove 1,3 as it doesn't have a reverse duplicate of 3,1

I currently have this script which removes the duplicate values:

import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

entries = set()

for row in reader:
   key = (row[0], row[1])
   key = tuple(key)
   if key in entries and key[::-1] in entries:
       writer.writerow(row)
       entries.add(key)

How would I edit this script to remove the non-duplicated reverse values? So that I am only left with

1,2
2,1

Thanks

Body:
Question: Remove non-duplicates from a CSV file?

First aggregate the data using the sum(...) of the data as key

Loop the aggregated data and write only if more than one aggregated in a specific key.

reader = [('1','2'), ('1','3'), ('2','1')]
data_counter = {}

for row in reader:
    key = sum([int(v) for v in row])
    data_counter.setdefault(key, []).append(row)

print(data_counter)

for value in data_counter.values():
    if len(value) == 1:
        print('non duplicate {}'.format(value))
    else:
        # writer.writerows(value)
        print('writer.writerows({})'.format(value))

Output:

{3: [('1', '2'), ('2', '1')], 4: [('1', '3')]}

writer.writerows([('1', '2'), ('2', '1')])
non duplicate [('1', '3')]


问:
Error: Highcharts error #13: www.highcharts.com/errors/13/ in Reactjs
I am trying to use High-charts in reactjs and I am new to both these. In the beginning, everything was fine but now I am unable to solve this error.

The following is my code:

```<code>Array.prototype.contains = function (v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};

Array.prototype.unique = function () {
  var arr = [];
  for (var i = 0; i < this.length; i++) {
    if (!arr.contains(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
}
export default class Chart extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      installs: [],
      isLoaded: false,
    }

    this.state = {
      filteredData: [],
      isLoadedFilteredData: false,
      showChart: true
    }

    this.state = {
      options: {}
    }

  }

  componentDidMount() {
    //  setInterval(() => {
    fetch('xyz)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          installs: json,

        });

      });

  }

  getFilteredData = async (operatingSystem, applicationServer, database, cloud, serverRelease) => {

    fetch(`xyz`)
      .then(res => res.json())
      .then(json => {
       // console.log(json);
        this.setState({
          isLoadedFilteredData: true,
          filteredData: json,
        }, console.log("getFilteredData called ... "));

      });

  }

  handleChange = ({ altered, name, text, value }) => {
    const nextFormValue = {
      [name]: {
        text,
        value,
        altered
      }
    };

    this.setState({ ...this.state, ...nextFormValue }, () =>

      console.log("handleChange()", this.state),

    );

  };

  render() {

    const { isLoaded, installs } = this.state;
    const { isLoadedFilteredData, filteredData } = this.state;

    if (!isLoaded) {
      return <p>Loading...</p>;
    }
    else {

      var arrayOS = []
      var arrayApp = []
      var arrayDB = []
      var arrayCloud = []
      var arrayServerRelease = []

      for (var i = 0; i < installs.length; i++) {

        arrayOS.push(this.state.installs[i].object.hardwareStackDetails.operatingSystem)
        arrayApp.push(this.state.installs[i].object.hardwareStackDetails.applicationServer)
        arrayDB.push(this.state.installs[i].object.hardwareStackDetails.database)
        arrayCloud.push(this.state.installs[i].object.cloud)
        arrayServerRelease.push(this.state.installs[i].object.serverRelease)

      }

      var operatingSystemTemp = arrayOS.unique();
      var applicationServerTemp = arrayApp.unique();
      var dataBaseTemp = arrayDB.unique();
      var cloudTemp = arrayCloud.unique();
      var serverReleaseTemp = arrayServerRelease.unique();

      arrayOS = []
      arrayApp = []
      arrayDB = []
      arrayCloud = []
      arrayServerRelease = []

      for (var i = 0; i < operatingSystemTemp.length; i++) {
        arrayOS.push({
          text: operatingSystemTemp[i],
          value: operatingSystemTemp[i]
        })
      }
      for (var i = 0; i < applicationServerTemp.length; i++) {
        arrayApp.push({
          text: applicationServerTemp[i],
          value: applicationServerTemp[i]
        })
      }
      for (var i = 0; i < dataBaseTemp.length; i++) {
        arrayDB.push({
          text: dataBaseTemp[i],
          value: dataBaseTemp[i],

        })
      }
      for (var i = 0; i < cloudTemp.length; i++) {
        arrayCloud.push({
          text: cloudTemp[i],
          value: cloudTemp[i]
        })
      }
      for (var i = 0; i < serverReleaseTemp.length; i++) {
        arrayServerRelease.push({
          text: serverReleaseTemp[i],
          value: serverReleaseTemp[i]
        })
      }

      if (isLoadedFilteredData){
      if(filteredData.length === 0) {

        console.log("filteredData")

        mapNew = new Map();
        labelMap = {};
        xlabels = []
        seriesDataValue = []

        Highcharts.chart('container', {

          title: {
             text: ''
          },

          subtitle: {
            // text: 'Source: thesolarfoundation.com'
          },

          xAxis: {

            categories: xlabels
          },

          legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
          },

          series: seriesDataValue,

          responsive: {
            rules: [{
              condition: {
                maxWidth: 500
              },
              chartOptions: {
                legend: {
                  layout: 'horizontal',
                  align: 'center',
                  verticalAlign: 'bottom'
                }
              }
            }]
          }

        }
        );

      }
      else {

          console.log(filteredData)

          var mapNew = new Map();
          var labelMap = {};
          var xlabels = []
          var seriesDataValue = []

          for (var j = 0; j < filteredData.length; j++) {

            if (filteredData[j].object.status === "PASS") {

              var date1 = moment(filteredData[j].object.creationTime);
              var date2 = moment(filteredData[j].object.updationTime);

              var ms = moment(date2, "DD/MM/YYYY HH:mm:ss").diff(moment(date1, "DD/MM/YYYY HH:mm:ss"));
              var d = moment.duration(ms);
              //  var s = d.format("hh:mm:ss");

              console.log(ms)
              console.log(d.hours())

              var timeInhrs = d.hours()

              if (mapNew.has(filteredData[j].object.clientBuild)) {

                //    timeInhrs = ((timeInhrs + mapNewInnerTemp.get(this.state.kuch[j].object.clientBuild)));

                console.log(this.state.filteredData[j].object.clientBuild + "  " + timeInhrs);
                mapNew.set(this.state.filteredData[j].object.clientBuild, timeInhrs);

              } else {
                console.log(this.state.filteredData[j].object.clientBuild + "  " + timeInhrs);

                mapNew.set(this.state.filteredData[j].object.clientBuild, timeInhrs);

                labelMap[this.state.filteredData[j].object.clientBuild] = 0; ///

                //count = count + 1;

              }

            }
          }
          console.log(mapNew)

          for (var key in labelMap) {

            xlabels.push(key);
          }

          console.log(xlabels)

          var dataValue = [] // array
          for (const entry of mapNew.entries()) {

            console.log(entry)

            for (var key in labelMap) {

              if (key === entry[0]) {

                dataValue.push(entry[1])
              }

            }

          }
          console.log(dataValue)

          seriesDataValue.push(
            {

              data: dataValue,

            })

          console.log(seriesDataValue)

          var elementExists = document.getElementById("container");
          if(elementExists === null){
            let div = document.createElement("div");
            div.id="container";
            div.id="select"
            document.body.appendChild(div);
          }

          Highcharts.chart('container',

            xAxis: {

              categories: xlabels
            },

            legend: {
              layout: 'vertical',
              align: 'right',
              verticalAlign: 'middle'
            },

            series: seriesDataValue,

            responsive: {
              rules: [{
                condition: {
                  maxWidth: 500
                },
                chartOptions: {
                  legend: {
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: 'bottom'
                  }
                }
              }]
            }

          }
          );

        }

    }

      return (
        <div>

          <div id="container"> </div>

        </div>
      );

    }

  }

}

</code>```

The above error gets vanished after the page gets refreshed .

答:
The error results from the fact that you create a chart before a div element with the 'container' id is created.

However, to avoid such problems I recommend you to use officially supported Highcharts wrapper for React: https://www.npmjs.com/package/highcharts-react-official

Body:
I am trying to use High-charts in reactjs and I am new to both these. In the beginning, everything was fine but now I am unable to solve this error.

The following is my code:

Array.prototype.contains = function (v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};

Array.prototype.unique = function () {
  var arr = [];
  for (var i = 0; i < this.length; i++) {
    if (!arr.contains(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
}
export default class Chart extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      installs: [],
      isLoaded: false,
    }

    this.state = {
      filteredData: [],
      isLoadedFilteredData: false,
      showChart: true
    }

    this.state = {
      options: {}
    }

  }

  componentDidMount() {
    //  setInterval(() => {
    fetch('xyz)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          installs: json,

        });

      });

  }

  getFilteredData = async (operatingSystem, applicationServer, database, cloud, serverRelease) => {

    fetch(`xyz`)
      .then(res => res.json())
      .then(json => {
       // console.log(json);
        this.setState({
          isLoadedFilteredData: true,
          filteredData: json,
        }, console.log("getFilteredData called ... "));

      });

  }

  handleChange = ({ altered, name, text, value }) => {
    const nextFormValue = {
      [name]: {
        text,
        value,
        altered
      }
    };

    this.setState({ ...this.state, ...nextFormValue }, () =>

      console.log("handleChange()", this.state),

    );

  };

  render() {

    const { isLoaded, installs } = this.state;
    const { isLoadedFilteredData, filteredData } = this.state;

    if (!isLoaded) {
      return
Loading...
;
    }
    else {

      var arrayOS = []
      var arrayApp = []
      var arrayDB = []
      var arrayCloud = []
      var arrayServerRelease = []

      for (var i = 0; i < installs.length; i++) {

        arrayOS.push(this.state.installs[i].object.hardwareStackDetails.operatingSystem)
        arrayApp.push(this.state.installs[i].object.hardwareStackDetails.applicationServer)
        arrayDB.push(this.state.installs[i].object.hardwareStackDetails.database)
        arrayCloud.push(this.state.installs[i].object.cloud)
        arrayServerRelease.push(this.state.installs[i].object.serverRelease)

      }

      var operatingSystemTemp = arrayOS.unique();
      var applicationServerTemp = arrayApp.unique();
      var dataBaseTemp = arrayDB.unique();
      var cloudTemp = arrayCloud.unique();
      var serverReleaseTemp = arrayServerRelease.unique();

      arrayOS = []
      arrayApp = []
      arrayDB = []
      arrayCloud = []
      arrayServerRelease = []

      for (var i = 0; i < operatingSystemTemp.length; i++) {
        arrayOS.push({
          text: operatingSystemTemp[i],
          value: operatingSystemTemp[i]
        })
      }
      for (var i = 0; i < applicationServerTemp.length; i++) {
        arrayApp.push({
          text: applicationServerTemp[i],
          value: applicationServerTemp[i]
        })
      }
      for (var i = 0; i < dataBaseTemp.length; i++) {
        arrayDB.push({
          text: dataBaseTemp[i],
          value: dataBaseTemp[i],

        })
      }
      for (var i = 0; i < cloudTemp.length; i++) {
        arrayCloud.push({
          text: cloudTemp[i],
          value: cloudTemp[i]
        })
      }
      for (var i = 0; i < serverReleaseTemp.length; i++) {
        arrayServerRelease.push({
          text: serverReleaseTemp[i],
          value: serverReleaseTemp[i]
        })
      }

      if (isLoadedFilteredData){
      if(filteredData.length === 0) {

        console.log("filteredData")

        mapNew = new Map();
        labelMap = {};
        xlabels = []
        seriesDataValue = []

        Highcharts.chart('container', {

          title: {
             text: ''
          },

          subtitle: {
            // text: 'Source: thesolarfoundation.com'
          },

          xAxis: {

            categories: xlabels
          },

          legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
          },

          series: seriesDataValue,

          responsive: {
            rules: [{
              condition: {
                maxWidth: 500
              },
              chartOptions: {
                legend: {
                  layout: 'horizontal',
                  align: 'center',
                  verticalAlign: 'bottom'
                }
              }
            }]
          }

        }
        );

      }
      else {

          console.log(filteredData)

          var mapNew = new Map();
          var labelMap = {};
          var xlabels = []
          var seriesDataValue = []

          for (var j = 0; j < filteredData.length; j++) {

            if (filteredData[j].object.status === "PASS") {

              var date1 = moment(filteredData[j].object.creationTime);
              var date2 = moment(filteredData[j].object.updationTime);

              var ms = moment(date2, "DD/MM/YYYY HH:mm:ss").diff(moment(date1, "DD/MM/YYYY HH:mm:ss"));
              var d = moment.duration(ms);
              //  var s = d.format("hh:mm:ss");

              console.log(ms)
              console.log(d.hours())

              var timeInhrs = d.hours()

              if (mapNew.has(filteredData[j].object.clientBuild)) {

                //    timeInhrs = ((timeInhrs + mapNewInnerTemp.get(this.state.kuch[j].object.clientBuild)));

                console.log(this.state.filteredData[j].object.clientBuild + "  " + timeInhrs);
                mapNew.set(this.state.filteredData[j].object.clientBuild, timeInhrs);

              } else {
                console.log(this.state.filteredData[j].object.clientBuild + "  " + timeInhrs);

                mapNew.set(this.state.filteredData[j].object.clientBuild, timeInhrs);

                labelMap[this.state.filteredData[j].object.clientBuild] = 0; ///

                //count = count + 1;

              }

            }
          }
          console.log(mapNew)

          for (var key in labelMap) {

            xlabels.push(key);
          }

          console.log(xlabels)

          var dataValue = [] // array
          for (const entry of mapNew.entries()) {

            console.log(entry)

            for (var key in labelMap) {

              if (key === entry[0]) {

                dataValue.push(entry[1])
              }

            }

          }
          console.log(dataValue)

          seriesDataValue.push(
            {

              data: dataValue,

            })

          console.log(seriesDataValue)

          var elementExists = document.getElementById("container");
          if(elementExists === null){
            let div = document.createElement("div");
            div.id="container";
            div.id="select"
            document.body.appendChild(div);
          }

          Highcharts.chart('container',

            xAxis: {

              categories: xlabels
            },

            legend: {
              layout: 'vertical',
              align: 'right',
              verticalAlign: 'middle'
            },

            series: seriesDataValue,

            responsive: {
              rules: [{
                condition: {
                  maxWidth: 500
                },
                chartOptions: {
                  legend: {
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: 'bottom'
                  }
                }
              }]
            }

          }
          );

        }

    }

      return (

      );

    }

  }

}

The above error gets vanished after the page gets refreshed .


问:
Remove comma only from number separators (regular expression grouping)
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

```<code>Hello, world! -> Hello, world!
</code>```

but

```<code>Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337
</code>```

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

答:
you need to capture the digits into group (\d+),(\d+)

```<code>import re

items = ['Hello, world!', 'Warhammer 40,000', 'Codename 1,337']

for item in items:
  item = re.sub(r'(\d+),(\d+)', r'\1\2', item)
  print(item)
</code>```

Results:

```<code>Hello, world!
Warhammer 40000
Codename 1337
</code>```

Body:
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

Hello, world! -> Hello, world!

but

Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

Body:
you need to capture the digits into group (\d+),(\d+)

import re

items = ['Hello, world!', 'Warhammer 40,000', 'Codename 1,337']

for item in items:
  item = re.sub(r'(\d+),(\d+)', r'\1\2', item)
  print(item)

Results:

Hello, world!
Warhammer 40000
Codename 1337


问:
SQL Error, unable to create table on a certain format
I am facing an error when creating a table  between the following two statement

```<code>CREATE TABLE SECTION (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
primary key (cid, sno),
foreign key (cid) references COURSE (cid)
);

CREATE TABLE ROUND_RELEASE (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
rid     int         not null,
foreign key (cid) references SECTION (cid),
foreign key (sno) references SECTION (sno),
foreign key (rid) references ROUND   (rid)
);
</code>```

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'round_release_ibfk_2' in the referenced table 'section'

However, when I try to swap the primary key order in SECTION table, I am able to create both table without error

```<code>CREATE TABLE SECTION (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
primary key (**sno, cid**),
foreign key (cid) references COURSE (cid)
);

CREATE TABLE ROUND_RELEASE (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
rid     int         not null,
foreign key (cid) references SECTION (cid),
foreign key (sno) references SECTION (sno),
foreign key (rid) references ROUND   (rid)
);
</code>```

The follow code above works, and I only swap the attribute, from my knowledge, the order does not matter, thus I am quite puzzled by why is this occurring.

Any guidance on this? Thanks!

答:
Based on the error message, I assume that you are using MySQL.

What you are seeing is a documented behavior:

In the referenced table, there must be an index where the referenced columns are the first columns in the same order.

Let me pinpoint, however, that your code probably does not do what you really want. You probably should be creating a compound foreign key, that references the tuples of columns, rather than one foreign key per column:

```<code>create table round_release (
    cid varchar(10) not null,
    sno varchar(3)  not null,
    rid int not null,
    foreign key (cid, sno) references section(cid, sno),
    foreign key (rid) references round(rid)
);
</code>```

One last thing to note is that your round_release table has no primary key defined; this is not a good practice, and might hurt you in several ways in the future. So, do create a primary key for the table, either as a separate column (possibly auto-incremented), or as a combination of existing columns.

Body:
I am facing an error when creating a table  between the following two statement

CREATE TABLE SECTION (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
primary key (cid, sno),
foreign key (cid) references COURSE (cid)
);

CREATE TABLE ROUND_RELEASE (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
rid     int         not null,
foreign key (cid) references SECTION (cid),
foreign key (sno) references SECTION (sno),
foreign key (rid) references ROUND   (rid)
);

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'round_release_ibfk_2' in the referenced table 'section'

However, when I try to swap the primary key order in SECTION table, I am able to create both table without error

CREATE TABLE SECTION (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
primary key (**sno, cid**),
foreign key (cid) references COURSE (cid)
);

CREATE TABLE ROUND_RELEASE (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
rid     int         not null,
foreign key (cid) references SECTION (cid),
foreign key (sno) references SECTION (sno),
foreign key (rid) references ROUND   (rid)
);

The follow code above works, and I only swap the attribute, from my knowledge, the order does not matter, thus I am quite puzzled by why is this occurring.

Any guidance on this? Thanks!

Body:
Based on the error message, I assume that you are using MySQL.

What you are seeing is a documented behavior:

In the referenced table, there must be an index where the referenced columns are the first columns in the same order.

Let me pinpoint, however, that your code probably does not do what you really want. You probably should be creating a compound foreign key, that references the tuples of columns, rather than one foreign key per column:

create table round_release (
    cid varchar(10) not null,
    sno varchar(3)  not null,
    rid int not null,
    foreign key (cid, sno) references section(cid, sno),
    foreign key (rid) references round(rid)
);

One last thing to note is that your round_release table has no primary key defined; this is not a good practice, and might hurt you in several ways in the future. So, do create a primary key for the table, either as a separate column (possibly auto-incremented), or as a combination of existing columns.


问:
Scipy semilogx: How to set label on each lines
I refer to

command, I tried:

```<code>plt.figure()
plt.semilogx(hs_001u_w,hs_001u_mag,color="red",label="u")
plt.semilogx(hs_01u_w,hs_01u_mag,color="blue",label="u1")
plt.grid()
plt.show()
</code>```

But result seems label="u" does not work:

semilogx's official docs does not mention how to add label for each lines,

maybe has but I have not found.

Does anyone knows?

答: As I commented, you must call plt.legend() somewhere in the code, before plt.show() to acutally show the labels.

Body:
I refer to

command, I tried:

plt.figure()
plt.semilogx(hs_001u_w,hs_001u_mag,color="red",label="u")
plt.semilogx(hs_01u_w,hs_01u_mag,color="blue",label="u1")
plt.grid()
plt.show()

But result seems label="u" does not work:

semilogx's official docs does not mention how to add label for each lines,

maybe has but I have not found.

Does anyone knows?


问:
How to display a 3D plot of a 3D array isosurface with mplot3D or similar
I have a 3-dimensional numpy array.  I'd like to display (in matplotlib) a nice 3D plot of an isosurface of this array (or more strictly, display an isosurface of the 3D scalar field defined by interpolating between the sample points).

matplotlib's mplot3D part provides nice 3D plot support, but (so far as I can see) its API doesn't have anything which will simply take a 3D array of scalar values and display an isosurface.  However, it does support displaying a collection of polygons, so presumably I could implement the marching cubes algorithm to generate such polygons.

It does seem quite likely that a scipy-friendly marching cubes has already been implemented somewhere and that I haven't found it, or that I'm missing some easy way of doing this.  Alternatively I'd welcome any pointers to other tools for visualising 3D array data easily usable from the Python/numpy/scipy world.

答:
Just to elaborate on my comment above, matplotlib's 3D plotting really isn't intended for something as complex as isosurfaces. It's meant to produce nice, publication-quality vector output for really simple 3D plots. It can't handle complex 3D polygons, so even if implemented marching cubes yourself to create the isosurface, it wouldn't render it properly.

However, what you can do instead is use mayavi (it's mlab API is a bit more convenient than directly using mayavi), which uses VTK to process and visualize multi-dimensional data.

As a quick example (modified from one of the mayavi gallery examples):

```<code>import numpy as np
from enthought.mayavi import mlab

x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
s = np.sin(x*y*z)/(x*y*z)

src = mlab.pipeline.scalar_field(s)
mlab.pipeline.iso_surface(src, contours=[s.min()+0.1*s.ptp(), ], opacity=0.3)
mlab.pipeline.iso_surface(src, contours=[s.max()-0.1*s.ptp(), ],)

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

Body:
Just to elaborate on my comment above, matplotlib's 3D plotting really isn't intended for something as complex as isosurfaces. It's meant to produce nice, publication-quality vector output for really simple 3D plots. It can't handle complex 3D polygons, so even if implemented marching cubes yourself to create the isosurface, it wouldn't render it properly.

However, what you can do instead is use mayavi (it's mlab API is a bit more convenient than directly using mayavi), which uses VTK to process and visualize multi-dimensional data.

As a quick example (modified from one of the mayavi gallery examples):

import numpy as np
from enthought.mayavi import mlab

x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
s = np.sin(x*y*z)/(x*y*z)

src = mlab.pipeline.scalar_field(s)
mlab.pipeline.iso_surface(src, contours=[s.min()+0.1*s.ptp(), ], opacity=0.3)
mlab.pipeline.iso_surface(src, contours=[s.max()-0.1*s.ptp(), ],)

mlab.show()


问:
How to Get first date and last date from given month in java?
We will pass month information in yyyyMM format.From that given input how i will get FirstDate and LastDate of that month?</p>

```<code>Input:-202002

OutPut Should be:-

First Date:- 2020-02-01,
Last Date:- 2020-02-29

DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
Date date = new Date();
System.out.println("First Date:- "+dateFormat.format(date));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
Date previousmonth = calendar.getTime();
System.out.println("LastDate:-"+dateFormat.format(previousmonth).toString());
</code>```

答:
You can use java 8 capabilities like TemporalAdjusters I think it May help you in your problem like the following

    public static void getFirstDayAndLastDayInMonth(String date){
        LocalDate monthOfYear=LocalDate.parse(new String(date+"01"),DateTimeFormatter.BASIC_ISO_DATE);
        LocalDate firstLocalDate=monthOfYear.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println(firstLocalDate);
        LocalDate lastLocalDate=monthOfYear.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println(lastLocalDate);
    }
```

<p>input <code>202002</code></p>

<p>output</p>

```2020-02-01
2020-02-29
```

and you can follow the following doc
it's a good start to learn more

Body:
We will pass month information in yyyyMM format.From that given input how i will get FirstDate and LastDate of that month?

Input:-202002

OutPut Should be:-

First Date:- 2020-02-01,
Last Date:- 2020-02-29

DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
Date date = new Date();
System.out.println("First Date:- "+dateFormat.format(date));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
Date previousmonth = calendar.getTime();
System.out.println("LastDate:-"+dateFormat.format(previousmonth).toString());

Body:
You can use java 8 capabilities like TemporalAdjusters I think it May help you in your problem like the following

    public static void getFirstDayAndLastDayInMonth(String date){
        LocalDate monthOfYear=LocalDate.parse(new String(date+"01"),DateTimeFormatter.BASIC_ISO_DATE);
        LocalDate firstLocalDate=monthOfYear.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println(firstLocalDate);
        LocalDate lastLocalDate=monthOfYear.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println(lastLocalDate);
    }

input 202002

output

2020-02-01
2020-02-29

and you can follow the following doc
it's a good start to learn more


答:
You're running into an issue with precision and floating point arithmetic at that scale. There's a load more information available at Is floating point math broken? if you're interested, but I don't think this quite counts as a duplicate of that.

Taking your first two numbers:

```<code>php > var_dump((float) 98602142989816970 === (float) 98602142989816971);
bool(true)

php > var_dump((float) 98602142989816970, (float) 98602142989816971);
float(9.8602142989817E+16)
float(9.8602142989817E+16)
</code>```

Internally, this is what's happening when PHP compares the values in your array using SORT_NUMERIC, deep down in numeric_compare_function.

sort suffers from the same issue, see https://3v4l.org/02UUB (Obviously no values are removed from the array since that only happens in array_unique - they just aren't sorted properly)

In short, with numbers this size (or specifically numbers that are very close together relative to their scale), SORT_NUMERIC isn't going to be reliable. Stick with comparing them as strings if you can.

Title: array_unique with SORT_NUMBERIC behaviour

Body:
I've stumbled upon something weird and I don't understand why it works that way.

I have an array of numbers, they are all unique:

$array = [
    98602142989816970,
    98602142989816971,
    98602142989816980,
    98602142989816981,
    98602142989816982,
    98602142989816983,
    98602142989820095,
    98602142989820096,
    98602142989822060,
    98602142989822061,
];
var_dump($array);

array(10) {
  [0]=>
  int(98602142989816970)
  [1]=>
  int(98602142989816971)
  [2]=>
  int(98602142989816980)
  [3]=>
  int(98602142989816981)
  [4]=>
  int(98602142989816982)
  [5]=>
  int(98602142989816983)
  [6]=>
  int(98602142989820095)
  [7]=>
  int(98602142989820096)
  [8]=>
  int(98602142989822060)
  [9]=>
  int(98602142989822061)
}

If I do print_r(array_unique($array)); everything is fine, I get:

Array
(
    [0] => 98602142989816970
    [1] => 98602142989816971
    [2] => 98602142989816980
    [3] => 98602142989816981
    [4] => 98602142989816982
    [5] => 98602142989816983
    [6] => 98602142989820095
    [7] => 98602142989820096
    [8] => 98602142989822060
    [9] => 98602142989822061
)

But If I add SORT_NUMERIC flag print_r(array_unique($array, SORT_NUMERIC)); I get:

Array
(
    [0] => 98602142989816970
    [6] => 98602142989820095
    [8] => 98602142989822060
)

Why only those 3 numbers are returned?

update: I'm on 64-bit system.

For sort functions I've manually shuffled some of the values because in original array they are already sorted.

If I do sort($array); then response is as expected:

Array
(
    [0] => 98602142989816970
    [1] => 98602142989816971
    [2] => 98602142989816980
    [3] => 98602142989816981
    [4] => 98602142989816982
    [5] => 98602142989816983
    [6] => 98602142989820095
    [7] => 98602142989820096
    [8] => 98602142989822060
    [9] => 98602142989822061
)

But with sort($array, SORT_NUMERIC);, they are sorted incorrectly:

Array
(
    [0] => 98602142989816970
    [1] => 98602142989816982
    [2] => 98602142989816983
    [3] => 98602142989816980
    [4] => 98602142989816981
    [5] => 98602142989816971
    [6] => 98602142989820095
    [7] => 98602142989820096
    [8] => 98602142989822060
    [9] => 98602142989822061
)

Body:
You're running into an issue with precision and floating point arithmetic at that scale. There's a load more information available at Is floating point math broken? if you're interested, but I don't think this quite counts as a duplicate of that.

Taking your first two numbers:

php > var_dump((float) 98602142989816970 === (float) 98602142989816971);
bool(true)

php > var_dump((float) 98602142989816970, (float) 98602142989816971);
float(9.8602142989817E+16)
float(9.8602142989817E+16)

Internally, this is what's happening when PHP compares the values in your array using SORT_NUMERIC, deep down in numeric_compare_function.

sort suffers from the same issue, see https://3v4l.org/02UUB (Obviously no values are removed from the array since that only happens in array_unique - they just aren't sorted properly)

In short, with numbers this size (or specifically numbers that are very close together relative to their scale), SORT_NUMERIC isn't going to be reliable. Stick with comparing them as strings if you can.