问:
PHP: substr runway loop
Here's a part of my code

```<code>    $hold = $this->content;
    $hold_table = array();
    for($i=0; $i<strlen($hold); $i++){
        $t = substr($hold, $i, 10);
        $count = substr_count($hold, $t);
        if($count > 1){
            $hold = str_replace($t, '', $hold); //Just iterating for now to get counts
            $hold_table[bin2hex($t)] = $count;
        }
    }
</code>```

$this->content is a file that is read in.

If the "10" in this line: $t = substr($hold, $i, 10); is 10 or lower, it works fine and spits out the result fine.

If I change the 10 to say, "15".  The script just hangs in a loop.

I don't think there is any array key size limitations that I'm running in to and the "FOR" loop should end if $i > strlen($hold)

Any ideas why changing from 10 to 15 causes chaos?

答: You are changing $hold along the way by your str_replace statement (shortening it basically). I think that's producing some unexpected results.</p>

Title: PHP: substr runway loop

Body:
Here's a part of my code

    $hold = $this->content;
    $hold_table = array();
    for($i=0; $i<strlen($hold); $i++){
        $t = substr($hold, $i, 10);
        $count = substr_count($hold, $t);
        if($count > 1){
            $hold = str_replace($t, '', $hold); //Just iterating for now to get counts
            $hold_table[bin2hex($t)] = $count;
        }
    }

$this->content is a file that is read in.

If the "10" in this line: $t = substr($hold, $i, 10); is 10 or lower, it works fine and spits out the result fine.

If I change the 10 to say, "15".  The script just hangs in a loop.

I don't think there is any array key size limitations that I'm running in to and the "FOR" loop should end if $i > strlen($hold)

Any ideas why changing from 10 to 15 causes chaos?


来源: stackexchange

问:
Pandas drop duplicates across columns
Good day,

I need a way to check each row of a dataframe and drop the row if all the values in that row (across the score columns) are the same. The person_id may differ.

Here is a part of the dataset:

In:

```<code>data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df
</code>```

Out:

```<code>    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7
</code>```

The desired output would be:

```<code>    person_id   score_1 score_2 score_3 score_4
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7
</code>```

Since row 0 (person_id 7) and row 1 (person_id 17) have the same scores.
The number of columns will also change, adding more score columns - thus, I cannot use

```<code>df_no_duplicates = df.loc[(df.score_1 != df.score_2) | (df.score_2 != df.score_3)| (df.score_3 != df.score_4)]
</code>```

答:
You can try nunique

```<code>out = df[df.filter(like='score').nunique(1)>1].copy()
Out[208]:
   person_id  score_1  score_2  score_3  score_4
2         18        8       10       10       10
3         20       10       10        9        9
4         25        9        8        8        7
</code>```

ContentLicense: CC BY-SA 4.0

Title: Pandas drop duplicates across columns

Body:
Good day,

I need a way to check each row of a dataframe and drop the row if all the values in that row (across the score columns) are the same. The person_id may differ.

Here is a part of the dataset:

In:

data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df

Out:

    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7

The desired output would be:

    person_id   score_1 score_2 score_3 score_4
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7

Since row 0 (person_id 7) and row 1 (person_id 17) have the same scores.
The number of columns will also change, adding more score columns - thus, I cannot use

df_no_duplicates = df.loc[(df.score_1 != df.score_2) | (df.score_2 != df.score_3)| (df.score_3 != df.score_4)]

Body:
You can try nunique

out = df[df.filter(like='score').nunique(1)>1].copy()
Out[208]:
   person_id  score_1  score_2  score_3  score_4
2         18        8       10       10       10
3         20       10       10        9        9
4         25        9        8        8        7


问:
How to identify labels on a Python Tkinter Tab in the event handler
I am placing labels on a Tab in Tkinter with a for loop. How can I identify in the event handler which label was clicked (or its loop index)? I guess it is functionally similar to a ListBox but without the formatting restrictions. I might want to put the labels in a circle or place them diagonally. I tried finding the coordinates of the label but these are available only if the tab is the first one visible or the tab is redrawn when made active. Also the x, y passed in the event handler is the x, y within the label which does not help to identify the label.

I could copy the label code about 10 times and and have about 10 event handlers. This would work but this is no longer 1970!

Perhaps I could bind a handler to the tab canvas and identify the label from its coordinates. The label would need to be on the first tab or the tab drawn when active.

Perhaps I could create a different event handler for each label by holding the event handlers in an array. I would need an event handler for each label. The code would need to change if the number of labels changed.

I am currently trying a label with ''. Would using buttons with command be easier?

What simple part of Python am I missing? I cannot be the first person to need this! Any help or advice would be appreciated.

答:
You can save a reference to the label text for each label widget in a dict.

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry('+800+50')

notebook = ttk.Notebook(root, width=300, height=200, padding=[10,10,10,10])
notebook.pack()
tab_one = tk.Frame(notebook, bg='wheat')
notebook.add(tab_one, text='Cheese', padding=[10,10,10,10])
tab_two = tk.Frame(notebook, bg='mint cream')
notebook.add(tab_two, text='Misc.', padding=[10,10,10,10])

def clicked(event):
    print('Clicked:', name_dict[event.widget])

# Populating Cheese tab with clickable Labels
name_list = ['Cheddar', 'Ilchester', 'Limburger']
name_dict = {}
for index, name in enumerate(name_list):
    a = tk.Label(tab_one, width=10, text=name, bg='peru')
    a.grid(row=index, column=0, padx=5, pady=5)
    name_dict[a] = name     # Save references in a dict
    a.bind('<Button-1>', clicked)

tk.Label(tab_two, text='Just some text...', bg='powder blue').pack(anchor='nw')

root.mainloop()
</code>```

Is this what you had in mind?

Body:
You can save a reference to the label text for each label widget in a dict.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry('+800+50')

notebook = ttk.Notebook(root, width=300, height=200, padding=[10,10,10,10])
notebook.pack()
tab_one = tk.Frame(notebook, bg='wheat')
notebook.add(tab_one, text='Cheese', padding=[10,10,10,10])
tab_two = tk.Frame(notebook, bg='mint cream')
notebook.add(tab_two, text='Misc.', padding=[10,10,10,10])

def clicked(event):
    print('Clicked:', name_dict[event.widget])

# Populating Cheese tab with clickable Labels
name_list = ['Cheddar', 'Ilchester', 'Limburger']
name_dict = {}
for index, name in enumerate(name_list):
    a = tk.Label(tab_one, width=10, text=name, bg='peru')
    a.grid(row=index, column=0, padx=5, pady=5)
    name_dict[a] = name     # Save references in a dict
    a.bind('<Button-1>', clicked)

tk.Label(tab_two, text='Just some text...', bg='powder blue').pack(anchor='nw')

root.mainloop()

Is this what you had in mind?


问:
Problem with CSV import from stage (curly brackets)
I am trying to import csv file from stage and I am getting the error below

Found character '}' instead of field delimiter ';'

My data in csv. looks like

0911220;NULL;{{lorem.ipsum}};{{bla.bla}}

I don't know what to do. I don't have anything related to curly braces set in File Format. Should I change something there?

The file format is:

```<code>ALTER FILE FORMAT "RAW"."CRM".CSV_SEMICOLON_QUOTES_HEADER
    SET
    COMPRESSION = 'AUTO'
    FIELD_DELIMITER = ';'
    RECORD_DELIMITER = '\n'
    SKIP_HEADER = 1
    FIELD_OPTIONALLY_ENCLOSED_BY = '\042'
    TRIM_SPACE = FALSE
    ERROR_ON_COLUMN_COUNT_MISMATCH = TRUE
    ESCAPE = 'NONE'
    ESCAPE_UNENCLOSED_FIELD = 'NONE'
    DATE_FORMAT = 'AUTO'
    TIMESTAMP_FORMAT = 'AUTO'
    NULL_IF = ('\\N');
</code>```

And method of import:

```<code>copy into "..." ( list of columns )
    FROM @stage_name files = ( 'file.zip') file_format = (
        format_name=CSV_SEMICOLON_QUOTES_HEADER compression=GZIP);
