问:
Critical error after pause in swift 0 thread 1: signal SIGABRT
I had a pause in my project - 1 month. I saved working version. Now when i try debug without any change, app dripping error on thread 1: signal SIGABRT with this:</p>

```<code>dyld: Library not loaded: @rpath/GTMSessionFetcher.framework/GTMSessionFetcher
  Referenced from: /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/BillyBill
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: code signature invalid for '/private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: stat() failed with errno=25
    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: code signature invalid for '/private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: stat() failed with errno=1
    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: code signature invalid for '/private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: stat() failed with errno=1
</code>```

答:
If you test your application on a physical device with iOS 13.3.1 and you are using podfile, it's a problem with a dynamic framework.
In your podfile comment the use_framework! line and run your pod install again.

Body:
I had a pause in my project - 1 month. I saved working version. Now when i try debug without any change, app dripping error on thread 1: signal SIGABRT with this:

dyld: Library not loaded: @rpath/GTMSessionFetcher.framework/GTMSessionFetcher
  Referenced from: /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/BillyBill
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: code signature invalid for '/private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: stat() failed with errno=25
    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: code signature invalid for '/private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: stat() failed with errno=1
    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: code signature invalid for '/private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

    /private/var/containers/Bundle/Application/1A1C365B-14A1-4438-9995-5622C7F9FAC3/BillyBill.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher: stat() failed with errno=1


来源: stackexchange

问:
Rewrite .htaccess resulting in 404
I'm trying to make my url look good but for some reasons it is not working what could be the problem here

```<code>RewriteEngine on
RewriteRule ^view/([^/]*)/([^/]*)$ /view?wall=$1&page=$2 [L]
</code>```

Above rewrite should resolve like this http://website.com/view/apartment-wallpapers/1247

Alternatively

Preferably I want to make my url to look like this but it's also resulting in

http://lifistudy.com/asus-red-903.html

.htaccess rewrite rule

```<code>RewriteEngine on
RewriteRule ^([^-]*)-([^-]*)\.html$ /view?wall=$1&page=$2 [L]
</code>```

Note: using openlitespeed and all .htaccess rules are working

答: The issue is in your rewrite rule. You're using ([^/]*) which is incorrect syntax use (.*) and your rewrite rule will work perfectly.

ContentLicense: CC BY-SA 4.0

Title: Rewrite .htaccess resulting in 404

Body:
I'm trying to make my url look good but for some reasons it is not working what could be the problem here

RewriteEngine on
RewriteRule ^view/([^/]*)/([^/]*)$ /view?wall=$1&page=$2 [L]

Above rewrite should resolve like this http://website.com/view/apartment-wallpapers/1247

Alternatively

Preferably I want to make my url to look like this but it's also resulting in

http://lifistudy.com/asus-red-903.html

.htaccess rewrite rule

RewriteEngine on
RewriteRule ^([^-]*)-([^-]*)\.html$ /view?wall=$1&page=$2 [L]

Note: using openlitespeed and all .htaccess rules are working


问:
Creating new columns based on certain strings appearing in a variable atleast twice
I have a data frame containing the variables 'id' and 'var1' similar to the following:

```<code>set.seed(100)
id <- sample(1:3, 10, replace = TRUE)
set.seed(101)
var1 <- sample(LETTERS[1:3], 10, replace = TRUE)
df <- data.frame(id, var1)
</code>```

I want to group the data frame by 'id' and create new columns 'condition1', 'condition2', 'condition3' and so on, if certain strings appear in var1 at least twice. So, when 'df' is grouped by 'id', 'condition1' will be 1 if var1 == 'A' and appears in at least 2 rows or else 'condition1' will be set to 0. Similarly, 'condition2' will be based on 'B' and 'condition3' will be based on 'C'.

So, far I have tried to use dplyr and come up with the following-

```<code>library(dplyr)
df2 <- df %>%
       group_by(id) %>%
       summarise(condition1 = case_when(**var1 == "A" appears in at least 2 rows** ~ 1, **var1 == "A" appears only once or does not appear at all** ~ 0),
                 condition2 = case_when(**var1 == "B" appears in at least 2 rows** ~ 1, **var1 == "B" appears only once or does not appear at all** ~ 0),
                 condition3 = case_when(**var1 == "C" appears in at least 2 rows** ~ 1, **var1 == "C" appears only once or does not appear at all** ~ 0))
</code>```

How do I correctly define the conditions inside case_when? Any other way to solve this would be welcome as well.

答:
Using data.table</p>
```<code>df <- data.table(df)
df[,.(condition1 = sum(var1 == "A") > 1,
      condition2 = sum(var1 == "B") > 1,
      condition2 = sum(var1 == "C") > 1), id]
</code>```

Body:
I have a data frame containing the variables 'id' and 'var1' similar to the following:

set.seed(100)
id <- sample(1:3, 10, replace = TRUE)
set.seed(101)
var1 <- sample(LETTERS[1:3], 10, replace = TRUE)
df <- data.frame(id, var1)

I want to group the data frame by 'id' and create new columns 'condition1', 'condition2', 'condition3' and so on, if certain strings appear in var1 at least twice. So, when 'df' is grouped by 'id', 'condition1' will be 1 if var1 == 'A' and appears in at least 2 rows or else 'condition1' will be set to 0. Similarly, 'condition2' will be based on 'B' and 'condition3' will be based on 'C'.

So, far I have tried to use dplyr and come up with the following-

library(dplyr)
df2 <- df %>%
       group_by(id) %>%
       summarise(condition1 = case_when(**var1 == "A" appears in at least 2 rows** ~ 1, **var1 == "A" appears only once or does not appear at all** ~ 0),
                 condition2 = case_when(**var1 == "B" appears in at least 2 rows** ~ 1, **var1 == "B" appears only once or does not appear at all** ~ 0),
                 condition3 = case_when(**var1 == "C" appears in at least 2 rows** ~ 1, **var1 == "C" appears only once or does not appear at all** ~ 0))

How do I correctly define the conditions inside case_when? Any other way to solve this would be welcome as well.

Body:
Using data.table

df <- data.table(df)
df[,.(condition1 = sum(var1 == "A") > 1,
      condition2 = sum(var1 == "B") > 1,
      condition2 = sum(var1 == "C") > 1), id]


问:
How to I fix this visual studio bug for my c++ program?
I have written this program in C++ and when I run it in visual studio my output is:

```<code>[Running] cd "c:\Users\Me\OneDrive\Desktop\c++\" && g++ main.cpp -o main && "c:\Users\Me\OneDrive\Desktop\c++\"main
Access is denied.

[Done] exited with code=1 in 0.636 seconds
</code>```

The 'cout' does work when I output an integer and floats, it seems it just wont output strings but the printf function does. How do I solve this>?

Here is my code

```<code>#include <iostream>

using namespace std;

int main() {

    cout << "Hello, world!" << endl;
    return 0;
}
</code>```

答:
The problem is not your code, or cout, or a Visual Studio bug.

The problem is that, as shown in your console output, "access [was] denied" when creating your new executable. You're not even running you're new code!

Most likely you have a previous instance of your application still open, probably waiting for you to "press any key to continue…". The executable cannot be replaced with a new one while it's running.

Find the window and end the program. Then you'll be able to build your new version.

Body:
I have written this program in C++ and when I run it in visual studio my output is:

[Running] cd "c:\Users\Me\OneDrive\Desktop\c++\" && g++ main.cpp -o main && "c:\Users\Me\OneDrive\Desktop\c++\"main
Access is denied.

[Done] exited with code=1 in 0.636 seconds

The 'cout' does work when I output an integer and floats, it seems it just wont output strings but the printf function does. How do I solve this>?

Here is my code

#include <iostream>

using namespace std;

int main() {

    cout << "Hello, world!" << endl;
    return 0;
}


问:
Deleting all documents in Firestore collection
I'm looking for a way to clear an entire collection. I saw that there is a batch update option, but that would require me to know all of the document IDs in the collection.

I'm looking for a way to simply delete every document in the collection.

Edit: Answer below is correct, I used the following:

```<code>func delete(collection: CollectionReference, batchSize: Int = 100) {
    // Limit query to avoid out-of-memory errors on large collections.
    // When deleting a collection guaranteed to fit in memory,
    // batching can be avoided entirely.
    collection.limit(to: batchSize).getDocuments { (docset, error) in
        // An error occurred.
        let docset = docset
        let batch = collection.firestore.batch()
        docset?.documents.forEach {
            batch.deleteDocument($0.reference)
        }
        batch.commit {_ in
            self.delete(collection: collection, batchSize: batchSize)
        }
    }
}
</code>```

答:
You have to get all the documents then use batch to delete them in bulk
P.S. i prefer try...catch syntax</p>

```<code>    let deleteInBatch = async (query, size = 100) => {
    try{

        let batch = firestore().batch();

        //get documents
        let values = await query.get();
        if(values.size>0){
            values.foreach(value=> {
                batch.delete(value.ref);
            })

            //Delete the documents in bulk
            batch.commit();
            if(values.size>0){
                //Recusively call the function again to finish
                //deleting the rest of documents
                deleteInBatch(query,size);
            }
        }else{
            //exist function
            return;
        }
    }catch(err){
        throw err;
    }
}
</code>```

Body:
I'm looking for a way to clear an entire collection. I saw that there is a batch update option, but that would require me to know all of the document IDs in the collection.

I'm looking for a way to simply delete every document in the collection.

Edit: Answer below is correct, I used the following:

func delete(collection: CollectionReference, batchSize: Int = 100) {
    // Limit query to avoid out-of-memory errors on large collections.
    // When deleting a collection guaranteed to fit in memory,
    // batching can be avoided entirely.
    collection.limit(to: batchSize).getDocuments { (docset, error) in
        // An error occurred.
        let docset = docset
        let batch = collection.firestore.batch()
        docset?.documents.forEach {
            batch.deleteDocument($0.reference)
        }
        batch.commit {_ in
            self.delete(collection: collection, batchSize: batchSize)
        }
    }
}

Body:
You have to get all the documents then use batch to delete them in bulk
P.S. i prefer try...catch syntax

    let deleteInBatch = async (query, size = 100) => {
    try{

        let batch = firestore().batch();

        //get documents
        let values = await query.get();
        if(values.size>0){
            values.foreach(value=> {
                batch.delete(value.ref);
            })

            //Delete the documents in bulk
            batch.commit();
            if(values.size>0){
                //Recusively call the function again to finish
                //deleting the rest of documents
                deleteInBatch(query,size);
            }
        }else{
            //exist function
            return;
        }
    }catch(err){
        throw err;
    }
}


问:
C - program ends after a do-while loop
```<code>...

do {

   printf("A:");
   scanf(" %d", &cm);

   printf(" %d od x\n", 100*(Info20-Info10)/cm);

} while (cm != 0);

int V;

for(V = 0; V <=100; V += 8) {
printf("V: %d.\n", V);

}

...
</code>```

The problem is the transition from the do-while loop to the for loop below, the exit key is 0 and after getting that input, the program ends instead of proceeding to the code below.

答:
Because, if you insert 0, you do a division for 0.

```<code>printf(" %d od x\n", 100*(Info20-Info10)/cm);
</code>```

raises an error

Title: C - program ends after a do-while loop

Body:
...

do {

   printf("A:");
   scanf(" %d", &cm);

   printf(" %d od x\n", 100*(Info20-Info10)/cm);

} while (cm != 0);

int V;

for(V = 0; V <=100; V += 8) {
printf("V: %d.\n", V);

}

...

The problem is the transition from the do-while loop to the for loop below, the exit key is 0 and after getting that input, the program ends instead of proceeding to the code below.

Body:
Because, if you insert 0, you do a division for 0.

printf(" %d od x\n", 100*(Info20-Info10)/cm);

raises an error


问:
Add a ListView Into a SlidingDrawer?
How do I inflate a ListView into a SlidingDrawer?  Thnx for the input.

The main.xml:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<WebView android:id="@+id/webView1" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</WebView>

<include android:id="@+id/windowTitle" layout="@layout/window_title" />
<include android:id="@+id/slidingDrawer" layout="@layout/sliding_drawer" />

</FrameLayout>
</code>```

The Drawer XML:

```<code><SlidingDrawer android:layout_width="fill_parent"
android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer" android:handle="@+id/handle" android:content="@+id/content"
android:allowSingleTap="false">

<LinearLayout android:id="@+id/handle"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="20dip" android:background="@drawable/gradient2">

    <ImageView android:id="@+id/handleGrip" android:src="@drawable/handle"
        android:layout_height="wrap_content" android:gravity="center"
        android:layout_centerInParent="true" android:layout_gravity="center"
        android:layout_width="match_parent" />

</LinearLayout>

<ListView android:id="@+id/content" android:layout_height="match_parent"
    android:background="#000" android:layout_width="wrap_content" />

</SlidingDrawer>
</code>```

答:
You have to do something like this.</p>

```<code><SlidingDrawer android:id="@+id/drawer" android:handle="@+id/handle"
    android:content="@+id/content" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:orientation="vertical"
    android:layout_gravity="bottom">

    <LinearLayout android:id="@id/content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Below there is a list view." />

        <ListView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listview_"
            android:divider="@android:color/transparent"
            android:dividerHeight="10.0sp" />

    </LinearLayout>

    <ImageView android:id="@id/handle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/icon" />

</SlidingDrawer>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add a ListView Into a SlidingDrawer?

Body:
How do I inflate a ListView into a SlidingDrawer?  Thnx for the input.

The main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<WebView android:id="@+id/webView1" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</WebView>

<include android:id="@+id/windowTitle" layout="@layout/window_title" />
<include android:id="@+id/slidingDrawer" layout="@layout/sliding_drawer" />

</FrameLayout>

The Drawer XML:

<SlidingDrawer android:layout_width="fill_parent"
android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer" android:handle="@+id/handle" android:content="@+id/content"
android:allowSingleTap="false">

<LinearLayout android:id="@+id/handle"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="20dip" android:background="@drawable/gradient2">

    <ImageView android:id="@+id/handleGrip" android:src="@drawable/handle"
        android:layout_height="wrap_content" android:gravity="center"
        android:layout_centerInParent="true" android:layout_gravity="center"
        android:layout_width="match_parent" />

</LinearLayout>

<ListView android:id="@+id/content" android:layout_height="match_parent"
    android:background="#000" android:layout_width="wrap_content" />

</SlidingDrawer>

Body:
You have to do something like this.

<SlidingDrawer android:id="@+id/drawer" android:handle="@+id/handle"
    android:content="@+id/content" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:orientation="vertical"
    android:layout_gravity="bottom">

    <LinearLayout android:id="@id/content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Below there is a list view." />

        <ListView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listview_"
            android:divider="@android:color/transparent"
            android:dividerHeight="10.0sp" />

    </LinearLayout>

    <ImageView android:id="@id/handle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/icon" />

</SlidingDrawer>


问:
Ngixg reverse proxy - real ip
I'm having trouble getting the client's ip sent to the backend server behind an nginx reverse proxy,
I've tried a little of each with the proxy_set but unfortunately without luck</p>

```<code>server {
 listen 443 ssl http2;

 # SSL config
 ssl on;
 ssl_certificate /etc/nginx/ssl/domain/domain.net.pem;
 ssl_certificate_key /etc/nginx/ssl/domain/domain.net.key;

 server_name domain.net www.domain.net;

 set $upstream 10.0.1.10;

 location / {
 proxy_pass_header Authorization;
 proxy_pass https://$upstream;
 proxy_set_header Host $host;
 proxy_set_header X-Real-IP $remote_addr;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_http_version 1.1;
 proxy_set_header Connection "";
 proxy_buffering off;
 client_max_body_size 0;
 proxy_read_timeout 36000s;
 proxy_redirect off;
 proxy_ssl_session_reuse off;
 }
}
</code>```

答: You may forgot proxy_set_header Forwarded $proxy_add_forwarded;

Title: Ngixg reverse proxy - real ip

Body:
I'm having trouble getting the client's ip sent to the backend server behind an nginx reverse proxy,
I've tried a little of each with the proxy_set but unfortunately without luck

server {
 listen 443 ssl http2;

 # SSL config
 ssl on;
 ssl_certificate /etc/nginx/ssl/domain/domain.net.pem;
 ssl_certificate_key /etc/nginx/ssl/domain/domain.net.key;

 server_name domain.net www.domain.net;

 set $upstream 10.0.1.10;

 location / {
 proxy_pass_header Authorization;
 proxy_pass https://$upstream;
 proxy_set_header Host $host;
 proxy_set_header X-Real-IP $remote_addr;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_http_version 1.1;
 proxy_set_header Connection "";
 proxy_buffering off;
 client_max_body_size 0;
 proxy_read_timeout 36000s;
 proxy_redirect off;
 proxy_ssl_session_reuse off;
 }
}


问:
Android - Program ImageView Constraints in Custom Toast Class
I have successfully add an ImageView to a CUSTOM TOAST VIEW GROUP.

Right now that ImageView is horizontally centered in the bottom of the screen.

What I wish to do is to constraint this widget to the top of the screen and later put it some top margins. However I can't find the methods name that allows this to happen? Does it even exist? Is there a different solution to this scenario?

How do I programmatically constraint this ImageView to the top of the toast view?

```<code>public class CustomToast extends android.widget.Toast{

public CustomToast(String toast_text, Context toast_context, int toast_status) {
    super(toast_context);

    // TOAST
    Toast toast = Toast.makeText(toast_context, toast_text, Toast.LENGTH_LONG);

    // VIEW
    ViewGroup view = (ViewGroup) toast.getView();

    // BACKGROUND
    view.setBackgroundResource(R.drawable.background_toast);

    // IMAGE VIEW
    ImageView myImage = new ImageView(toast_context);
    myImage.setImageResource(R.drawable.icon_toast_valid);
    myImage.setMaxWidth(200);
    myImage.setMaxHeight(200);
    myImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    myImage.setAdjustViewBounds(true);

    view.addView(myImage);

    // SHOW
    toast.show();
}
</code>```

}

I have checked the android documentation, some stackoverflow links and even tried to find the method through the Android Studio intelligent code completion. So far I haven't been capable of solving this problem...

答:
In Android you have View and ViewGroups.
The ViewGroups can contain childs, and this childs can be other View or ViewGroups.

The View have behave to himself (color, size, orientation...).
The ViewGroups have order behave to himself and his childs.

The most used ViewGroups are:

FrameLayout

LinearLayout

RelativeLayout

ConstraintLayout

Depending on your what you need you got to choose.

FrameLayout order his child like a Stack of Views in the same way you
are declaring in the xml.

LinearLayout arranges other views either horizontally in a single
column or vertically in a single row.

RelativeLayout has references between childs to order.

ConstraintLayout has "constraints" to order his childs, it is like
RelativeLayout but most powerful.

In your implementation you have a "programmatically" implementation, maybe if you try to use the xml will be more simple.