</code>```

答:
The file format name is wrong in the copy into ... query.

The file format you created is named as CSV_SEMICOLON_QUOTES_HEADER2. but in your query you wrote ..HEADER instead of ..HEADER2

Body:
I am trying to import csv file from stage and I am getting the error below

Found character '}' instead of field delimiter ';'

My data in csv. looks like

0911220;NULL;{{lorem.ipsum}};{{bla.bla}}

I don't know what to do. I don't have anything related to curly braces set in File Format. Should I change something there?

The file format is:

ALTER FILE FORMAT "RAW"."CRM".CSV_SEMICOLON_QUOTES_HEADER
    SET
    COMPRESSION = 'AUTO'
    FIELD_DELIMITER = ';'
    RECORD_DELIMITER = '\n'
    SKIP_HEADER = 1
    FIELD_OPTIONALLY_ENCLOSED_BY = '\042'
    TRIM_SPACE = FALSE
    ERROR_ON_COLUMN_COUNT_MISMATCH = TRUE
    ESCAPE = 'NONE'
    ESCAPE_UNENCLOSED_FIELD = 'NONE'
    DATE_FORMAT = 'AUTO'
    TIMESTAMP_FORMAT = 'AUTO'
    NULL_IF = ('\\N');

And method of import:

copy into "..." ( list of columns )
    FROM @stage_name files = ( 'file.zip') file_format = (
        format_name=CSV_SEMICOLON_QUOTES_HEADER compression=GZIP);


问:
Avoid executing event's default action. `event.cancelable` vs `event.preventDefault`?
When I don't want to execute the default action that is associated with the event, I use

```<code>function listener(e){
    if(e.preventDefault) e.preventDefault();
    /* Other code */
}
</code>```

But I have just learnt that events have the boolean cancelable. Then, should I use this code instead?

```<code>function listener(e){
    if(e.cancelable) e.preventDefault();
    /* Other code */
}
</code>```

I wonder:

If event.preventDefault is true, does it really mean that the event is cancelable? Maybe if it isn't cancelable, that attribute is defined (and true), but it isn't a function; or it's a function but if I call it it throws an error.

Does all browsers (IE, I'm looking at you) support event.cancelable? Is there a browser which has the method event.preventDefault but doesn't have event.cancelable; or has the method event.cancelable but doesn't have event.preventDefault; or that event.cancelable doesn't always imply that event.preventDefault is defined and it's a function and it doesn't throw errors?

答:
First you can check if the event is cancelable. Know that not all events are cancelable, for example the change event.

After that you check if the event has been defaultPrevented.

if (!event.cancelable || !event.defaultPrevented) {
  // execute the event logic, because the previous event didn't prevented it
}
```

The cancelable check is optional, but I use it to remind myself that not all events are cancelable.

Body:
When I don't want to execute the default action that is associated with the event, I use

function listener(e){
    if(e.preventDefault) e.preventDefault();
    /* Other code */
}

But I have just learnt that events have the boolean cancelable. Then, should I use this code instead?

function listener(e){
    if(e.cancelable) e.preventDefault();
    /* Other code */
}

I wonder:

If event.preventDefault is true, does it really mean that the event is cancelable? Maybe if it isn't cancelable, that attribute is defined (and true), but it isn't a function; or it's a function but if I call it it throws an error.