Body:
I have successfully add an ImageView to a CUSTOM TOAST VIEW GROUP.

Right now that ImageView is horizontally centered in the bottom of the screen.

What I wish to do is to constraint this widget to the top of the screen and later put it some top margins. However I can't find the methods name that allows this to happen? Does it even exist? Is there a different solution to this scenario?

How do I programmatically constraint this ImageView to the top of the toast view?

public class CustomToast extends android.widget.Toast{

public CustomToast(String toast_text, Context toast_context, int toast_status) {
    super(toast_context);

    // TOAST
    Toast toast = Toast.makeText(toast_context, toast_text, Toast.LENGTH_LONG);

    // VIEW
    ViewGroup view = (ViewGroup) toast.getView();

    // BACKGROUND
    view.setBackgroundResource(R.drawable.background_toast);

    // IMAGE VIEW
    ImageView myImage = new ImageView(toast_context);
    myImage.setImageResource(R.drawable.icon_toast_valid);
    myImage.setMaxWidth(200);
    myImage.setMaxHeight(200);
    myImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    myImage.setAdjustViewBounds(true);

    view.addView(myImage);

    // SHOW
    toast.show();
}

}

I have checked the android documentation, some stackoverflow links and even tried to find the method through the Android Studio intelligent code completion. So far I haven't been capable of solving this problem...


问:
SSH Mysql query result
I'm trying to pass a query result to an SSH command.

```<code>command $queryresult
</code>```

The query result can be one or more then one row and in case of more than one row, I need to concatenate them.

If I run mysql command with -N and -e parameters,

```<code>mysql -u $MUSER -p$MPASS -D $DBS -N -e "$QUERY6"
</code>```

I obtain one result per row

```<code>result1
result2
</code>```

Is there a way to separate them by a space?

```<code>result1 result2
</code>```

Query is

```<code>SELECT view_id
FROM mview_state
WHERE STATUS != 'idle' AND (CURRENT_TIMESTAMP() + 60000 - updated) > 1800
</code>```

答:
Use GROUP_COCAT

```<code>SELECT GROUP_CONCAT(mview_state.view_id SEPARATOR ' ') view_id
FROM mview_state
WHERE `STATUS` != 'idle' AND (CURRENT_TIMESTAMP() + 60000 - mview_state.updated) > 1800
GROUP BY view_id
</code>```

Sidenote:

STATUS is a MySQL Keyword and should ideally not be used as a column name. Column names in MySQL should be universally lower case.

Title: SSH Mysql query result

Body:
I'm trying to pass a query result to an SSH command.

command $queryresult

The query result can be one or more then one row and in case of more than one row, I need to concatenate them.

If I run mysql command with -N and -e parameters,

mysql -u $MUSER -p$MPASS -D $DBS -N -e "$QUERY6"

I obtain one result per row

result1
result2

Is there a way to separate them by a space?

result1 result2

Query is

SELECT view_id
FROM mview_state
WHERE STATUS != 'idle' AND (CURRENT_TIMESTAMP() + 60000 - updated) > 1800

Body:
Use GROUP_COCAT

SELECT GROUP_CONCAT(mview_state.view_id SEPARATOR ' ') view_id
FROM mview_state
WHERE `STATUS` != 'idle' AND (CURRENT_TIMESTAMP() + 60000 - mview_state.updated) > 1800
GROUP BY view_id

Sidenote:

STATUS is a MySQL Keyword and should ideally not be used as a column name. Column names in MySQL should be universally lower case.


问:
Anomaly detection python
I have a dataset with 7 parameters for each point:

counterOfPackets

counterOfSyn

counterOfPa

counterOfR

counterOfRA

counterOfFin

packetsTotalSize

I would like to find a way to get all the outliers to a python list (not as a plt.show GUI).
What algorithm should I use and how can I view the results as a python list?
Thanks for your help :D

答: This page on Medium from Will Badr is a good resource - https://towardsdatascience.com/5-ways-to-detect-outliers-that-every-data-scientist-should-know-python-code-70a54335a623. In terms of what outlier detection algorithm to use, the answer depends on the distribution of your data. I have found success using standard deviations and distance from inter-quartile ranges to identify outliers. However, these approaches work better over normal distributions, and in my scenario, I found methods to transform my data into a normal distribution without impacting the outcome.</p>

Title: Anomaly detection python


问:
Django, How to import model class to another model class?
I have this two app name Business and ChartofAccounts,

in my business.models i have

```<code>class businessType(models.Model):
    Name = models.CharField(max_length=500)
    Description = models.CharField(max_length=500)
    RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True)
</code>```

and my ChartofAccounts.models i have

```<code>class ChartOfAccount(models.Model):
    AccountNo = models.IntegerField()
    Account_Name = models.CharField(max_length=500)
    Account_Type = models.CharField(max_length=500)
    Details_Type = models.CharField(max_length=500)
    Description = models.CharField(max_length=500)
    BusinessTypeID = models.ForeignKey(Business, related_name='+', on_delete=models.CASCADE, blank=True)
    RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True)
</code>```

I dont know how to import the business.models in my ChartofAccounts App, any ideas?

what i tried is

```<code>from myAccounting import Business
</code>```

and the error is

UPDATE

when i tried this

```<code>from Business.models import Business

BusinessTypeID = models.ForeignKey('Business.Business', related_name='+', on_delete=models.CASCADE, blank=True)
</code>```

the error says

UPDATE

```<code>from business.models import business
</code>```

i rename my Business app to business app same goes to chartofAccounts but same error

答:
It is defined in the models module, hence you import this with:

```<code>from Business<b>.models</b> import Business</code>```

the name of the app is Business, so it should be Business.models, not myAccounting.models.

That being said, it might be easier to refer to the model with a string literal, then you do not need to import this at all:

```<code>from django.db import models

class ChartOfAccount(models.Model):
    AccountNo = models.IntegerField()
    Account_Name = models.CharField(max_length=500)
    Account_Type = models.CharField(max_length=500)
    Details_Type = models.CharField(max_length=500)
    Description = models.CharField(max_length=500)
    BusinessTypeID = models.ForeignKey(<b>'Business.Business'</b>, related_name='+', on_delete=models.CASCADE, blank=True)
    RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True)</code>```

This also helps avoind circular imports, like @RHSmith159 says.

Note: modules and field names are normally written in slug_case, not PerlCase. Therefore it is advisable to name your app business instead of <s>Business</s>, and the field account_no, instead of <s>AccountNo</s>.

Body:
I have this two app name Business and ChartofAccounts,

in my business.models i have

class businessType(models.Model):
    Name = models.CharField(max_length=500)
    Description = models.CharField(max_length=500)
    RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True)

and my ChartofAccounts.models i have

class ChartOfAccount(models.Model):
    AccountNo = models.IntegerField()
    Account_Name = models.CharField(max_length=500)
    Account_Type = models.CharField(max_length=500)
    Details_Type = models.CharField(max_length=500)
    Description = models.CharField(max_length=500)
    BusinessTypeID = models.ForeignKey(Business, related_name='+', on_delete=models.CASCADE, blank=True)
    RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True)

I dont know how to import the business.models in my ChartofAccounts App, any ideas?

what i tried is

from myAccounting import Business

and the error is

UPDATE

when i tried this

from Business.models import Business

BusinessTypeID = models.ForeignKey('Business.Business', related_name='+', on_delete=models.CASCADE, blank=True)

the error says

UPDATE

from business.models import business

i rename my Business app to business app same goes to chartofAccounts but same error

Body:
It is defined in the models module, hence you import this with:

from Business.models import Business

the name of the app is Business, so it should be Business.models, not myAccounting.models.

That being said, it might be easier to refer to the model with a string literal, then you do not need to import this at all:

from django.db import models

class ChartOfAccount(models.Model):
    AccountNo = models.IntegerField()
    Account_Name = models.CharField(max_length=500)
    Account_Type = models.CharField(max_length=500)
    Details_Type = models.CharField(max_length=500)
    Description = models.CharField(max_length=500)
    BusinessTypeID = models.ForeignKey('Business.Business', related_name='+', on_delete=models.CASCADE, blank=True)
    RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True)

This also helps avoind circular imports, like @RHSmith159 says.

Note: modules and field names are normally written in slug_case, not PerlCase. Therefore it is advisable to name your app business instead of <s>Business</s>, and the field account_no, instead of <s>AccountNo</s>.


问:
Using CoreML Word Tagger on iOS 12.4
I trained a Core ML Text Classifier with Transfer Learning and Dynamic Embedding. It works great, but when I tried testing on a device running iOS 12.4, it failed to predict and gave me the error:

```<code>Error Domain=com.apple.CoreML Code=0 "Prediction failed" UserInfo={NSLocalizedDescription=Prediction failed}
</code>```

I also get this error when running on a simulator. I made sure the model could only be used on devices running iOS 12+. Is this model not supported on iOS 13? I saw these new features were released at this WWDC, but I was hoping/assuming they were backward compatible. Was I mistaken? If this model can't be run on iOS 12 devices, is there any way to export the model so it can be. Lastly, is there anywhere I can find a list of what models are supported on each iOS.

Thanks so much!

答: Just found the answer from a WWDC 2019 video at the 10 minute mark. Transfer learning for text classification is new with iOS 13 and in order to save space, a pre-trained model is deployed on iOS 13 devices. When you train a model with transfer learning, this model modifies the pre-trained model on device. This is why using a TextClassifier with transfer learning doesn’t work on iOS 12</p>

Title: Using CoreML Word Tagger on iOS 12.4

Body:
I trained a Core ML Text Classifier with Transfer Learning and Dynamic Embedding. It works great, but when I tried testing on a device running iOS 12.4, it failed to predict and gave me the error:

Error Domain=com.apple.CoreML Code=0 "Prediction failed" UserInfo={NSLocalizedDescription=Prediction failed}

I also get this error when running on a simulator. I made sure the model could only be used on devices running iOS 12+. Is this model not supported on iOS 13? I saw these new features were released at this WWDC, but I was hoping/assuming they were backward compatible. Was I mistaken? If this model can't be run on iOS 12 devices, is there any way to export the model so it can be. Lastly, is there anywhere I can find a list of what models are supported on each iOS.

Thanks so much!


问:
Chrome, when using width="100%", images become blurred?
I'm using Google Chrome, and have a 1440px wide display. I made the images about that wide,  and whenever I use the attribute width="100%" with the img tag, it blurs the image.

When I add it however, it downsizes the image to the exact screen size.

Not sure if this is a Chrome issue, or there is another way to do it.

Thanks!

答:
I get the same issue, only on chrome.
I use a workaround with a div with background-image, the blur disappear.</p>


问:
Javascript function to convert color names to hex codes
Is there a built-in function that would convert a color by name into its hex representation?
Like I want to pass 'white' and receive '#FFFFFF'. I really want to avoid coding all hundred if's myself :)</p>

答:
This function request a named color and send return a hexadecimal color value.
If the named color not supported (example "whyte") send back black color by default but on consol you can find a warning:
Not supported named color: ${namedColor}</p>

```<code>const namedColorToHex = namedColor => {
    const html = document.querySelector("html");
    const originalColor = html.style.color;
    html.style.color = namedColor;
    const rgbFormatBgColor = window.getComputedStyle(html).color;
    if (namedColor !== "black" && rgbFormatBgColor === "rgb(0, 0, 0)") {
        console.warn(`Not supported named color: ${namedColor}`);
    }
    html.style.color = originalColor;
    const regEx = /(\d+)/g;
    const result = rgbFormatBgColor.match(regEx);
    let hexColor = `#`;
    result.forEach(value => {
        let hex = Number(value).toString(16);
        if (hex.length === 1) {
            hex = `0${hex}`;
        }
        hexColor += hex;
    });
    return hexColor;
};
</code>```

Body:
This function request a named color and send return a hexadecimal color value.
If the named color not supported (example "whyte") send back black color by default but on consol you can find a warning:
Not supported named color: ${namedColor}

const namedColorToHex = namedColor => {
    const html = document.querySelector("html");
    const originalColor = html.style.color;
    html.style.color = namedColor;
    const rgbFormatBgColor = window.getComputedStyle(html).color;
    if (namedColor !== "black" && rgbFormatBgColor === "rgb(0, 0, 0)") {
        console.warn(`Not supported named color: ${namedColor}`);
    }
    html.style.color = originalColor;
    const regEx = /(\d+)/g;
    const result = rgbFormatBgColor.match(regEx);
    let hexColor = `#`;
    result.forEach(value => {
        let hex = Number(value).toString(16);
        if (hex.length === 1) {
            hex = `0${hex}`;
        }
        hexColor += hex;
    });
    return hexColor;
};


问:
Call same promise inside `Then`
I want to know if you can call the same promise twice like so

//receiver is sent if the mail should be sent to someone else and will have a
//different email boy

const body = (req.body.receiver) === undefined ? 'regular mail': 'admin email body'

//the sendEmail Function takes to, from and body arguments
await sendEmail(req.body.requestedBy, someEmailAddress, body)
        .then(info => {
          console.log(info)
         //a mail should be sent only to requester if req.body.receiver is present in the request
          if (req.body.receiver) {
            await sendEmail(req.body.receiver, someEmailAddress, body)
              .then(res => {
                console.log(res)
              })
              .catch(err => {
                console.log(err)
              })
          }
          return res.send(data)
        })
        .catch(err => {
          console.log('Error:', err)
        })
```

Of course this would be wrapped in an async function because the sendMail function i created returns a promise. Mail is sent via nodemailer.

答:
What you are doing in your example is not technically calling the same promise twice. You are calling the same function twice, sendMail. Each time you call that function, it returns a new promise.

So the answer is yes, you can call that function multiple times even though it returns a promise, because it will return a new promise each time.

Title: Call same promise inside `Then`

Body:
I want to know if you can call the same promise twice like so

//receiver is sent if the mail should be sent to someone else and will have a
//different email boy

const body = (req.body.receiver) === undefined ? 'regular mail': 'admin email body'

//the sendEmail Function takes to, from and body arguments
await sendEmail(req.body.requestedBy, someEmailAddress, body)
        .then(info => {
          console.log(info)
         //a mail should be sent only to requester if req.body.receiver is present in the request
          if (req.body.receiver) {
            await sendEmail(req.body.receiver, someEmailAddress, body)
              .then(res => {
                console.log(res)
              })
              .catch(err => {
                console.log(err)
              })
          }
          return res.send(data)
        })
        .catch(err => {
          console.log('Error:', err)
        })

Of course this would be wrapped in an async function because the sendMail function i created returns a promise. Mail is sent via nodemailer.


问:
Does it make sense to define an Interface for internal use where we know needs with change?
I am in the designing stage of a new project for internal use - the software will never be "shipped". I know with absolute certainty that we will add more functionality to the project going forward. If I were to wait then the project will never get done. I am approaching the project by designing Interfaces. I want to use interfaces in the code so I can check classes for that type and do certain things. I also want to perform operations on all classes of a certain Interface. There will be certain Interfaces where classes will have different logic to achieve the result. Interfaces make sense for this.

My two questions:

Everybody seems to say that your interface needs to be stable. If you need to add additional capabilities later on what does one typically do? Inherit a base interface and add on?

There are certain situations where (for now) an Interface will only be implemented by one class. In this case does it still make sense to use an Interface?

答:
Answer to 1st question:

It should be stable, yes. To achieve this create very focused interfaces. This means 1 interface should describe very limited function / has only few property.
Then to have a complex interface: merge them into a combined interface.

Forexample ITree and IPlant is a very wide description and should not exists. IEverGreen and IDeciduous are just a bit better. What you should look is smaller parts like:

```<code>IHaveRoot {}
IRePlantable {}
IHaveLeaves{}
</code>```

and then:

```<code>ILeafAndRootOwner : IHaveRoot, IHaveLeaves
</code>```

Answer to 2nd question:

It makes sense because you leave an open possibility for Decorator Pattern or to mark the existing implementation to obsolete while defining a new. And all other .cs files that references the interface doesn't have to change!

Body:
Answer to 1st question:

It should be stable, yes. To achieve this create very focused interfaces. This means 1 interface should describe very limited function / has only few property.
Then to have a complex interface: merge them into a combined interface.

Forexample ITree and IPlant is a very wide description and should not exists. IEverGreen and IDeciduous are just a bit better. What you should look is smaller parts like:

IHaveRoot {}
IRePlantable {}
IHaveLeaves{}

and then:

ILeafAndRootOwner : IHaveRoot, IHaveLeaves

Answer to 2nd question:

It makes sense because you leave an open possibility for Decorator Pattern or to mark the existing implementation to obsolete while defining a new. And all other .cs files that references the interface doesn't have to change!


问:
display tip when mouse is anywhere over line chart
I have a composite line chart.

How can I display the respective values (date and value) when i hover on any place of the chart like below:

```<code>                var composechart = dc.compositeChart("#test_composed");

                composechart
                    .width(990)
                    .height(450)
                    .margins({ top: 50, right: 40, left: 50, bottom: 50 })
                    .x(d3.scaleTime().domain([new Date(2017, 0, 1), new Date(2019, 10, 30)]))
                    .rangeChart(xChart)
                    .elasticY(true)
                    .xUnits(d3.timeMonths)
                    .legend(dc.legend().x(80).y(20).itemHeight(13).gap(5))
                    .renderHorizontalGridLines(true)
                    .brushOn(false)

                    .compose([
                     dc.lineChart(composechart)
                        .dimension(salesgrafikDim)
                        .group(salesgrafikGroup,"Sales"),
                     dc.lineChart(composechart)
                        .dimension(satisgrafikDim)
                        .colors('red')
                        .group(quantitygrafikGroup,"Quantity")
                    ])

                     xChart
                     .width(990)
                     .height(40)
                     .margins({top: 0, right: 50, bottom: 20, left: 50})
                     .dimension(salesgrafikDim)
                     .group(salesgrafikGroup)
                     .x(d3.scaleTime().domain([new Date(2017, 0, 1), new Date(2019, 10, 30)]))
                     .xUnits(d3.timeMonths);

                     xChart.yAxis().ticks(0);