Does all browsers (IE, I'm looking at you) support event.cancelable? Is there a browser which has the method event.preventDefault but doesn't have event.cancelable; or has the method event.cancelable but doesn't have event.preventDefault; or that event.cancelable doesn't always imply that event.preventDefault is defined and it's a function and it doesn't throw errors?

Body:
First you can check if the event is cancelable. Know that not all events are cancelable, for example the change event.

After that you check if the event has been defaultPrevented.

if (!event.cancelable || !event.defaultPrevented) {
  // execute the event logic, because the previous event didn't prevented it
}

The cancelable check is optional, but I use it to remind myself that not all events are cancelable.


问:
Get meta from podcast episode into wordpress template
Is there a way to get the Podcast Name, Episode Title, and Date through a link inserted in a wordpress post?
I'm using ACF plugin where the user may insert a podcast link.

Like what happens when I paste a link in WhatsApp, and an information with appears containing even an image or a logo from the website pasted.

Thank you.
AMP.

答:
Yes!

Option 1

You could hook into the save_post hook, get the url that has been supplied, grab the data from that url with either curl / file_get_contents / whatever and then save the data as post meta for that post.

On the frontend, you can grab the saved data from the post meta.

Option 2

You could also grab the data on the frontend. Either with php in wordpress, or on the client side with js (e.g. axios or fetch). You get the acf link and pass it to e.g. window.WP_VARS, for your clientside code to use it. I e.g. use this to pass generic vars to my clientside code:

```<code>  wp_register_script('mainjs', get_template_directory_uri() . '/js/main.js', array(), REL_VERSION, true);
  wp_localize_script('mainjs', 'WP_VARS', $generic_vars);
  wp_enqueue_script('mainjs');
</code>```

The advantage of this is that you don't have to store and grab this data from your database. Make sure that the fetch is non blocking, so do it on page ready.

Body:
Yes!

Option 1

You could hook into the save_post hook, get the url that has been supplied, grab the data from that url with either curl / file_get_contents / whatever and then save the data as post meta for that post.

On the frontend, you can grab the saved data from the post meta.

Option 2

You could also grab the data on the frontend. Either with php in wordpress, or on the client side with js (e.g. axios or fetch). You get the acf link and pass it to e.g. window.WP_VARS, for your clientside code to use it. I e.g. use this to pass generic vars to my clientside code:

  wp_register_script('mainjs', get_template_directory_uri() . '/js/main.js', array(), REL_VERSION, true);
  wp_localize_script('mainjs', 'WP_VARS', $generic_vars);
  wp_enqueue_script('mainjs');

The advantage of this is that you don't have to store and grab this data from your database. Make sure that the fetch is non blocking, so do it on page ready.


问:
What could be causing incessant calls to my Telegram webhook?
I have a simple PHP script (using Botman) called by my Telegram bot via a webhook. It's supposed to respond on receiving a keyword. This works, sending response messages to my phone.

Randomly however it repeats the messages, without any input. Though random, its so frequent I would estimate it does this at least 10 times per minute.

Thinking this could be due to some web bots calling my URL, I modified the script to check the presence (and value of) and query parameter and all random messages stopped. The web bots wouldn't know this secret parameter, right?

As expected, once I updated the PHP script (without updating Telegram with the modified webhook), the messages stopped. So far so good.

Next, updated the Telegram with the webhook containing the secret query parameter, then waited 5 minutes. No messages: still looking good.

Alas, once I send my keyword, it gives the expected response but then keeps repeating endlessly again.

Where do I look to fix this?

Ps. To test, the script also returns general info of the user. I can see it keeps returning my info in the repeated message, as if I made each request. Could this be a bug with Telegram?

答:
According to your description, it seems that your webhook architecture it still looking for the most recent updates returned by Telegram getUpdates method: if your script repeats answering to the same exact message, it means that it's receiving the same exact update object more than one time.

A good solution to solve this problem could be have a look at the webhook working of, how it communicates with Telegram servers in order to understand how does it handle updates received from the Telegram Chatbot itself.


问:
Are there any good and free libraries to develop web applications in C?
I've searched the web a bit, but all I found were abandoned projects and only CGI support.

EDIT 1: C isn't just used for writing drivers or embedded systems. We have mailreaders, newsreaders, editors, etc. all written in C. I've written two BBS in the last century before the web became popular. The libraries are getting better and you don't have to reinvent the wheel over and over again. Nice data structures and string handling is easily possible in C. But yet, there's not much going on in web development.

I'd like to come back to my roots and try to write web applications in C.

As for bad languages: People use C++, Perl, and PHP for web applications. It doesn't stop them that the common perception of these languages isn't very good.

EDIT 2: I've written BBS software in C and nobody thought this was a crazy idea, although others have done it in GfA BASIC back then. I don't understand why today it should be considered a bad idea. Have a look at the software you are using or the most common programming languages in open-source software.

答: You could try libevent. It has a HTTP server.</p>

OwnerDisplayName: stesch

LastEditorDisplayName: stesch

ContentLicense: CC BY-SA 2.5


问:
Create sql query - MSSQL with distinct
I have a table with columns Id,DoucmentId,Name,Created,MinorVersion,MajorVersion

with example data  :

```<code>GUID,1,'document1',GETDATE(),1,0)
GUID,1,'document1',GETDATE(),2,0)
GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)
</code>```

In query i need get all unique with higest major and minor version :

```<code>GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)
</code>```

I have this query, but i need return all column in table...

```<code>SELECT DISTINCT
          DocumentId,
          MAX(MajorVersion),
          MAX(MinorVersion)
FROM ComDoc_Document
GROUP BY(DocumentId)
</code>```

Is here some trick to get this?

Thanks for help

EDIT : My configuration is MSSQL 2008R2 standart

答:
You need to join the original table with your result to get all columns:</p>

```<code>SELECT t1.*
FROM ComDoc_Document AS t1
INNER JOIN (SELECT
                  DocumentId,
                  MAX(MajorVersion) AS MaxMajor,
                  MAX(MinorVersion) AS MaxMinor,
            FROM ComDoc_Document
            GROUP BY DocumentId) AS t2
ON (t1.DocumentID=t2.DocumentID AND t1.MajorVersion = t2.MaxMajor AND t1.MinorVersion = t2.MaxMinor)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create sql query - MSSQL with distinct

Body:
I have a table with columns Id,DoucmentId,Name,Created,MinorVersion,MajorVersion

with example data  :

GUID,1,'document1',GETDATE(),1,0)
GUID,1,'document1',GETDATE(),2,0)
GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)

In query i need get all unique with higest major and minor version :

GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)

I have this query, but i need return all column in table...

SELECT DISTINCT
          DocumentId,
          MAX(MajorVersion),
          MAX(MinorVersion)
FROM ComDoc_Document
GROUP BY(DocumentId)

Is here some trick to get this?

Thanks for help

EDIT : My configuration is MSSQL 2008R2 standart

Body:
You need to join the original table with your result to get all columns:

SELECT t1.*
FROM ComDoc_Document AS t1
INNER JOIN (SELECT
                  DocumentId,
                  MAX(MajorVersion) AS MaxMajor,
                  MAX(MinorVersion) AS MaxMinor,
            FROM ComDoc_Document
            GROUP BY DocumentId) AS t2
ON (t1.DocumentID=t2.DocumentID AND t1.MajorVersion = t2.MaxMajor AND t1.MinorVersion = t2.MaxMinor)


问:
Huawei Map not loading tiles
I have followed the documentation here and here (which are pretty straight forward), but the map view does not load any tiles.

I use HMS Toolkit, and the Configuration Wizard results in success. I also have set my api key, using this line in both my application class and my activity class onCreate.

MapsInitializer.setApiKey(HUAWEI_API_KEY);

Here is the device information and SDK version:

Phone model: Huawei Y7 Prime 2018

EMUI version: 8.0.0

HMS Core version: 6.1.0.305

Map SDK version: com.huawei.hms:maps:6.0.0.301

Here is the screen:

Relevant error logs:

E/HmsMapKit_MapView_151: createDelegate: creator == null

E/HmsMapKit_GrsClient_24: GRS returns empty.

E/HmsMapKit_ErrorTraceLogPusher_4: cache error trace log :
ErrorTraceLogDTO{ scenario = GET_GRS_URL_FAILED', message='GRS returns
empty, service name is com.huawei.hms.map.'}

E/HmsMapKit_ErrorTraceLogPusher_12: eventId is null or empty.

E/HmsMapKit_AuthenticateClient_27: Exception occur
com.huawei.hms.maps.foundation.client.c

E/HmsMapKit_ErrorTraceLogPusher_4: cache error trace log :
ErrorTraceLogDTO{ scenario = ACCESS_SERVICE_ERROR', message='060001 :
NETWORK_ERROR'}

E/HmsMapKit_AuthenticateCache_0: authenticate error, throw
RetryException.

E/HmsMapKit_CopyrightDelegate_27: get copyright statement html data
failed: htmlData = null

E/HmsMapKit_TileCache_38: startUrlRequest Identity fail, do not has
permission get tile. authResult :060011

PS: I have the exact same problem with this demo.

答:
You need to generate and upload to AppGallery Connect two SHA-256 keys, one for debug version and one for release.

for generating key for debug version you need to:

open cmd

run command cd [path to directory with keytool.exe file]
for example: cd C:\Program Files\Java\jdk1.8.0_301\bin

run command keytool -list -v -keystore [path to debug.keystore]\debug.keystore -alias androiddebugkey -storepass android -keypass android

copy SHA-256 key and add it to AppGallery Connect -> Project Settings -> App information -> SHA-256 certificate fingerprint

for release version do everything the same, but replace the path to the key for signing the release build in 2 step and enter real release alias and password in 3 step

Title: Huawei Map not loading tiles


问:
Download zip is invalid
I have a simple aspx page where is in the codebehind I am creating a zip file and streaming it back. Everything worked fine while I kept all my code inside of page_load method. Now I am executing the code on a button click. After download Windows cannot open the zip saying it is invalid. Here is my code:

```<code><body style="height: 100%; overflow: hidden" onload="return onBodyLoad();">
<script>
    function onBodyLoad() {
        document.getElementById("ExportBtn").click();
    }
</script>

protected void ExportBtn_OnClick(object sender, EventArgs e)
{
   // prepare zip
   .....
   // send zip back
   Response.Clear();
   Response.AppendHeader("content-disposition", "attachment; filename=" + fileToDownload);
   Response.ContentType = "application/zip";
   Response.BinaryWrite(File.ReadAllBytes(zipPath));
}
</code>```

The same code wihtout a button click runs fine from the page_load which currently looks like this:

```<code>protected void Page_Load(object sender, EventArgs e)
{

}
</code>```

答: Found the problem. All I needed is Response.End(); as the last statement.</p>

Title: Download zip is invalid

Body:
I have a simple aspx page where is in the codebehind I am creating a zip file and streaming it back. Everything worked fine while I kept all my code inside of page_load method. Now I am executing the code on a button click. After download Windows cannot open the zip saying it is invalid. Here is my code:

protected void ExportBtn_OnClick(object sender, EventArgs e)
{
   // prepare zip
   .....
   // send zip back
   Response.Clear();
   Response.AppendHeader("content-disposition", "attachment; filename=" + fileToDownload);
   Response.ContentType = "application/zip";
   Response.BinaryWrite(File.ReadAllBytes(zipPath));
}

The same code wihtout a button click runs fine from the page_load which currently looks like this:

protected void Page_Load(object sender, EventArgs e)
{

}


问:
Spring-Cloud-AWS vs AWS-SDK-Java 2
Ours is a Spring-Boot based application. For integration with AWS SNS and SQS, we have couple of options:

Use Spring-Cloud-AWS

Use AWS-SDK-Java 2

I wanted to know if there is any advantage in using one or the other.

When I ask AWS guys, they tell me that AWS SDK gets updated regularly and integration with SNS and SQS is not difficult. Hence, there is no need to integrate with Spring-Cloud-AWS.

I tried searching on gitter channel for Spring-Cloud and could not find any relevant information. Documentation does state that I can update the AWS-SDK version. Documentation does not state any compelling reason for not using AWS-SDK directly.

If anyone has some insights, please share.

答:
From the AWS Spring Team:

"From now on, our efforts focus on 3.0 - based on AWS SDK 2.0."

So, if you need AWS SDK 2.0, you probably want to go directly with the SDK.

https://spring.io/blog/2021/03/17/spring-cloud-aws-2-3-is-now-available

For more on what's new on AWS Java SDK 2.0:
https://aws.amazon.com/blogs/developer/aws-sdk-for-java-2-0-developer-preview/

Title: Spring-Cloud-AWS vs AWS-SDK-Java 2


问:
Python, NLP - finding the top document containing given list of words
I am new to learning NLP. I am trying to do an exercise of finding the best matching resume.

For example, I have a list of skills that I am looking for like ['java', 'python', 'SQL', 'API', ...], and a set of documents. I want to create a model to find the document that is the best match with these skills. Similar to resume matching.

I started with this tutorial - Extracting words from pdf as a reference

I was able to extract the text from pdf, remove stop words, perform lemmatization, compute the number of times these keywords appear in each document and I am not sure how to go head from here.

Could anyone provide me with what the next steps should be? Any tutorials or references would be helpful as well.

答:
I think you can use the vector similarity approach.

The best matching resume is the similarity between the query (qualification keywords) and the texts. You can use doc2vec or sbert -which I prefer most- to collect the top n best results.

```<code>corpus_embeddings = model.encode(YOUR_CV_TEXT, convert_to_tensor=True)
query_1=['java python SQL']

for query in query_1:
    query_embedding = model.encode(query_1, convert_to_tensor=True)

    cos_scores = util.cos_sim(query_embedding, corpus_embeddings)[0]
    top_results = torch.topk(cos_scores, k=5)

    print("\n\n======================\n\n")
    print("Query:", query)
    print("\nTop 5 most similar sentences in corpus:")

    for score, idx in zip(top_results[0], top_results[1]):
        print(par_list[idx], "(Score: {:.4f})".format(score))
</code>```

For more you can deep dive into: Semantic Search

Body:
I think you can use the vector similarity approach.

The best matching resume is the similarity between the query (qualification keywords) and the texts. You can use doc2vec or sbert -which I prefer most- to collect the top n best results.

corpus_embeddings = model.encode(YOUR_CV_TEXT, convert_to_tensor=True)
query_1=['java python SQL']

for query in query_1:
    query_embedding = model.encode(query_1, convert_to_tensor=True)

    cos_scores = util.cos_sim(query_embedding, corpus_embeddings)[0]
    top_results = torch.topk(cos_scores, k=5)

    print("\n\n======================\n\n")
    print("Query:", query)
    print("\nTop 5 most similar sentences in corpus:")

    for score, idx in zip(top_results[0], top_results[1]):
        print(par_list[idx], "(Score: {:.4f})".format(score))

For more you can deep dive into: Semantic Search


问:
How can I get my python code to run again
I wrote a python script with for loops, which is meant to extract metadata from tweets, and it worked well initially. Now, I have replaced the for loops with list comprehension, and my code is throwing up an error, which I can't really decipher. Here is my code below:

```<code>def tweetFeatures(tweet):
        #Count the number of words in each tweet
        wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]

        #Count the number of characters in each tweet
        chars = [len(tweet.loc[k]) for k in range(len(tweet))]

        #Extract the mentions in each tweet
        mentions = [list(re.findall("@([a-zA-Z0-9_]{1,50})",tweet.loc[p])) for p in range(len(tweet))]

        #Counts the number of mentions in each tweet
        mention_count = [len(mentions[t]) for t in range(len(mentions))]

        #Extracts the hashtags in each tweet
        hashtags = [list(re.findall("#([a-zA-Z0-9_]{1,50})",tweet.loc[f])) for f in range(len(tweet))]

        #Counts the number of hashtags in each tweet
        hashtag_count = [len(hashtags[d]) for d in range(len(hashtags))]

        #Extracts the urls in each tweet
        url = [list(re.findall("(?P<url>https?://[^\s]+)",tweet.loc[l])) for l in range(len(tweet))]

        #Counts the number of urls in each tweet
        url_count = [len(url[c]) for c in range(len(url))]

        #Put everything into a dataframe
        feats = {"n_words":wordcount,"n_chars":chars,"n_mentions":mention_count,"n_hashtag":hashtag_count,"n_url":url_count}
        feats_df = pd.DataFrame(feats)

        return feats_df