</code>```

Basically want to display a tooltip like in the screenshot below, where the mouse should not need to be over a dot for it to display.

I can do it with straight D3, with svg and append and so on. But i have dimension with other charts and dataTable, so I want to use this with dc.js.

It would be much more user friendly and easy to understand if you don't have to hover over the dots to see the tip.

My chart is below :

答:
Since dc.js doesn't support this directly, you're going to end up dropping down into D3 in order to implement this.

First, we need to disable the existing titles:

```<code>.title(() => '')
</code>```

and hover events:

```<code>composite.on('pretransition', chart => {
  chart.children().forEach(
    child => child.selectAll('circle.dot')
      .on('mousemove', null)
      .on('mouseout', null)
    );
})
</code>```

Then we can add a handler to put mouse handlers on the SVG itself

```<code>composite.on('postRender', chart => {
  chart.svg().on('mousemove', () => { // 2
    // find closest data point
    const x = chart.x().invert(d3.mouse(chart.svg().node())[0] - chart.margins().left),
      xs = chart.children()[0].group().all().map(kv => kv.key),
      right = d3.bisectLeft(xs, x);
    let closest = right;
    if(right >= xs.length)
      closest = right - 1;
    else if(right > 0) {
      // see if point to the left is closer
      if(x - xs[right-1] < xs[right] - x)
        closest = right - 1;
    }
    //console.log('closest', new Date(x), closest, xs[closest])
    chart.children().forEach(child => { // 3
      child.g().selectAll('circle.dot').each(function(d) {
        if(d.x === xs[closest]) {
          child._showDot(d3.select(this));
          child.g().select('text.data-tip')
            .attr('visibility', 'visible')
            .attr('x', child.x()(d.x))
            .attr('y', child.y()(d.y))
            .text(tooltip_text(d.data))
        } else
          child._hideDot(d3.select(this));
      });
    })
  })
  chart.svg().on('mouseout', () => { // 4
    chart.children().forEach(child => {
      child.selectAll('circle.dot').each(function(d) {
        child._hideDot(d3.select(this));
      });
    })
  })
  chart.children().forEach(child => child.g() // 1
    .append('text')
    .attr('class', 'data-tip')
    .attr('fill', 'black')
    .attr('alignment-baseline', 'top')
    .attr('text-anchor', 'begin')
    .attr('visibility', 'hidden')
    )
});
</code>```

I'm not going to get into the details, but this

adds a text element to each child chart, which will display the tip

listens for mousemove and finds the nearest point

shows the dots and text for the selected point in each child

hides all dots and text when the mouse leaves the chart

I ran out of time to think about this, so I didn't try to get the text positioned correctly or make it look nice.

linear scale

Linear scale fiddle.

time scale

Time scale fiddle.

As I mentioned in the comments, you're going to run into trouble with this design, if the lines get too close together. You can see this problem with the first point in this example.

Body:
I have a composite line chart.

How can I display the respective values (date and value) when i hover on any place of the chart like below:

                var composechart = dc.compositeChart("#test_composed");

                composechart
                    .width(990)
                    .height(450)
                    .margins({ top: 50, right: 40, left: 50, bottom: 50 })
                    .x(d3.scaleTime().domain([new Date(2017, 0, 1), new Date(2019, 10, 30)]))
                    .rangeChart(xChart)
                    .elasticY(true)
                    .xUnits(d3.timeMonths)
                    .legend(dc.legend().x(80).y(20).itemHeight(13).gap(5))
                    .renderHorizontalGridLines(true)
                    .brushOn(false)

                    .compose([
                     dc.lineChart(composechart)
                        .dimension(salesgrafikDim)
                        .group(salesgrafikGroup,"Sales"),
                     dc.lineChart(composechart)
                        .dimension(satisgrafikDim)
                        .colors('red')
                        .group(quantitygrafikGroup,"Quantity")
                    ])

                     xChart
                     .width(990)
                     .height(40)
                     .margins({top: 0, right: 50, bottom: 20, left: 50})
                     .dimension(salesgrafikDim)
                     .group(salesgrafikGroup)
                     .x(d3.scaleTime().domain([new Date(2017, 0, 1), new Date(2019, 10, 30)]))
                     .xUnits(d3.timeMonths);

                     xChart.yAxis().ticks(0);

Basically want to display a tooltip like in the screenshot below, where the mouse should not need to be over a dot for it to display.

I can do it with straight D3, with svg and append and so on. But i have dimension with other charts and dataTable, so I want to use this with dc.js.

It would be much more user friendly and easy to understand if you don't have to hover over the dots to see the tip.

My chart is below :

Body:
Since dc.js doesn't support this directly, you're going to end up dropping down into D3 in order to implement this.

First, we need to disable the existing titles:

.title(() => '')

and hover events:

composite.on('pretransition', chart => {
  chart.children().forEach(
    child => child.selectAll('circle.dot')
      .on('mousemove', null)
      .on('mouseout', null)
    );
})

Then we can add a handler to put mouse handlers on the SVG itself

composite.on('postRender', chart => {
  chart.svg().on('mousemove', () => { // 2
    // find closest data point
    const x = chart.x().invert(d3.mouse(chart.svg().node())[0] - chart.margins().left),
      xs = chart.children()[0].group().all().map(kv => kv.key),
      right = d3.bisectLeft(xs, x);
    let closest = right;
    if(right >= xs.length)
      closest = right - 1;
    else if(right > 0) {
      // see if point to the left is closer
      if(x - xs[right-1] < xs[right] - x)
        closest = right - 1;
    }
    //console.log('closest', new Date(x), closest, xs[closest])
    chart.children().forEach(child => { // 3
      child.g().selectAll('circle.dot').each(function(d) {
        if(d.x === xs[closest]) {
          child._showDot(d3.select(this));
          child.g().select('text.data-tip')
            .attr('visibility', 'visible')
            .attr('x', child.x()(d.x))
            .attr('y', child.y()(d.y))
            .text(tooltip_text(d.data))
        } else
          child._hideDot(d3.select(this));
      });
    })
  })
  chart.svg().on('mouseout', () => { // 4
    chart.children().forEach(child => {
      child.selectAll('circle.dot').each(function(d) {
        child._hideDot(d3.select(this));
      });
    })
  })
  chart.children().forEach(child => child.g() // 1
    .append('text')
    .attr('class', 'data-tip')
    .attr('fill', 'black')
    .attr('alignment-baseline', 'top')
    .attr('text-anchor', 'begin')
    .attr('visibility', 'hidden')
    )
});

I'm not going to get into the details, but this

adds a text element to each child chart, which will display the tip

listens for mousemove and finds the nearest point

shows the dots and text for the selected point in each child

hides all dots and text when the mouse leaves the chart

I ran out of time to think about this, so I didn't try to get the text positioned correctly or make it look nice.

linear scale

Linear scale fiddle.

time scale

Time scale fiddle.

As I mentioned in the comments, you're going to run into trouble with this design, if the lines get too close together. You can see this problem with the first point in this example.


问:
invalid literal for int() with base 10 : '(1,2,3,4,5,6,7)'
```<code>tuple1 = int(input())
list1 = list()
for i in tuple1:
    if tuple1[i-1] % 2 == 0:
        list1.append(tuple1[i-1])
tuple2 = tuple(list1)
print(tuple2)
</code>```

I'm getting error as

invalid literal for int() with base 10 : '(1,2,3,4,5,6,7)'

答:
you could use literal_eval from the ast module to try and convert the input to a tuple, e.g.

```<code>from ast import literal_eval

s = '(1,2,3,4,5,6,7)' # your input...
t = literal_eval(s)

print(t, type(t))
# (1, 2, 3, 4, 5, 6, 7) <class 'tuple'>
</code>```

Body:
tuple1 = int(input())
list1 = list()
for i in tuple1:
    if tuple1[i-1] % 2 == 0:
        list1.append(tuple1[i-1])
tuple2 = tuple(list1)
print(tuple2)

I'm getting error as

invalid literal for int() with base 10 : '(1,2,3,4,5,6,7)'

Body:
you could use literal_eval from the ast module to try and convert the input to a tuple, e.g.

from ast import literal_eval

s = '(1,2,3,4,5,6,7)' # your input...
t = literal_eval(s)

print(t, type(t))
# (1, 2, 3, 4, 5, 6, 7) <class 'tuple'>


问:
Is it possible to run the elk stack on kubernetes using minikube
I am trying to get the elk stack running locally on a  linux ubuntu 18.04 laptop using minikube.
But I don' get past step one, the elastiearch master nodes do not come on line. Appearantly because the physical volumes are not being created, or cannot be used. My short question is whether minikube is supported as a means of running kibana/elastisearch/logstach or are they solely intented to be running in the clould.
I've been following this tutorial:

https://logz.io/blog/deploying-the-elk-stack-on-kubernetes-with-helm/

```<code>Running pods
NAME                                          READY   STATUS                  RESTARTS   AGE
elk-elasticsearch-client-5ffc974f8-987zv      1/1     Running                 0          21m
elk-elasticsearch-curator-1582107120-4f2wm    0/1     Completed               0          19m
elk-elasticsearch-data-0                      0/1     Pending                 0          21m
elk-elasticsearch-exporter-84ff9b656d-t8vw2   1/1     Running                 0          21m
elk-elasticsearch-master-0                    1/1     Running                 0          21m
elk-elasticsearch-master-1                    1/1     Running                 0          20m
elk-filebeat-4sxn9                            0/2     Init:CrashLoopBackOff   9          21m
elk-kibana-77b97d7c69-d4jzz                   1/1     Running                 0          21m
elk-logstash-0                                0/2     Pending                 0          21m
</code>```

So filebeat won't start for me I tried doing
kubectl logs elk-filebeat-4sxn9 load-es-template

From which I get:

Exiting: Couldn't connect to any of the configured Elasticsearch hosts. Errors: [Error connection to Elasticsearch http://elk-elasticsearch-client.elk.svc:9200: Get http://elk-elasticsearch-client.elk.svc:9200: lookup elk-elasticsearch-client.elk.svc on 10.96.0.10:53: no such host]

答:
Well, yes, you can use minikube but you need to install it with correct options.

Keep in mind this is not recommended.

In Elastic docs about Production Deployment - Hardware we can read:

MEMORY

A machine with 64 GB of RAM is the ideal sweet spot, but 32 GB and 16 GB machines are also common. Less than 8 GB tends to be counterproductive

Minikube by deafault only allocates 2GB of RAM, you can check that by $ minikube config get memory. You can increase this value by using --memory flag or making that persistent with $ minikube config set memory 4096

CPU

This is not really an issue because:

Most Elasticsearch deployments tend to be rather light on CPU requirements. As such, the exact processor setup matters less than the other resources. You should choose a modern processor with multiple cores. Common clusters utilize two- to eight-core machines.

DISKS

They are important and usually they are a main bottleneck in the cluster.

If you can afford SSDs, they are by far superior to any spinning media. SSD-backed nodes see boosts in both query and indexing performance. If you can afford it, SSDs are the way to go.

...

If you use spinning media, try to obtain the fastest disks possible (high-performance server disks, 15k RPM drives).

Using RAID 0 is an effective way to increase disk speed, for both spinning disks and SSD. There is no need to use mirroring or parity variants of RAID, since high availability is built into Elasticsearch via replicas.

Those are the basic stuff related to ELK. You can read ELK Architecture and requirements and Hardware requirement ELK for more details regarding data consumption.

You would need to share the logs from the pods and your minikube configuration so we could start debugging the issue.

Body:
I am trying to get the elk stack running locally on a  linux ubuntu 18.04 laptop using minikube.
But I don' get past step one, the elastiearch master nodes do not come on line. Appearantly because the physical volumes are not being created, or cannot be used. My short question is whether minikube is supported as a means of running kibana/elastisearch/logstach or are they solely intented to be running in the clould.
I've been following this tutorial:

https://logz.io/blog/deploying-the-elk-stack-on-kubernetes-with-helm/

Running pods
NAME                                          READY   STATUS                  RESTARTS   AGE
elk-elasticsearch-client-5ffc974f8-987zv      1/1     Running                 0          21m
elk-elasticsearch-curator-1582107120-4f2wm    0/1     Completed               0          19m
elk-elasticsearch-data-0                      0/1     Pending                 0          21m
elk-elasticsearch-exporter-84ff9b656d-t8vw2   1/1     Running                 0          21m
elk-elasticsearch-master-0                    1/1     Running                 0          21m
elk-elasticsearch-master-1                    1/1     Running                 0          20m
elk-filebeat-4sxn9                            0/2     Init:CrashLoopBackOff   9          21m
elk-kibana-77b97d7c69-d4jzz                   1/1     Running                 0          21m
elk-logstash-0                                0/2     Pending                 0          21m

So filebeat won't start for me I tried doing
kubectl logs elk-filebeat-4sxn9 load-es-template

From which I get:

Exiting: Couldn't connect to any of the configured Elasticsearch hosts. Errors: [Error connection to Elasticsearch http://elk-elasticsearch-client.elk.svc:9200: Get http://elk-elasticsearch-client.elk.svc:9200: lookup elk-elasticsearch-client.elk.svc on 10.96.0.10:53: no such host]


问:
What is the difference between library crates and normal crates in Rust?
While reading the official book, I stumbled upon packages and crates. To create a new "project", this is what I ran:

```<code>$ cargo new my-project
     Created binary (application) `my-project` package
$ ls my-project
Cargo.toml
src
$ ls my-project/src
main.rs
</code>```

The book states the following:

A package must contain zero or one library crates, and no more. It can contain as many binary crates as you’d like, but it must contain at least one crate (either library or binary).

My doubt is, what is the difference between binary crates and normal crates?

答:
The difference is between binary crate and library crate. There are no "normal" crates.

A binary crate is an executable program.

A library crate is a library of reusable components that can be included in another library crate or in a binary crate.

Body:
While reading the official book, I stumbled upon packages and crates. To create a new "project", this is what I ran:

$ cargo new my-project
     Created binary (application) `my-project` package
$ ls my-project
Cargo.toml
src
$ ls my-project/src
main.rs

The book states the following:

A package must contain zero or one library crates, and no more. It can contain as many binary crates as you’d like, but it must contain at least one crate (either library or binary).

My doubt is, what is the difference between binary crates and normal crates?


问:
string split into lines php by pattern
I have a string like this:

```<code>1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps
</code>```

I want to split the string into two strings like this:

```<code>192.168.122.1 0.89 Bps
192.168.122.10 0.25 Bps
</code>```

答:
Are they always guaranteed to be in that order? Is anything static, what changes, etc.?

Not really enough criteria here, but you'll probably be looking at exploding spaces and going from there...

```<code><?php
$str = "1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps";
$arr = explode(" ", $str);
$your_result = "{$str[1]} {$str[3]} {$str[4]}\n{$str[6]} {$str[7]} {$str[8]}";
?>
</code>```

Title: string split into lines php by pattern

Body:
I have a string like this:

1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps

I want to split the string into two strings like this:

192.168.122.1 0.89 Bps
192.168.122.10 0.25 Bps

Body:
Are they always guaranteed to be in that order? Is anything static, what changes, etc.?

Not really enough criteria here, but you'll probably be looking at exploding spaces and going from there...

<?php
$str = "1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps";
$arr = explode(" ", $str);
$your_result = "{$str[1]} {$str[3]} {$str[4]}\n{$str[6]} {$str[7]} {$str[8]}";
?>


问:
Replacing one value in a time series when it appears more than once
I am trying to replace a value in a python Series, the clue here is that I want to replace it only once, for instance:

```<code>S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])
</code>```

The number 2 is repeated 3 times and I want to replace only the "second" 2 for 4,
I don't want to replace all the '2' numbers within the series.

Is there any way to do it?

Thank you in advance

答:
You can do the following:

In my code min_pos gets you the first position where 2 is in the Series.
We then look for the index of the next position where 2 appears in the Series using iloc to filter the first occurrence.

```<code>import pandas as pd

S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])
min_pos = S[S==2].idxmin(2)
replace_idx = S.iloc[min_pos+1:].idxmin(2)
S.iloc[replace_idx] = 'new'

print(S)
</code>```

Output

```<code> 0      0
1      1
2      2
3      3
4    new
5      5
6      2
7      6
</code>```

Body:
I am trying to replace a value in a python Series, the clue here is that I want to replace it only once, for instance:

S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])

The number 2 is repeated 3 times and I want to replace only the "second" 2 for 4,
I don't want to replace all the '2' numbers within the series.

Is there any way to do it?

Thank you in advance

Body:
You can do the following:

In my code min_pos gets you the first position where 2 is in the Series.
We then look for the index of the next position where 2 appears in the Series using iloc to filter the first occurrence.

import pandas as pd

S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])
min_pos = S[S==2].idxmin(2)
replace_idx = S.iloc[min_pos+1:].idxmin(2)
S.iloc[replace_idx] = 'new'

print(S)

Output

 0      0
1      1
2      2
3      3
4    new
5      5
6      2
7      6


问:
JavaFX Maven jfx:jar error: Could not find artifact javafx-packager
I am trying to build an executable file using JavaFX and Maven.

'clean javafx:run' is working fine but when I run 'mvn clean jfx:jar' (in eclipse or cmd) I get this error:

```<code>[ERROR] Failed to execute goal com.zenjava:javafx-maven-plugin:8.8.3:jar (default-cli) on project inkoop: Execution default-cli of goal com.zenjava:javafx-maven-plugin:8.8.3:jar failed: Plugin com.zenjava:javafx-maven-plugin:8.8.3 or one of its dependencies could not be resolved: Could not find artifact javafx-packager:javafx-packager:jar:1.8.0_20 at specified path C:\Program Files\Java\jdk-13.0.2/../lib/ant-javafx.jar -> [Help 1]
</code>```

.

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>nl.myname.programs</groupId>
<artifactId>name</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>13</version>
    </dependency>

    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>13</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.4</version>
            <configuration>
                <mainClass>nl.myname.programs.name.App</mainClass>
                <executable>C:/Program Files/Java/jdk-13.0.2/bin/java</executable>
            </configuration>
        </plugin>

        <plugin>
            <groupId>com.zenjava</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>8.8.3</version>
            <configuration>
                <jfxMainAppJarName>${project.build.finalName}.jar</jfxMainAppJarName>
                <mainClass>nl.myname.programs.name.App</mainClass>
            </configuration>
        </plugin>

    </plugins>
</build>
</code>```

My path has both %JAVA_HOME%\bin and C:\Program Files\apache-maven-3.6.3\bin (%JAVA_HOME is set to C:\Program Files\Java\jdk-13.0.2)

Is there any way I can build my application?

Do I need both javax-maven-plugin's?
Thanks for helping!

答:
AFAIK, the com.zenjava:javafx-maven-plugin does not work with Java 11+ / JavaFX 11+.

Just use the org.openjfx:javafx-maven-plugin with Java 11+ / JavaFX 11+.

Body:
I am trying to build an executable file using JavaFX and Maven.

'clean javafx:run' is working fine but when I run 'mvn clean jfx:jar' (in eclipse or cmd) I get this error:

[ERROR] Failed to execute goal com.zenjava:javafx-maven-plugin:8.8.3:jar (default-cli) on project inkoop: Execution default-cli of goal com.zenjava:javafx-maven-plugin:8.8.3:jar failed: Plugin com.zenjava:javafx-maven-plugin:8.8.3 or one of its dependencies could not be resolved: Could not find artifact javafx-packager:javafx-packager:jar:1.8.0_20 at specified path C:\Program Files\Java\jdk-13.0.2/../lib/ant-javafx.jar -> [Help 1]