</code>```

Here is the error I am now getting after running this line of code tweetFeatures(tweet = text_df)

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-22-a074a939c816> in <module>
----> 1 tweetFeatures(tweet = text_df)

<ipython-input-21-36def6dfde04> in tweetFeatures(tweet)
      1 def tweetFeatures(tweet):
      2         #Count the number of words in each tweet
----> 3         wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]
      4
      5         #Count the number of characters in each tweet

<ipython-input-21-36def6dfde04> in <listcomp>(.0)
      1 def tweetFeatures(tweet):
      2         #Count the number of words in each tweet
----> 3         wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]
      4
      5         #Count the number of characters in each tweet

~\anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5463             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5464                 return self[name]
-> 5465             return object.__getattribute__(self, name)
   5466
   5467     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'split'
</code>```

This is the test data I created:

```<code>text = ["@Harrison2Jennifer Tokyo 2020 is so much fun. Loving every bit of it just as @MeggyJane & @Tommy620 say #Tokyo2020 https://www.corp.com",
           "Gabrielle Thomas is my favourite sprinter @TooSports https://www.flick.org https://www.bugger.com",
           "@Sports_head I wish the #Tokyo2020 @Olympics will never end #Athletics #Sprints",
           "I hate the attitude of officials at this olympics @Kieran https://www.launch.com",
           "Why can't the #Athletics be more exciting? #Tokyo2020",
           "It is so much fun to see beautful colors at the #Olympics"]
</code>```

I convert it to a Pandas dataframe with text_df = pd.DataFrame(text), and then print that with print(text_df), with the below result:

```<code>0
0   @Harrison2Jennifer Tokyo 2020 is so much fun. ...
1   Gabrielle Thomas is my favourite sprinter @Too...
2   @Sports_head I wish the #Tokyo2020 @Olympics w...
3   I hate the attitude of officials at this olymp...
4   Why can't the #Athletics be more exciting? #To...
5   It is so much fun to see beautful colors at th...
</code>```

The code was written in Jupyter notebooks.
Please, I will appreciate your helpful suggestions as to what exactly has gone wrong, thank you.

答:
What you are doing is creating a pd.DataFrame, but you only have a single column. In your case this column is called 0.

So you can fix your code by either:

tweetFeatures(tweet = text_df[0])

Creating a Series instead of a DataFrame: text_df = pd.Series(text) and calling it like you are doing right now.

Additionally, you can speed up your function by using apply in most cases. Note that this is a bit slower for small input such as the sample you provided, but gives a significant speed up when using more tweets:

```<code>text = ["@Harrison2Jennifer Tokyo 2020 is so much fun. Loving every bit of it just as @MeggyJane & @Tommy620 say #Tokyo2020 https://www.corp.com",
       "Gabrielle Thomas is my favourite sprinter @TooSports https://www.flick.org https://www.bugger.com",
       "@Sports_head I wish the #Tokyo2020 @Olympics will never end #Athletics #Sprints",
       "I hate the attitude of officials at this olympics @Kieran https://www.launch.com",
       "Why can't the #Athletics be more exciting? #Tokyo2020",
       "It is so much fun to see beautful colors at the #Olympics"]*1000

from functools import partial
def tweetFeatures_speedup(tweet):
    #Count the number of words in each tweet
    wordcount = tweet.apply(lambda x: len(x.split()))

    #Count the number of characters in each tweet
    chars = tweet.apply(len)

    #Extract the mentions in each tweet
    mention_finder = partial(re.findall, "@([a-zA-Z0-9_]{1,50})")

    #Counts the number of mentions in each tweet
    mention_count = tweet.apply(lambda x: len(mention_finder(x)))

    #Extracts the hashtags in each tweet
    #Counts the number of hashtags in each tweet
    hashtag_finder = partial(re.findall, "#([a-zA-Z0-9_]{1,50})")
    hashtag_count = tweet.apply(lambda x: len(hashtag_finder(x)))

    #Extracts the urls in each tweet
    #Counts the number of urls in each tweet
    url_finder = partial(re.findall, "(?P<url>https?://[^\s]+)")
    url_count = tweet.apply(lambda x: len(url_finder(x)))

    #Put everything into a dataframe
    feats = {"n_words":wordcount,"n_chars":chars,"n_mentions":mention_count,"n_hashtag":hashtag_count,"n_url":url_count}
    feats_df = pd.DataFrame(feats)

    return feats_df
</code>```

This results in the %%timeit comparison:

Your version: 193 ms ± 1.95 ms per loop

My version: 21.3 ms ± 85.1 µs

Body:
I wrote a python script with for loops, which is meant to extract metadata from tweets, and it worked well initially. Now, I have replaced the for loops with list comprehension, and my code is throwing up an error, which I can't really decipher. Here is my code below:

def tweetFeatures(tweet):
        #Count the number of words in each tweet
        wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]

        #Count the number of characters in each tweet
        chars = [len(tweet.loc[k]) for k in range(len(tweet))]

        #Extract the mentions in each tweet
        mentions = [list(re.findall("@([a-zA-Z0-9_]{1,50})",tweet.loc[p])) for p in range(len(tweet))]

        #Counts the number of mentions in each tweet
        mention_count = [len(mentions[t]) for t in range(len(mentions))]

        #Extracts the hashtags in each tweet
        hashtags = [list(re.findall("#([a-zA-Z0-9_]{1,50})",tweet.loc[f])) for f in range(len(tweet))]

        #Counts the number of hashtags in each tweet
        hashtag_count = [len(hashtags[d]) for d in range(len(hashtags))]

        #Extracts the urls in each tweet
        url = [list(re.findall("(?P<url>https?://[^\s]+)",tweet.loc[l])) for l in range(len(tweet))]

        #Counts the number of urls in each tweet
        url_count = [len(url[c]) for c in range(len(url))]

        #Put everything into a dataframe
        feats = {"n_words":wordcount,"n_chars":chars,"n_mentions":mention_count,"n_hashtag":hashtag_count,"n_url":url_count}
        feats_df = pd.DataFrame(feats)

        return feats_df

Here is the error I am now getting after running this line of code tweetFeatures(tweet = text_df)

AttributeError                            Traceback (most recent call last)
<ipython-input-22-a074a939c816> in <module>
----> 1 tweetFeatures(tweet = text_df)

<ipython-input-21-36def6dfde04> in tweetFeatures(tweet)
      1 def tweetFeatures(tweet):
      2         #Count the number of words in each tweet
----> 3         wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]
      4
      5         #Count the number of characters in each tweet

<ipython-input-21-36def6dfde04> in <listcomp>(.0)
      1 def tweetFeatures(tweet):
      2         #Count the number of words in each tweet
----> 3         wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]
      4
      5         #Count the number of characters in each tweet

~\anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5463             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5464                 return self[name]
-> 5465             return object.__getattribute__(self, name)
   5466
   5467     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'split'

This is the test data I created:

text = ["@Harrison2Jennifer Tokyo 2020 is so much fun. Loving every bit of it just as @MeggyJane & @Tommy620 say #Tokyo2020 https://www.corp.com",
           "Gabrielle Thomas is my favourite sprinter @TooSports https://www.flick.org https://www.bugger.com",
           "@Sports_head I wish the #Tokyo2020 @Olympics will never end #Athletics #Sprints",
           "I hate the attitude of officials at this olympics @Kieran https://www.launch.com",
           "Why can't the #Athletics be more exciting? #Tokyo2020",
           "It is so much fun to see beautful colors at the #Olympics"]

I convert it to a Pandas dataframe with text_df = pd.DataFrame(text), and then print that with print(text_df), with the below result:

0
0   @Harrison2Jennifer Tokyo 2020 is so much fun. ...
1   Gabrielle Thomas is my favourite sprinter @Too...
2   @Sports_head I wish the #Tokyo2020 @Olympics w...
3   I hate the attitude of officials at this olymp...
4   Why can't the #Athletics be more exciting? #To...
5   It is so much fun to see beautful colors at th...

The code was written in Jupyter notebooks.
Please, I will appreciate your helpful suggestions as to what exactly has gone wrong, thank you.

Body:
What you are doing is creating a pd.DataFrame, but you only have a single column. In your case this column is called 0.

So you can fix your code by either:

tweetFeatures(tweet = text_df[0])

Creating a Series instead of a DataFrame: text_df = pd.Series(text) and calling it like you are doing right now.

Additionally, you can speed up your function by using apply in most cases. Note that this is a bit slower for small input such as the sample you provided, but gives a significant speed up when using more tweets:

text = ["@Harrison2Jennifer Tokyo 2020 is so much fun. Loving every bit of it just as @MeggyJane & @Tommy620 say #Tokyo2020 https://www.corp.com",
       "Gabrielle Thomas is my favourite sprinter @TooSports https://www.flick.org https://www.bugger.com",
       "@Sports_head I wish the #Tokyo2020 @Olympics will never end #Athletics #Sprints",
       "I hate the attitude of officials at this olympics @Kieran https://www.launch.com",
       "Why can't the #Athletics be more exciting? #Tokyo2020",
       "It is so much fun to see beautful colors at the #Olympics"]*1000

from functools import partial
def tweetFeatures_speedup(tweet):
    #Count the number of words in each tweet
    wordcount = tweet.apply(lambda x: len(x.split()))

    #Count the number of characters in each tweet
    chars = tweet.apply(len)

    #Extract the mentions in each tweet
    mention_finder = partial(re.findall, "@([a-zA-Z0-9_]{1,50})")

    #Counts the number of mentions in each tweet
    mention_count = tweet.apply(lambda x: len(mention_finder(x)))

    #Extracts the hashtags in each tweet
    #Counts the number of hashtags in each tweet
    hashtag_finder = partial(re.findall, "#([a-zA-Z0-9_]{1,50})")
    hashtag_count = tweet.apply(lambda x: len(hashtag_finder(x)))

    #Extracts the urls in each tweet
    #Counts the number of urls in each tweet
    url_finder = partial(re.findall, "(?P<url>https?://[^\s]+)")
    url_count = tweet.apply(lambda x: len(url_finder(x)))

    #Put everything into a dataframe
    feats = {"n_words":wordcount,"n_chars":chars,"n_mentions":mention_count,"n_hashtag":hashtag_count,"n_url":url_count}
    feats_df = pd.DataFrame(feats)

    return feats_df

This results in the %%timeit comparison:

Your version: 193 ms ± 1.95 ms per loop

My version: 21.3 ms ± 85.1 µs


问:
The type or namespace name 'Resource File' does not exist in the namespace 'Resources' after deploying the Asp.Net app in Docker Kubernetes
I have an ASP.NET Webforms application. It has been working without any issues for years. Now I am trying to deploy the app in Docker Kubernetes. It is deployed successfully without any compilation errors. But when I access one page it's throwing this exception:

System.Web.HttpCompileException (0x80004005):
c:\inetpub\wwwroot\Client\User\MyPage.aspx.cs(179): error
CS0234: The type or namespace name 'Messages' does not exist in the
namespace 'Resources' (are you missing an assembly reference?) at
System.Web.Compilation.AssemblyBuilder.Compile() at
System.Web.Compilation.BuildProvidersCompiler.PerformBuild() at
System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath
virtualPath) at
System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath
virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean
allowBuildInPrecompile, Boolean throwIfNotFoun d, Boolean
ensureIsUpToDate)

Resource file Messages.resx is added in the App_GlobalResources folder and it's being copied under the root folder of the app as guided in the official documentation.

I have tried to recreate the resource also, but it also didn't work.

Below is the Messages class

```<code>#region Assembly App_GlobalResources.tlvvgtfn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// C:\Users\Vivek.Nuna\AppData\Local\Temp\Temporary ASP.NET Files\root\dfad19b2\_shadow\477aa3de\26952\App_GlobalResources.tlvvgtfn.dll
#endregion

using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Runtime.CompilerServices;

namespace Resources
{
    [CompilerGenerated]
    [DebuggerNonUserCode]
    [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    public class Messages
    {
</code>```

答: I have solved the issues. It copied to resource files with all lower cases in the file name. So I have made the changes in my Dockerfile to copy the file with the same cases in file names and it worked like magic.</p>

Body:
I have an ASP.NET Webforms application. It has been working without any issues for years. Now I am trying to deploy the app in Docker Kubernetes. It is deployed successfully without any compilation errors. But when I access one page it's throwing this exception:

System.Web.HttpCompileException (0x80004005):
c:\inetpub\wwwroot\Client\User\MyPage.aspx.cs(179): error
CS0234: The type or namespace name 'Messages' does not exist in the
namespace 'Resources' (are you missing an assembly reference?) at
System.Web.Compilation.AssemblyBuilder.Compile() at
System.Web.Compilation.BuildProvidersCompiler.PerformBuild() at
System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath
virtualPath) at
System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath
virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean
allowBuildInPrecompile, Boolean throwIfNotFoun d, Boolean
ensureIsUpToDate)

Resource file Messages.resx is added in the App_GlobalResources folder and it's being copied under the root folder of the app as guided in the official documentation.

I have tried to recreate the resource also, but it also didn't work.

Below is the Messages class

#region Assembly App_GlobalResources.tlvvgtfn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// C:\Users\Vivek.Nuna\AppData\Local\Temp\Temporary ASP.NET Files\root\dfad19b2\_shadow\477aa3de\26952\App_GlobalResources.tlvvgtfn.dll
#endregion

using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Runtime.CompilerServices;

namespace Resources
{
    [CompilerGenerated]
    [DebuggerNonUserCode]
    [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    public class Messages
    {


问:
Is it possible to give away a apple content subscription code?
I know that as a developer you can give away codes so that users can download your app for free. Is it possible to do the same for a subscription to content within an app?</p>

答: No, it's not possible with in-app purchases, you have codes only for download apps.</p>


问:
awk remove before match but after empty line
I didn't find the exact similar question, so i need to ask:

I have a file gist :

```<code>...
must_be_intact

bad_line
bad_line
bad_line
match_line
...
</code>```

I use awk to remove everything before the match but after a space:

'NR==FNR{if (/match_line/) {
    i=0;
    while(1) {
        if (NR-i==/^\s*$/) break;
        del[NR-i];
        i=i-1;
        next
        }
    }
} !(FNR in del)'
```

But this does not work correctly. Help improve this code, or you can advise another way.

答:
With your shown samples only, please try following awk code, written and tested in GNU awk. Simple explanation would be, setting RS(record separator) as 1 or more occurrences of new lines till match_line and in main program; substituting first new line with NULL and then printing the lines as per RS.

```<code>awk -v RS='\n+.*match_line' '{sub(/\n/,"")}1' Input_file
</code>```

Body:
I didn't find the exact similar question, so i need to ask:

I have a file gist :

...
must_be_intact

bad_line
bad_line
bad_line
match_line
...

I use awk to remove everything before the match but after a space:

'NR==FNR{if (/match_line/) {
    i=0;
    while(1) {
        if (NR-i==/^\s*$/) break;
        del[NR-i];
        i=i-1;
        next
        }
    }
} !(FNR in del)'

But this does not work correctly. Help improve this code, or you can advise another way.

Body:
With your shown samples only, please try following awk code, written and tested in GNU awk. Simple explanation would be, setting RS(record separator) as 1 or more occurrences of new lines till match_line and in main program; substituting first new line with NULL and then printing the lines as per RS.

awk -v RS='\n+.*match_line' '{sub(/\n/,"")}1' Input_file


答:
According to your error message AttributeError: 'Series' object has no attribute 'split' you're trying to call the String method split() on a pandas Series object.

wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]
```
<p>By looking at the test data you provided, you could do something like this in order to fix the error:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd

text_df = pd.DataFrame(text,columns=["tweet"])

text_df.tweet.loc[0].split()
</code>```

Will return:

```<code>['@Harrison2Jennifer',
 'Tokyo',
 '2020',
 'is',
 'so',
 'much',
 'fun.',
 'Loving',
 'every',
 'bit',
 'of',
 'it',
 'just',
 'as',
 '@MeggyJane',
 '&',
 '@Tommy620',
 'say',
 '#Tokyo2020',
 'https://www.corp.com']
</code>```

Alternatively there is a solution without pandas by passing the "raw" list of tweets and changing the list comprehension to

```<code>wordcount = [len(t.split()) for t in tweet]
</code>```

Title: How can I get my python code to run again

Body:
According to your error message AttributeError: 'Series' object has no attribute 'split' you're trying to call the String method split() on a pandas Series object.

wordcount = [len(tweet.loc[j].split()) for j in range(len(tweet))]

By looking at the test data you provided, you could do something like this in order to fix the error:

import pandas as pd

text_df = pd.DataFrame(text,columns=["tweet"])

text_df.tweet.loc[0].split()

Will return:

['@Harrison2Jennifer',
 'Tokyo',
 '2020',
 'is',
 'so',
 'much',
 'fun.',
 'Loving',
 'every',
 'bit',
 'of',
 'it',
 'just',
 'as',
 '@MeggyJane',
 '&',
 '@Tommy620',
 'say',
 '#Tokyo2020',
 'https://www.corp.com']

Alternatively there is a solution without pandas by passing the "raw" list of tweets and changing the list comprehension to

wordcount = [len(t.split()) for t in tweet]


问:
Difference between namespace install vs managed namespace install in Argo Workflows?
I am trying to install argo workflows and looking at the documentation I can see 3 different types of installation https://argoproj.github.io/argo-workflows/installation/.

Can anybody give some clarity on the namespace install vs managed namespace install? If its a managed namespace, how can I tell the managed namespace? Should I edit the k8's manifest for deployment? What benefit it can provide compared to simple namespace install
?

答:
A namespace install allows Workflows to run only in the namespace where Argo Workflows is installed.

A managed namespace install allows Workflows to run only in one namespace besides the one where Argo Workflows is installed.

Using a managed namespace install might make sense if you want some users/processes to be able to run Workflows without granting them any privileges in the namespace where Argo Workflows is installed.

For example, if I only run CI/CD-related Workflows that are maintained by the same team that manages the Argo Workflows installation, it's probably reasonable to use a namespace install. But if all the Workflows are run by a separate data science team, it probably makes sense to give them a data-science-workflows namespace and run a "managed namespace install" of Argo Workflows from another namespace.

To configure a managed namespace install, edit the workflow-controller and argo-server Deployments to pass the --managed-namespace argument.

You can currently only configure one managed namespace, but in the future it may be possible to manage more than one.


问:
Pandas drop duplicates across columns
Good day,

I need a way to check each row of a dataframe and drop the row if all the values in that row (across the score columns) are the same. The person_id may differ.

Here is a part of the dataset:

In:

```<code>data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df
</code>```

Out:

```<code>    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7
</code>```

The desired output would be:

```<code>    person_id   score_1 score_2 score_3 score_4
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7
</code>```

Since row 0 (person_id 7) and row 1 (person_id 17) have the same scores.
The number of columns will also change, adding more score columns - thus, I cannot use

```<code>df_no_duplicates = df.loc[(df.score_1 != df.score_2) | (df.score_2 != df.score_3)| (df.score_3 != df.score_4)]
</code>```

答:
A cheeky way to omit the person_id column from the process is to set it as the index temporarily.

```<code>result = df.set_index('person_id').drop_duplicates(keep=False).reset_index()
</code>```

You could also use the subset argument of drop_duplicates:

```<code>result = df.drop_duplicates(subset=df.columns.difference(['person_id']), keep=False)
</code>```

Title: Pandas drop duplicates across columns

Body:
Good day,

I need a way to check each row of a dataframe and drop the row if all the values in that row (across the score columns) are the same. The person_id may differ.

Here is a part of the dataset:

In:

data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df

Out:

    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7

The desired output would be:

    person_id   score_1 score_2 score_3 score_4
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7

Since row 0 (person_id 7) and row 1 (person_id 17) have the same scores.
The number of columns will also change, adding more score columns - thus, I cannot use

df_no_duplicates = df.loc[(df.score_1 != df.score_2) | (df.score_2 != df.score_3)| (df.score_3 != df.score_4)]

Body:
A cheeky way to omit the person_id column from the process is to set it as the index temporarily.

result = df.set_index('person_id').drop_duplicates(keep=False).reset_index()

You could also use the subset argument of drop_duplicates:

result = df.drop_duplicates(subset=df.columns.difference(['person_id']), keep=False)


问:
Begginer in Flutter trying to use FireBase auth
So im really just experimenting to get used to flutter with firebase, so first thing im trying to do in my app its an anonymous authenticantion. With the following code im getting the error "[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()"

Here is my main

```<code>void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Wrapper(),
    );
  }
}
</code>```

Here is The Sign In screen, where i first tried to use firebase.

```<code>class SignIn extends StatefulWidget {
  const SignIn({Key? key}) : super(key: key);

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

class _SignInState extends State<SignIn> {

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green[100],
      appBar: AppBar(
        title: Text('Sign In'),
        backgroundColor: Colors.green[500],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(vertical:20.0 , horizontal:50.0,),
        child: ElevatedButton(
          child: Text('Sign In'),
          onPressed: () async{
            dynamic result = await _auth.signInAnon();
            if(result == null) {
              print ('failed');}
              else{
                print('Success');
                print(result);
            }
          },
        ),
      ),
    );
  }
}
</code>```

And the auth class where i use signInAnon().

```<code>class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  //login anon
  Future signInAnon() async{
    try{
     UserCredential result =  _auth.signInAnonymously() as UserCredential;
     User user = result.user as User;
     return user;
    } catch(e){
        print(e.toString());
        return null;
    }
  }
}
</code>```

I am following an youtube course form about 2 years ago, so i know firebase changed, but a few recent questions here with the same error have been solved changing the code in main like this:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
   runApp(const MyApp());
}
</code>```

After this change the app is showing a white screen and console says it has an error:

Syncing files to device Android SDK built for x86...

E/flutter (15860): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.

E/flutter (15860):

E/flutter (15860): Usually this means you've attempted to use a Firebase service before calling Firebase.initializeApp.

E/flutter (15860):

E/flutter (15860): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization

E/flutter (15860):

E/flutter (15860): #0      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)

E/flutter (15860):

E/flutter (15860): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)

E/flutter (15860):

E/flutter (15860): #2      main (package:order_beer/main.dart:10:3)

E/flutter (15860):

E/flutter (15860):

If anybody could help me!

答:
I'm not sure if this is the case but for your main function try writing it as</p>
```<code>Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}
</code>```

Body:
So im really just experimenting to get used to flutter with firebase, so first thing im trying to do in my app its an anonymous authenticantion. With the following code im getting the error "[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()"

Here is my main

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Wrapper(),
    );
  }
}

Here is The Sign In screen, where i first tried to use firebase.

class SignIn extends StatefulWidget {
  const SignIn({Key? key}) : super(key: key);

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

class _SignInState extends State<SignIn> {

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green[100],
      appBar: AppBar(
        title: Text('Sign In'),
        backgroundColor: Colors.green[500],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(vertical:20.0 , horizontal:50.0,),
        child: ElevatedButton(
          child: Text('Sign In'),
          onPressed: () async{
            dynamic result = await _auth.signInAnon();
            if(result == null) {
              print ('failed');}
              else{
                print('Success');
                print(result);
            }
          },
        ),
      ),
    );
  }
}

And the auth class where i use signInAnon().

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  //login anon
  Future signInAnon() async{
    try{
     UserCredential result =  _auth.signInAnonymously() as UserCredential;
     User user = result.user as User;
     return user;
    } catch(e){
        print(e.toString());
        return null;
    }
  }
}

I am following an youtube course form about 2 years ago, so i know firebase changed, but a few recent questions here with the same error have been solved changing the code in main like this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
   runApp(const MyApp());
}

After this change the app is showing a white screen and console says it has an error:

Syncing files to device Android SDK built for x86...

E/flutter (15860): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.

E/flutter (15860):

E/flutter (15860): Usually this means you've attempted to use a Firebase service before calling Firebase.initializeApp.

E/flutter (15860):

E/flutter (15860): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization

E/flutter (15860):

E/flutter (15860): #0      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)

E/flutter (15860):

E/flutter (15860): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)

E/flutter (15860):

E/flutter (15860): #2      main (package:order_beer/main.dart:10:3)

E/flutter (15860):

E/flutter (15860):

If anybody could help me!

Body:
I'm not sure if this is the case but for your main function try writing it as

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}


问:
How to have a factor outside the axis for an arrow in ggplot
I want to make an annotation with an arrow that goes outside a plot in ggplot. Using geom_curve changes the order of the factor, and I do not understand why.

Here is the example: let's consider the following plot:

```<code>df <- data.frame(ID = factor(c("A","B","C"),level = c("AA","B","C","A")),
           y = 1:3)

ggplot(df,aes(ID,y,color = ID))+
  geom_point()+
  coord_flip(clip = "off")+
  scale_x_discrete(breaks = c("B","C","A"))
</code>```

I want to keep the order of the vertical axis (B,C,A), and have an arrow pointing at the first point but from above the plot. I thus want to ass a factor before A that goes outside the plot:

```<code>ggplot(df,aes(ID,y,color = ID))+
  geom_point()+
  geom_curve(data = data.frame(ID = factor("AA",level = c("AA","B","C","A")),
                               ID_end = "A",
                               y = 2,y_end = 1),
             aes(x = ID,xend = ID_end,
                 y = y ,yend = y_end),
             curvature = -.1,
             arrow =arrow(length = unit(2, "mm"),type = "closed"),
             color = "grey20" ,size = .2)+
  coord_flip(clip = "off")+
  scale_x_discrete(breaks = c("B","C","A"))
</code>```

Here the vertical axis has the factors reordered, although I specified the same order in geom_curve. My arrow lies in the middle instead of being on the top/outside the plot.

How can I solve this problem?

答:
If you want to manually add a few things to a graph, use annotate(geom = "XXX") rather than geom_XXX with a custom data =.

Also, factor levels get converted to integers.  It is easier to specify the integer value, rather than forcing the factor levels.

```<code>ggplot(df,aes(ID,y,color = ID))+
    geom_point()+
    annotate(geom = "curve", x = -1L, xend = 1, y = 2, yend = 1,
             curvature = -.1,
             arrow =arrow(length = unit(2, "mm"),type = "closed"),
             color = "grey20" ,size = .2) +
    coord_flip(clip = "off")+
    scale_x_discrete(breaks = c("B","C","A"))
</code>```

Body:
I want to make an annotation with an arrow that goes outside a plot in ggplot. Using geom_curve changes the order of the factor, and I do not understand why.

Here is the example: let's consider the following plot:

df <- data.frame(ID = factor(c("A","B","C"),level = c("AA","B","C","A")),
           y = 1:3)

ggplot(df,aes(ID,y,color = ID))+
  geom_point()+
  coord_flip(clip = "off")+
  scale_x_discrete(breaks = c("B","C","A"))

I want to keep the order of the vertical axis (B,C,A), and have an arrow pointing at the first point but from above the plot. I thus want to ass a factor before A that goes outside the plot:

ggplot(df,aes(ID,y,color = ID))+
  geom_point()+
  geom_curve(data = data.frame(ID = factor("AA",level = c("AA","B","C","A")),
                               ID_end = "A",
                               y = 2,y_end = 1),
             aes(x = ID,xend = ID_end,
                 y = y ,yend = y_end),
             curvature = -.1,
             arrow =arrow(length = unit(2, "mm"),type = "closed"),
             color = "grey20" ,size = .2)+
  coord_flip(clip = "off")+
  scale_x_discrete(breaks = c("B","C","A"))

Here the vertical axis has the factors reordered, although I specified the same order in geom_curve. My arrow lies in the middle instead of being on the top/outside the plot.

How can I solve this problem?

Body:
If you want to manually add a few things to a graph, use annotate(geom = "XXX") rather than geom_XXX with a custom data =.

Also, factor levels get converted to integers.  It is easier to specify the integer value, rather than forcing the factor levels.

ggplot(df,aes(ID,y,color = ID))+
    geom_point()+
    annotate(geom = "curve", x = -1L, xend = 1, y = 2, yend = 1,
             curvature = -.1,
             arrow =arrow(length = unit(2, "mm"),type = "closed"),
             color = "grey20" ,size = .2) +
    coord_flip(clip = "off")+
    scale_x_discrete(breaks = c("B","C","A"))


问:
Does move constructor only affect the memory space pointed to by the pointer member of the class？
For example, this Code:

```<code>struct President
{
    std::string name;
    std::string country;
    int year;

    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        std::cout << "--constructed\n";
    }
    /*
    President(const President& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    */
    President(const President& other)
        : name(other.name), country(other.country), year(other.year)
    {
        std::cout << "--copy constructed\n";
    }
    President(President&& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "--moved\n";
    }
    ~President()
    {
        cout << "\n"<< &name << " " << country << endl;
        std::cout << "--destruct\n";
    }
    President& operator=(const President& other);
};
</code>```

Whether it is a move constructor or a copy constructor, they will cause the values of the three data members to be stored in the new memory, and the old memory will be released.

And my meaning is right?

答:
And my meaning is right?

Sorry, no.  Your move constructor will work as you describe, in that it will 'steal' the contents of the name and country member variables from other, but the copy constructor will not.  std::move does nothing with a const object and you should remove it from your copy constructor.  After all, the operative word is copy, right?

It's worth noting that you don't need to write your own copy or move constructors at all here ('rule of zero').  The default constructors synthesized by the compiler will work just fine.  Oh, and std::move on a primitive type such as an int also does nothing - the variable will just be copied whether you include it or not.

Body:
For example, this Code:

struct President
{
    std::string name;
    std::string country;
    int year;

    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        std::cout << "--constructed\n";
    }
    /*
    President(const President& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    */
    President(const President& other)
        : name(other.name), country(other.country), year(other.year)
    {
        std::cout << "--copy constructed\n";
    }
    President(President&& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "--moved\n";
    }
    ~President()
    {
        cout << "\n"<< &name << " " << country << endl;
        std::cout << "--destruct\n";
    }
    President& operator=(const President& other);
};

Whether it is a move constructor or a copy constructor, they will cause the values of the three data members to be stored in the new memory, and the old memory will be released.

And my meaning is right?


问:
Is there a way to bypass the impossiblity of jQuery val() to read input type="number" when the first char is not a number IN SOME BROWSERS?
So I came upon the problem, that to for validating a form, I couldn't access an input's val through val() when:

1)the input was of type "number"

2)the input's value was not beginning with a number

simplified html:

```<code><form id="input" class="pro" autocomplete="on">
    <table>
        <tbody>
            <tr>
                <td><input type="number"></td>
            </tr>
        </tbody>
    </table>
</form>
</code>```

js:

```<code>$('input[type="number"]').each(function() {
   $(this).keyup(function() {
      alert($(this).val());
   });
});
</code>```

and

```<code>.attr("value")
</code>```

has the same behaviour

I have checked that the script is working by changing the type to text, and it worked... but my input needs to be a number and following HTML5 semantic rules this wouldn't be correct.

So, is there a way doing it or am I just missing something?

答:
After @Joseph gave me an idea through his fiddle and @Varun Vohra an idea of escaping the input this is a way of doing it:

```<code>$('#input input[type="number"]').each(function() {
    $(this).keyup(function(event) {
        if (!this.value) {
            this.value = '';
            // alert
        }
        else if (isNaN(this.value)) {
            this.value = '';
            //alert
        }
        else {
            // go on
        }
    });
});
</code>```

The first if is used when the browser understands type="number" and if it's a wrong value, deletes it. The second if the browser doesn't understand it so it checks whether is is a number or not. And the last (else) happens if the value is a number (optional though).

Body:
So I came upon the problem, that to for validating a form, I couldn't access an input's val through val() when:

1)the input was of type "number"

2)the input's value was not beginning with a number

simplified html:

<form id="input" class="pro" autocomplete="on">

                <input type="number">

</form>

js:

$('input[type="number"]').each(function() {
   $(this).keyup(function() {
      alert($(this).val());
   });
});

and

.attr("value")

has the same behaviour

I have checked that the script is working by changing the type to text, and it worked... but my input needs to be a number and following HTML5 semantic rules this wouldn't be correct.

So, is there a way doing it or am I just missing something?

Body:
After @Joseph gave me an idea through his fiddle and @Varun Vohra an idea of escaping the input this is a way of doing it:

$('#input input[type="number"]').each(function() {
    $(this).keyup(function(event) {
        if (!this.value) {
            this.value = '';
            // alert
        }
        else if (isNaN(this.value)) {
            this.value = '';
            //alert
        }
        else {
            // go on
        }
    });
});

The first if is used when the browser understands type="number" and if it's a wrong value, deletes it. The second if the browser doesn't understand it so it checks whether is is a number or not. And the last (else) happens if the value is a number (optional though).


问:
How to access array of files in request with Django Rest Framework
I'm sending a request from a React frontend to Python backend, in this request i'm sending a FormData() with an array of images, like this:

```<code>const data = new FormData()
images.forEach(image => {
    data.append('images', image.arquivo)
})
data.append('product', JSON.stringify(product))
return recuperarInstanciaAxios(true).post(`${recuperarUrlBackend()}/products/`, data)
</code>```

But I'm not being able to access this array of pictures in Python.
Through PyCharm evaluate, request.FILES shows me a dict with an array 'images' within.
But when I do request.FILES['images'] it returns me a single file.
This is the python code:

```<code>def create(self, request):
    try:
        productData = json.loads(request.data['product'])
        serializer = ProductSerializer(data=productData )
        if serializer.is_valid():
            product = serializer.save()
            files = request.FILES['images']
            for image in files:
                product_image= {'image': image, 'product': product.id}
                image_serializer = ProductImage(data=product_image)
                if image_serializer .is_valid():
                    image_serializer .save()
                else:
                    raise IntegrityError('Error :' +
                                         serializer.errors.__str__())
            return Response(serializer.data,
                            status=status.HTTP_201_CREATED)
        else:
            raise IntegrityError('Error:' +
                                 serializer.errors.__str__())

    except IntegrityError as exc:
        print(exc)
        return Response(exc.__str__(),
                        status.HTTP_412_PRECONDITION_FAILED)
</code>```

It gives me an error because files is not iterable.
Am I accessing the array in a wrong way?

答:
I think the problem is in how you form the variable "files" should be something like this:

```<code>files = request.FILES.getlist('file_field')
</code>```

file_field is the name of your html file

Body:
I'm sending a request from a React frontend to Python backend, in this request i'm sending a FormData() with an array of images, like this:

const data = new FormData()
images.forEach(image => {
    data.append('images', image.arquivo)
})
data.append('product', JSON.stringify(product))
return recuperarInstanciaAxios(true).post(`${recuperarUrlBackend()}/products/`, data)

But I'm not being able to access this array of pictures in Python.
Through PyCharm evaluate, request.FILES shows me a dict with an array 'images' within.
But when I do request.FILES['images'] it returns me a single file.
This is the python code:

def create(self, request):
    try:
        productData = json.loads(request.data['product'])
        serializer = ProductSerializer(data=productData )
        if serializer.is_valid():
            product = serializer.save()
            files = request.FILES['images']
            for image in files:
                product_image= {'image': image, 'product': product.id}
                image_serializer = ProductImage(data=product_image)
                if image_serializer .is_valid():
                    image_serializer .save()
                else:
                    raise IntegrityError('Error :' +
                                         serializer.errors.__str__())
            return Response(serializer.data,
                            status=status.HTTP_201_CREATED)
        else:
            raise IntegrityError('Error:' +
                                 serializer.errors.__str__())

    except IntegrityError as exc:
        print(exc)
        return Response(exc.__str__(),
                        status.HTTP_412_PRECONDITION_FAILED)

It gives me an error because files is not iterable.
Am I accessing the array in a wrong way?

Body:
I think the problem is in how you form the variable "files" should be something like this:

files = request.FILES.getlist('file_field')

file_field is the name of your html file


问:
Vue.js best practices in data settings, using data method to set data dynamically
I have created an app, which works pretty good but I am (I think) doing stuff on places where it's not the best practice to do. I have a component and I use this piece of code for my data method:

    data() {

        var versionThing = "v1";
        if(this.$store.getters.version !=''){
            versionThing = this.$store.getters.version;
        }

        var settings = this.$store.getters.settings;

        var checkboxesThing = [
                    { val: "val1", text:"Text 1", isChecked: false },
                    { val: "val2", text:"Text 2", isChecked: false },
                    { val: "val3", text:"Text 3", isChecked: false },
                ];
        if(settings.checkboxes != ''){
            checkboxesThing = settings.checkboxes;
        }
        return {

            settings: {
                key: settings.key,
                version: versionThing,
                checkboxes: checkboxesThing,
            }

        };
    },
```
<p>This way I check whether or not there is a input in my VueX store. But i have a feeling this is probably not the way to do it properly...</p>
<p>This is my VueX code index.js file:</p>
<pre class="lang-js prettyprint-override"><code>    import { createStore } from 'vuex';
    import { Storage } from '@ionic/storage';

    const ionicStorage = new Storage();
    ionicStorage.create();

    const store = createStore({

        state() {
            return {
                settings:{
                    key:"",
                    version:'',
                    checkboxes:"",

                },
            }

        },
        getters: {
            key(state){
                return state.settings.key;
            },

            version(state){
                return state.settings.version;
            },

            settings(state){
                return state.settings;
            },

            // Ionic/Storage getters
            async getStorageAandoening(state){
                const myAwesomeValue = await ionicStorage.get('key')
                if(myAwesomeValue != ''){
                    state.settings.key = myAwesomeValue;
                }
                return state.settings.key;
            },

            async getStorageSettings(state){
                const myAwesomeValue = await ionicStorage.get('settings');
                var objectMyAwesomeValue = JSON.parse(myAwesomeValue);
                if(objectMyAwesomeValue.key != ''){
                    state.settings = objectMyAwesomeValue;
                }
                return state.settings;
            }
        },
        mutations: {
            changeKey (state, payload) {
                ionicStorage.set('key', payload)
                state.settings.key = payload
            },
            changeVersion(state, payload){
                ionicStorage.set('version', payload)
                state.settings.version = payload
            },
            changeSettings(state,payload){
                ionicStorage.set('settings', JSON.stringify(payload));
                state.settings = payload;
            }
        },
        actions: {}
    }
    );

    export default store;
</code>```

答:
First thing, the vuex modules state is usually filled with the default state you expect.

state() {
  return {
    settings:{
      key: "",
      version: "v1",
      checkboxes: [
        { val: "val1", text:"Text 1", isChecked: false },
        { val: "val2", text:"Text 2", isChecked: false },
        { val: "val3", text:"Text 3", isChecked: false },
      ],
    },
  }
},
```
<p><em>But that's up to you, you can leave it empty if you need.</em></p>
<hr />
<p>Then, <strong>most of your getters are not useful</strong>. Getters should be used just like "computed" in vue component: it's a derived value from your state, not shortcuts. I mean, it can be done but it's a bad practise in my opinion.</p>
<p>If you need to access your vuex state, just do <code>this.$store.state.settings</code>.</p>
<hr />
<p>Finally, from your component point of vue, you may skip the step where you copy your vuex store into component data. <strong>Vuex should be the source of truth for your data</strong>, so copying them just make it useless since you could update that data in the component without notifying the vuex store (it can be useful sometimes, but I feel that it's not your case here)</p>
<pre class="lang-html prettyprint-override"><code><template>
  <div>{{ $store.state.settings.version }}</div>
</template>

<script>
export default {
  computeds: {
    isLastVersion() {
        return this.$store.state.settings.version === 'v2'
    },
  }
}
</script>
</code>```

That's how I'd do it for your case, even though I don't have the global picture.

If really you need your vuex store to be empty, and your component only needs to set default values to this state, you can do it like so:

export default {
  computeds: {
    settings() {
        const storeSettings = this.$store.state.settings
        const defaultSettings = { version: 'v1', checkboxes: [...] }

        return {
          version: storeSettings.version || defaultSettings.version,
          checkboxes: storeSettings.checkboxes || defaultSettings.checkboxes,
        }
    },
  }
}
```

Declare a computed that reacts on your state changes. If the state is empty, you return default values. If the state is updated, then the computed updates too and return the store values.

Body:
I have created an app, which works pretty good but I am (I think) doing stuff on places where it's not the best practice to do. I have a component and I use this piece of code for my data method:

    data() {

        var versionThing = "v1";
        if(this.$store.getters.version !=''){
            versionThing = this.$store.getters.version;
        }

        var settings = this.$store.getters.settings;

        var checkboxesThing = [
                    { val: "val1", text:"Text 1", isChecked: false },
                    { val: "val2", text:"Text 2", isChecked: false },
                    { val: "val3", text:"Text 3", isChecked: false },
                ];
        if(settings.checkboxes != ''){
            checkboxesThing = settings.checkboxes;
        }
        return {

            settings: {
                key: settings.key,
                version: versionThing,
                checkboxes: checkboxesThing,
            }

        };
    },

This way I check whether or not there is a input in my VueX store. But i have a feeling this is probably not the way to do it properly...

This is my VueX code index.js file:

    import { createStore } from 'vuex';
    import { Storage } from '@ionic/storage';

    const ionicStorage = new Storage();
    ionicStorage.create();

    const store = createStore({

        state() {
            return {
                settings:{
                    key:"",
                    version:'',
                    checkboxes:"",

                },
            }

        },
        getters: {
            key(state){
                return state.settings.key;
            },

            version(state){
                return state.settings.version;
            },

            settings(state){
                return state.settings;
            },

            // Ionic/Storage getters
            async getStorageAandoening(state){
                const myAwesomeValue = await ionicStorage.get('key')
                if(myAwesomeValue != ''){
                    state.settings.key = myAwesomeValue;
                }
                return state.settings.key;
            },

            async getStorageSettings(state){
                const myAwesomeValue = await ionicStorage.get('settings');
                var objectMyAwesomeValue = JSON.parse(myAwesomeValue);
                if(objectMyAwesomeValue.key != ''){
                    state.settings = objectMyAwesomeValue;
                }
                return state.settings;
            }
        },
        mutations: {
            changeKey (state, payload) {
                ionicStorage.set('key', payload)
                state.settings.key = payload
            },
            changeVersion(state, payload){
                ionicStorage.set('version', payload)
                state.settings.version = payload
            },
            changeSettings(state,payload){
                ionicStorage.set('settings', JSON.stringify(payload));
                state.settings = payload;
            }
        },
        actions: {}
    }
    );

    export default store;

Body:
First thing, the vuex modules state is usually filled with the default state you expect.

state() {
  return {
    settings:{
      key: "",
      version: "v1",
      checkboxes: [
        { val: "val1", text:"Text 1", isChecked: false },
        { val: "val2", text:"Text 2", isChecked: false },
        { val: "val3", text:"Text 3", isChecked: false },
      ],
    },
  }
},

But that's up to you, you can leave it empty if you need.

Then, most of your getters are not useful. Getters should be used just like "computed" in vue component: it's a derived value from your state, not shortcuts. I mean, it can be done but it's a bad practise in my opinion.

If you need to access your vuex state, just do this.$store.state.settings.

Finally, from your component point of vue, you may skip the step where you copy your vuex store into component data. Vuex should be the source of truth for your data, so copying them just make it useless since you could update that data in the component without notifying the vuex store (it can be useful sometimes, but I feel that it's not your case here)

<template>
  <div>{{ $store.state.settings.version }}</div>
</template>

<script>
export default {
  computeds: {
    isLastVersion() {
        return this.$store.state.settings.version === 'v2'
    },
  }
}
</script>

That's how I'd do it for your case, even though I don't have the global picture.

If really you need your vuex store to be empty, and your component only needs to set default values to this state, you can do it like so:

export default {
  computeds: {
    settings() {
        const storeSettings = this.$store.state.settings
        const defaultSettings = { version: 'v1', checkboxes: [...] }

        return {
          version: storeSettings.version || defaultSettings.version,
          checkboxes: storeSettings.checkboxes || defaultSettings.checkboxes,
        }
    },
  }
}

Declare a computed that reacts on your state changes. If the state is empty, you return default values. If the state is updated, then the computed updates too and return the store values.