.

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>nl.myname.programs</groupId>
<artifactId>name</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>13</version>
    </dependency>

    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>13</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.4</version>
            <configuration>
                <mainClass>nl.myname.programs.name.App</mainClass>
                <executable>C:/Program Files/Java/jdk-13.0.2/bin/java</executable>
            </configuration>
        </plugin>

        <plugin>
            <groupId>com.zenjava</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>8.8.3</version>
            <configuration>
                <jfxMainAppJarName>${project.build.finalName}.jar</jfxMainAppJarName>
                <mainClass>nl.myname.programs.name.App</mainClass>
            </configuration>
        </plugin>

    </plugins>
</build>

My path has both %JAVA_HOME%\bin and C:\Program Files\apache-maven-3.6.3\bin (%JAVA_HOME is set to C:\Program Files\Java\jdk-13.0.2)

Is there any way I can build my application?

Do I need both javax-maven-plugin's?
Thanks for helping!


问:
django-table2 - Change background color for entire row depending on the value of specific column
I have been trying to highlight an entire row of a table with django-table2 package.

I managed to change font color of one record doing the below:

```<code>def render_MyValue(self, value, column, record):
   if record['Warning']:
       column.attrs = {'td': {'style': 'color:darkorange;'}}
   else:
       column.attrs = {'td': {'style': 'color:black;'}}
   return value
</code>```

Find below my table class:

```<code>class DetailedReportTable(tables.Table):
    MyValue = tables.Column(orderable=False, verbose_name='Value')
    ...
    Warning = tables.Column(orderable=False, visible=False)
</code>```

The problem is I cannot find how to set the background of the row in orange if Warning is True.

Following the doc here I tried also the below:

```<code>class DetailedReportTable(tables.Table):
    ...

    class Meta:
        row_attrs = { "bg-color": lambda record: "#8B0000" if record['Warning'] else "#000000" }
</code>```

But this is doing nothing...

How can you change background color for a row using django-table2 ?

答:
What you've tried is close, but you're just setting an attribute of "bg-color" on the row html element - that attribute doesn't exist. Instead, you want to set either a class, which you can style in CSS, or directly set a style attribute. Here's the second option:

class DetailedReportTable(tables.Table):
    ...

    class Meta:
        row_attrs = { "style": lambda record: "background-color: #8B0000;" if record['Warning'] else "background-color: #000000;" }
```

Body:
I have been trying to highlight an entire row of a table with django-table2 package.

I managed to change font color of one record doing the below:

def render_MyValue(self, value, column, record):
   if record['Warning']:
       column.attrs = {'td': {'style': 'color:darkorange;'}}
   else:
       column.attrs = {'td': {'style': 'color:black;'}}
   return value

Find below my table class:

class DetailedReportTable(tables.Table):
    MyValue = tables.Column(orderable=False, verbose_name='Value')
    ...
    Warning = tables.Column(orderable=False, visible=False)

The problem is I cannot find how to set the background of the row in orange if Warning is True.

Following the doc here I tried also the below:

class DetailedReportTable(tables.Table):
    ...

    class Meta:
        row_attrs = { "bg-color": lambda record: "#8B0000" if record['Warning'] else "#000000" }

But this is doing nothing...

How can you change background color for a row using django-table2 ?


问:
Can I use Sql Server CE (3.0) as an embedded database for my windows application? Do I have to install Sql Server CE in the machine?
I created a windows application and I needed a database for it. I first used SQL Server Express edition in it. Then I came to know that it is not exactly a portable database. That is, SQL Server Express edition should be already installed in the computer where I suppose to use my application. I came to know that I can use SQL CE instead and changed to it. I found somewhere that all I have to do is just copy the sqlceme30.dll in the application. Worked fine in my developement system. But when I copy the application to another system and open the application, it throws the error

```<code> System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.SqlServerCe, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
</code>```

Can I use SQL CE in my application? I really don't want to install it in all the machines I use my app. Or if not, which other db I can use without intalling? Access?

答: Ensure your reference is set to Copy Local. Right click on the reference, and click properties. They change the Copy Local property to true. That will ensure that the dll is included in the publish.

Body:
I created a windows application and I needed a database for it. I first used SQL Server Express edition in it. Then I came to know that it is not exactly a portable database. That is, SQL Server Express edition should be already installed in the computer where I suppose to use my application. I came to know that I can use SQL CE instead and changed to it. I found somewhere that all I have to do is just copy the sqlceme30.dll in the application. Worked fine in my developement system. But when I copy the application to another system and open the application, it throws the error

 System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.SqlServerCe, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Can I use SQL CE in my application? I really don't want to install it in all the machines I use my app. Or if not, which other db I can use without intalling? Access?


问:
How add ScrollMagic in nuxt project?
I am trying to add ScollMagic in my Nuxt project, I followed this article: https://nuxtjs.org/guide/plugins & I've added ScrollMagic.js in nuxt.config.js and I got this issue: ReferenceError window is not defined.

```<code>module.exports = {
 plugins: [
    { src: '~plugins/ScrollMagic', mode: 'client' }
  ],
}

Then I've added this snippet in my component:
import ScrollMagic from 'scrollmagic'
</code>```

I still have this issue...

Even if cover it like this:

```<code>if (process.client) {
  Vue.use(ScrollMagic)
}
</code>```

答:
currently what works is to use the cdn and integrate in 'nuxt.config.js'.
Like this :

```<code>      head: {
...
script: [
  {
    src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js",
    async: 'async',
    ssr: false,
    defer: true,
    body: true,
  },
  {
    src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js",
    async: 'async',
    ssr: false,
    defer: true,
    body: true,
  },
] },
</code>```

in the component :

```<code>export default {
mounted () {
  if (process.client) {
    var controller = new ScrollMagic.Controller()
    var scene = new ScrollMagic.Scene({ triggerElement: '#trigger1' })

      // exemple : trigger animation by adding a css class

      .setClassToggle('#animate1', 'zap')
      .addIndicators({ name: '1 - add a class' }) // add indicators (requires plugin)
      .addTo(controller)
  }
}}
</code>```

you can use this method for other puglins that wouldn't work on nuxt by using npm or [puglins]

Title: How add ScrollMagic in nuxt project?

Body:
I am trying to add ScollMagic in my Nuxt project, I followed this article: https://nuxtjs.org/guide/plugins & I've added ScrollMagic.js in nuxt.config.js and I got this issue: ReferenceError window is not defined.

module.exports = {
 plugins: [
    { src: '~plugins/ScrollMagic', mode: 'client' }
  ],
}

Then I've added this snippet in my component:
import ScrollMagic from 'scrollmagic'

I still have this issue...

Even if cover it like this:

if (process.client) {
  Vue.use(ScrollMagic)
}

Body:
currently what works is to use the cdn and integrate in 'nuxt.config.js'.
Like this :

      head: {
...
script: [
  {
    src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js",
    async: 'async',
    ssr: false,
    defer: true,
    body: true,
  },
  {
    src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js",
    async: 'async',
    ssr: false,
    defer: true,
    body: true,
  },
] },

in the component :

export default {
mounted () {
  if (process.client) {
    var controller = new ScrollMagic.Controller()
    var scene = new ScrollMagic.Scene({ triggerElement: '#trigger1' })

      // exemple : trigger animation by adding a css class

      .setClassToggle('#animate1', 'zap')
      .addIndicators({ name: '1 - add a class' }) // add indicators (requires plugin)
      .addTo(controller)
  }
}}

you can use this method for other puglins that wouldn't work on nuxt by using npm or [puglins]


问:
Increment all entries in an array by 'n' without a for loop
I have an array:

arr = [5,5,5,5,5,5]

I want to increment a particular range in the arr by 'n'. So if n=2 and the range is [2,5].
The array should look like this:

arr = [5,5,7,7,7,5]

Needed to do this without a for loop, for a problem im trying to solve.

Tried:

arr[2:5] = [n]*3

but that obviously replaces the entries and becomes:

arr = [5,5,3,3,3,5]

Any suggestions would be highly appriciated.

答:
You actually have a list, not an array. If you convert it to a Numpy array it is simple. </p>

```<code>>>> n=3
>>> arr = np.array([5,5,5,5,5,5])
>>> arr[2:5] += n
>>> arr
array([5, 5, 8, 8, 8, 5])
</code>```

Body:
You actually have a list, not an array. If you convert it to a Numpy array it is simple.

>>> n=3
>>> arr = np.array([5,5,5,5,5,5])
>>> arr[2:5] += n
>>> arr
array([5, 5, 8, 8, 8, 5])


问:
How do I search for a specific element in my ListView?
I have a listView, that is represented as a gridView. I have added a search bar with a TextController.
The Grid view has individual elements that have a name and an age called in it. I want the search query to search the names and show only the related elements.

```<code>List<Map> itemList = [
{
  'Name':"Bob",
  'Age':"24"
}
{
  'Name':"Billy",
  'Age':"34"
}
]
</code>```

This is the representation of my GridView:

```<code>  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return GridView.count(
              mainAxisSpacing: 32.0,
              crossAxisSpacing: 32.0,
              childAspectRatio: 0.8,
              shrinkWrap: true,
              physics: ClampingScrollPhysics(),
              padding: const EdgeInsets.all(8),
              crossAxisCount: 2,

              children: List<Widget>.generate(
                itemList.length,
                (int index) {
                  return GestureDetector(
                    onTap: () => _goToItemViewer(itemList[index]),
                    child: CategoryView(
                      callback: () {

                      },
                      item: itemList[index],
                    ),
                  );
                },
              ),
            );
          }
        },
      ),
    );
  }
}

class CategoryView extends StatefulWidget {
  final Map item;
  const CategoryView({Key key, this.callback, this.item}) : super(key: key);

  final VoidCallback callback;

  @override
  CategoryViewState createState() => CategoryViewState();
}

class CategoryViewState extends State<CategoryView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        splashColor: Colors.transparent,
        child: SizedBox(
          height: 280,
          child: Stack(
            alignment: AlignmentDirectional.bottomCenter,
            children: <Widget>[
              Container(
                child: Container(
                  child: Column(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Color(0xfff8fafb),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(16.0)),

                          ),
                          child: Column(
                            children: <Widget>[
                              Expanded(
                                child: Container(
                                  child: Column(
                                    children: <Widget>[
                                      Padding(
                                        padding: const EdgeInsets.only(
                                            top: 16, left: 16, right: 16),
                                        child: Text(
                                          widget.item['Name'],
                                          textAlign: TextAlign.left,
                                          style: TextStyle(
                                            fontWeight: FontWeight.w600,
                                            fontFamily: "Netflix",
                                            fontSize: 16,
                                            letterSpacing: 0.27,
                                            color:
                                                Color(0xFF17262A),
                                          ),
                                        ),
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.only(
                                            top: 8,
                                            left: 16,
                                            right: 16,
                                            bottom: 8),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: <Widget>[],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              const SizedBox(
                                width: 48,
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 48,
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                child: Padding(
                  padding: const EdgeInsets.only(top: 24, right: 16, left: 16),
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius:
                          const BorderRadius.all(Radius.circular(16.0)),
                      boxShadow: <BoxShadow>[
                        BoxShadow(
                            color: Color(0xFF3A5160).withOpacity(0.2),
                            offset: const Offset(0.0, 0.0),
                            blurRadius: 6.0),
                      ],
                    ),
                    child: ClipRRect(
                      borderRadius:
                          const BorderRadius.all(Radius.circular(16.0)),
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: Image(
                          image: NetworkImage(

                            widget.item['Age'],
                          ),
                          fit: BoxFit.fill, // use this
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

My SearchBar is called separately:

```<code>Container(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                onChanged: (value) {

                },
                controller: editingController,
                decoration: InputDecoration(
                    labelText: "Search",
                    hintText: "Search",
                    prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(25.0)))),

              ),
            ),
          ],),),
</code>```

I need a way to make a duplicate list to search the elements in the given list and show only those elements.

答:
Here is a complete example.
Do it like this:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

// Main code starts here // Your widget must be stateful
class MyWidget extends StatefulWidget {
  @override
  createState() => _MyWidgetState();
}

// Here is the list of all your people
List<Map> people = [
  {
    'name': 'John',
    'age': 25
  },
  {
    'name': 'Billy',
    'age': 21
  },
  {
    'name': 'Bob',
    'age': 18
  },
  {
    'name': 'Kate',
    'age': 23
  },
  {
    'name': 'Rose',
    'age': 18
  },
  {
    'name': 'David',
    'age': 42
  },
  {
    'name': 'Marc',
    'age': 42
  },
  {
    'name': 'Sophie',
    'age': 38
  },
  {
    'name': 'Bill',
    'age': 77
  },
];

class _MyWidgetState extends State<MyWidget> {
  List<Map> _filtered = people.toList(); // Make a copy of the original list
  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose(); // Remember to dispose the controller
    super.dispose();
  }

  // This method filters the '_filtered' list according to the key
  void filter(String match) {
    setState(() {
      _filtered = people
          .where((data) => data['name'].toLowerCase().contains(match.toLowerCase()))
          .toList();
    }); // Set state to notify flutter that the widget must be rebuilt
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            controller: _controller,
            onChanged: filter, // When the text is changed, this method is called, You can do it as lambda too (match) => ....
          ),
        ),
        SizedBox(height: 20),
        Expanded(
          // I have used list view but you can use your own widget like a grid view. The idea is same for both cases
          child: ListView.builder(
            physics: BouncingScrollPhysics(),
            itemCount: _filtered.length, // Filtered list length
            itemBuilder: (context, i) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(_filtered[i]['name'] + ', Age: ' + _filtered[i]['age'].toString(),), // Put your data this way
              );
            },
          ),
        )
      ],
    );
  }
}
</code>```

Here is the result:

And after you start entering text:

Body:
I have a listView, that is represented as a gridView. I have added a search bar with a TextController.
The Grid view has individual elements that have a name and an age called in it. I want the search query to search the names and show only the related elements.

List<Map> itemList = [
{
  'Name':"Bob",
  'Age':"24"
}
{
  'Name':"Billy",
  'Age':"34"
}
]

This is the representation of my GridView:

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return GridView.count(
              mainAxisSpacing: 32.0,
              crossAxisSpacing: 32.0,
              childAspectRatio: 0.8,
              shrinkWrap: true,
              physics: ClampingScrollPhysics(),
              padding: const EdgeInsets.all(8),
              crossAxisCount: 2,

              children: List<Widget>.generate(
                itemList.length,
                (int index) {
                  return GestureDetector(
                    onTap: () => _goToItemViewer(itemList[index]),
                    child: CategoryView(
                      callback: () {

                      },
                      item: itemList[index],
                    ),
                  );
                },
              ),
            );
          }
        },
      ),
    );
  }
}

class CategoryView extends StatefulWidget {
  final Map item;
  const CategoryView({Key key, this.callback, this.item}) : super(key: key);

  final VoidCallback callback;

  @override
  CategoryViewState createState() => CategoryViewState();
}

class CategoryViewState extends State<CategoryView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        splashColor: Colors.transparent,
        child: SizedBox(
          height: 280,
          child: Stack(
            alignment: AlignmentDirectional.bottomCenter,
            children: <Widget>[
              Container(
                child: Container(
                  child: Column(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Color(0xfff8fafb),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(16.0)),

                          ),
                          child: Column(
                            children: <Widget>[
                              Expanded(
                                child: Container(
                                  child: Column(
                                    children: <Widget>[
                                      Padding(
                                        padding: const EdgeInsets.only(
                                            top: 16, left: 16, right: 16),
                                        child: Text(
                                          widget.item['Name'],
                                          textAlign: TextAlign.left,
                                          style: TextStyle(
                                            fontWeight: FontWeight.w600,
                                            fontFamily: "Netflix",
                                            fontSize: 16,
                                            letterSpacing: 0.27,
                                            color:
                                                Color(0xFF17262A),
                                          ),
                                        ),
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.only(
                                            top: 8,
                                            left: 16,
                                            right: 16,
                                            bottom: 8),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: <Widget>[],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              const SizedBox(
                                width: 48,
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 48,
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                child: Padding(
                  padding: const EdgeInsets.only(top: 24, right: 16, left: 16),
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius:
                          const BorderRadius.all(Radius.circular(16.0)),
                      boxShadow: <BoxShadow>[
                        BoxShadow(
                            color: Color(0xFF3A5160).withOpacity(0.2),
                            offset: const Offset(0.0, 0.0),
                            blurRadius: 6.0),
                      ],
                    ),
                    child: ClipRRect(
                      borderRadius:
                          const BorderRadius.all(Radius.circular(16.0)),
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: Image(
                          image: NetworkImage(

                            widget.item['Age'],
                          ),
                          fit: BoxFit.fill, // use this
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

My SearchBar is called separately:

Container(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                onChanged: (value) {

                },
                controller: editingController,
                decoration: InputDecoration(
                    labelText: "Search",
                    hintText: "Search",
                    prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(25.0)))),

              ),
            ),
          ],),),

I need a way to make a duplicate list to search the elements in the given list and show only those elements.

Body:
Here is a complete example.
Do it like this:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

// Main code starts here // Your widget must be stateful
class MyWidget extends StatefulWidget {
  @override
  createState() => _MyWidgetState();
}

// Here is the list of all your people
List<Map> people = [
  {
    'name': 'John',
    'age': 25
  },
  {
    'name': 'Billy',
    'age': 21
  },
  {
    'name': 'Bob',
    'age': 18
  },
  {
    'name': 'Kate',
    'age': 23
  },
  {
    'name': 'Rose',
    'age': 18
  },
  {
    'name': 'David',
    'age': 42
  },
  {
    'name': 'Marc',
    'age': 42
  },
  {
    'name': 'Sophie',
    'age': 38
  },
  {
    'name': 'Bill',
    'age': 77
  },
];

class _MyWidgetState extends State<MyWidget> {
  List<Map> _filtered = people.toList(); // Make a copy of the original list
  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose(); // Remember to dispose the controller
    super.dispose();
  }

  // This method filters the '_filtered' list according to the key
  void filter(String match) {
    setState(() {
      _filtered = people
          .where((data) => data['name'].toLowerCase().contains(match.toLowerCase()))
          .toList();
    }); // Set state to notify flutter that the widget must be rebuilt
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            controller: _controller,
            onChanged: filter, // When the text is changed, this method is called, You can do it as lambda too (match) => ....
          ),
        ),
        SizedBox(height: 20),
        Expanded(
          // I have used list view but you can use your own widget like a grid view. The idea is same for both cases
          child: ListView.builder(
            physics: BouncingScrollPhysics(),
            itemCount: _filtered.length, // Filtered list length
            itemBuilder: (context, i) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(_filtered[i]['name'] + ', Age: ' + _filtered[i]['age'].toString(),), // Put your data this way
              );
            },
          ),
        )
      ],
    );
  }
}

Here is the result:

And after you start entering text: