问:
Android data binding - cannot find getter for <> that accepts parameter type 'long'
I have been using data binding for the past few weeks and now am trying to use a two way data binding for a custom view with a 'value' attribute.

My problem is that I get the following error when building.

Cannot find a getter for <com.twisthenry8gmail.dragline.DraglineView
app:value> that accepts parameter type 'long'

Now it was my understanding that the binding library will automatically use my public setters and getters however the most confusing part is adding a redundant inverse binding adapter seems to solve the problem? So I get the impression that it is using my setter without needing an adapter but this is not the case for the getter?

My custom view

```<code>class DraglineView(context: Context, attrs: AttributeSet) : View(context, attrs) {
    ...

    var value = 0L
        set(value) {

            draggedValue = value
            field = value
            invalidate()
        }

    ...
}
</code>```

My view in the layout file

```<code><com.twisthenry8gmail.dragline.DraglineView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:increment="@{viewmodel.type.minIncrement}"
    app:minValue="@{viewmodel.type.minIncrement}"
    app:value="@={viewmodel.target}" />
</code>```

My seemingly redundant adapter

```<code>@InverseBindingAdapter(attribute = "value")
@JvmStatic
fun getValueTest(draglineView: DraglineView): Long {

    return draglineView.value
}
</code>```

My attribute changed adapter

```<code>@BindingAdapter("valueAttrChanged")
@JvmStatic
fun setDraglineListener(draglineView: DraglineView, listener: InverseBindingListener) {

    draglineView.valueChangedListener = {

        listener.onChange()
    }
}
</code>```

答:
The problem is that databinding system doesn't know when the view changes the value.

InverseBindingAdapter not only describes how to retrieve the value from the view, but it also defines an optional event property which will receive an InverseBindingListener instance. The default event name is the attribute name suffixed with "AttrChanged".

Now let's look at your setDraglineListener() adapter. It processes valueAttrChanged attribute added by InverseBindingAdapter and receives InverseBindingListener. The only thing is left is to notify the listener when the value is changed by calling listener.onChange();

Body:
I have been using data binding for the past few weeks and now am trying to use a two way data binding for a custom view with a 'value' attribute.

My problem is that I get the following error when building.

Cannot find a getter for <com.twisthenry8gmail.dragline.DraglineView
app:value> that accepts parameter type 'long'

Now it was my understanding that the binding library will automatically use my public setters and getters however the most confusing part is adding a redundant inverse binding adapter seems to solve the problem? So I get the impression that it is using my setter without needing an adapter but this is not the case for the getter?

My custom view

class DraglineView(context: Context, attrs: AttributeSet) : View(context, attrs) {
    ...

    var value = 0L
        set(value) {

            draggedValue = value
            field = value
            invalidate()
        }

    ...
}

My view in the layout file

<com.twisthenry8gmail.dragline.DraglineView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:increment="@{viewmodel.type.minIncrement}"
    app:minValue="@{viewmodel.type.minIncrement}"
    app:value="@={viewmodel.target}" />

My seemingly redundant adapter

@InverseBindingAdapter(attribute = "value")
@JvmStatic
fun getValueTest(draglineView: DraglineView): Long {

    return draglineView.value
}

My attribute changed adapter

@BindingAdapter("valueAttrChanged")
@JvmStatic
fun setDraglineListener(draglineView: DraglineView, listener: InverseBindingListener) {

    draglineView.valueChangedListener = {

        listener.onChange()
    }
}


来源: stackexchange

问:
Openpyxl 3 counts the empty row after saving custom cell format in MsExcel
Openpyxl 3.0.3,

Python 3.8.3,

MSExcel 16.27 (2019)

Reproduction:
In MSExcel, create workbook. Fill and save it similar to this,

Run the following code,

```<code>filepath = '..../yoursfilepath/Test.xlsx'
wb = openpyxl.load_workbook (filepath)
ws = wb.active
print (ws.max_row)
</code>```

Note down the max_row count.

Now open the workbook in MSExcel and clear all the content in last row (here, 12-May-20) which have cell format as 'Custom' (any other than 'General')

Save it and run the above code again. It counts last row.
Even if you convert the Custom format to General, it counts that row with empty cells.

If you check cell values with ws.iter_rows () they are 'None' for that row.

However, if you delete that particular row using MSExcel and save it, we get correct max row count. But this cannot be the solution all the time.

答:
The documentation states not to create the Worksheet yourself, I presume that this is a known bug when manually creating worksheets.

Do not create worksheets yourself, use openpyxl.workbook.Workbook.create_sheet() instead

However, if you must manually create them, this may solve your issue (modified from this answer)

```<code>def getMaxRows(ws):
    rows = 0
    for max_row, row in enumerate(ws, 1):
        if all(c.value is None for c in row):
            break
        rows += 1
    return rows
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Openpyxl 3.0.3,

Python 3.8.3,

MSExcel 16.27 (2019)

Reproduction:
In MSExcel, create workbook. Fill and save it similar to this,

Run the following code,

filepath = '..../yoursfilepath/Test.xlsx'
wb = openpyxl.load_workbook (filepath)
ws = wb.active
print (ws.max_row)

Note down the max_row count.

Now open the workbook in MSExcel and clear all the content in last row (here, 12-May-20) which have cell format as 'Custom' (any other than 'General')

Save it and run the above code again. It counts last row.
Even if you convert the Custom format to General, it counts that row with empty cells.

If you check cell values with ws.iter_rows () they are 'None' for that row.

However, if you delete that particular row using MSExcel and save it, we get correct max row count. But this cannot be the solution all the time.

Body:
The documentation states not to create the Worksheet yourself, I presume that this is a known bug when manually creating worksheets.

Do not create worksheets yourself, use openpyxl.workbook.Workbook.create_sheet() instead

However, if you must manually create them, this may solve your issue (modified from this answer)

def getMaxRows(ws):
    rows = 0
    for max_row, row in enumerate(ws, 1):
        if all(c.value is None for c in row):
            break
        rows += 1
    return rows


问:
How to count total number of person in a class

class Person:
      number_of_people = 0 #class atribute,define for the entire class

```<code>def __init__(self,name):
    self.name=name
</code>```

```<code>p1 = Person('tim')  # adding of object to class
p2 = Person('jill')
p3 = Person('Bill')

for x in range(Person.number_of_people): #will loop 3 time this case
print(Person.name)  # how do i print all the names in a class
</code>```

i cant seem to get this working

答:
You could initialize a variable NUMBER_OF_PEOPLE=0 outside your class declaration and then each time someone call __init__ you can add one:

class Person:
    # Declare class variables
    NUMBER_OF_PEOPLE = 0
    LIST_OF_PEOPLE = []
    def __init__(self, name):
        self.name = name
        # Change the class variables
        Person.LIST_OF_PEOPLE.append(self)
        Person.NUMBER_OF_PEOPLE +=  1

    @classmethod
    def get_number_of_people(cls):
        return Person.NUMBER_OF_PEOPLE

p1 = Person("tim")
p2 = Person("jill")
people = [p1, p2]  # create a list o two people
# Iterate through the list
for p in Person.LIST_OF_PEOPLE:
    # Access the name by calling p.name
    print("Name of the current person is: {}.".format(p.name))
# You can still access the NUMBER_OF_PEOPLE variable either by calling Person.get_number_of_people() (since it is a class method)
# or by simply using the NUMBER_OF_PEOPLE variable.
print("Currently, there are {} number of people in the class!".format(Person.get_number_of_people()))
# This will give 1 person.
```

Your issue here is that you don't completely understand object-oriented programming. You will get better by practising.

Body:
class Person:
      number_of_people = 0 #class atribute,define for the entire class

def __init__(self,name):
    self.name=name

p1 = Person('tim')  # adding of object to class
p2 = Person('jill')
p3 = Person('Bill')

for x in range(Person.number_of_people): #will loop 3 time this case
print(Person.name)  # how do i print all the names in a class

i cant seem to get this working

Body:
You could initialize a variable NUMBER_OF_PEOPLE=0 outside your class declaration and then each time someone call __init__ you can add one:

class Person:
    # Declare class variables
    NUMBER_OF_PEOPLE = 0
    LIST_OF_PEOPLE = []
    def __init__(self, name):
        self.name = name
        # Change the class variables
        Person.LIST_OF_PEOPLE.append(self)
        Person.NUMBER_OF_PEOPLE +=  1

    @classmethod
    def get_number_of_people(cls):
        return Person.NUMBER_OF_PEOPLE

p1 = Person("tim")
p2 = Person("jill")
people = [p1, p2]  # create a list o two people
# Iterate through the list
for p in Person.LIST_OF_PEOPLE:
    # Access the name by calling p.name
    print("Name of the current person is: {}.".format(p.name))
# You can still access the NUMBER_OF_PEOPLE variable either by calling Person.get_number_of_people() (since it is a class method)
# or by simply using the NUMBER_OF_PEOPLE variable.
print("Currently, there are {} number of people in the class!".format(Person.get_number_of_people()))
# This will give 1 person.

Your issue here is that you don't completely understand object-oriented programming. You will get better by practising.


问:
Apply javascript (add row) to 2 different form fields
This is all new to me and i don't have that much (or even none) knowledge of javascript. I hoped someone could help me out? I have 2 different form fields and i would like to apply a script to the 2 different form fields.
The thing is to add an extra form row. I found this script on-line and hoped to get it work for both fields.

These are the forms:

```<code><div class="card" style="width: 100%;" id="card-elements">
                <h5 class="card-header">Ingredients</h5>
                <div class="card-body">
                    <div class="ingredients-contents">
                        <form method="post" action="">
                            <div class="row">
                                <div class="col-lg-12">
                                    <div id="inputFormRow-ingredients">
                                        <div class="input-group mb-3">
                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">
                                            <div class="input-group-append">
                                                <button id="removeRow" type="button" class="btn btn-danger"><i class="fas fa-times-circle"></i></button>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="newRow"></div>
                                    <button id="addRow" type="button" class="btn btn-info">Add Ingredient</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="card" style="width: 100%;" id="card-elements">
                <h5 class="card-header">Steps</h5>
                <div class="card-body">
                    <div class="steps-contents">
                        <form method="post" action="">
                            <div class="row">
                                <div class="col-lg-12">
                                    <div id="inputFormRow-steps">
                                        <div class="input-group mb-3">
                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add Step" autocomplete="off">
                                            <div class="input-group-append">
                                                <button id="removeRow" type="button" class="btn btn-danger"><i class="fas fa-times-circle"></i></button>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="newRow"></div>
                                    <button id="addRow" type="button" class="btn btn-info">Add Step</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
</code>```

This is the script i'm using:

```<code> // add row
$("#addRow").click(function () {
    var html = '';
    html += '<div id="inputFormRow">';
    html += '<div class="input-group mb-3">';
    html += '<input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">';
    html += '<div class="input-group-append">';
    html += '<button id="removeRow" type="button" class="btn btn-danger"><i class="fas fa-times-circle"></i></button>';
    html += '</div>';
    html += '</div>';

    $('#newRow').append(html);
});

// remove row
$(document).on('click', '#removeRow', function () {
    $(this).closest('#inputFormRow').remove();
});
</code>```

答:
You're re-using the same id values throughout your code.  So when you select an element by its id like so:

```<code>$("#addRow")
</code>```

Which element are you expecting that selector to target and why?

To convert this to something that can be used multiple times on a page, your best bet is usually to switch from using an id to using a class.  In your code that'll involve a few changes.  First, change the addRow id values to class values:

```<code><div class="newRow"></div>
<button type="button" class="addRow btn btn-info">Add Ingredient</button>
</code>```

And target that selector:

```<code>$(".addRow").click(function () {
    // ...
});
</code>```

Within that click handler function, replace the id values with class values in the HTML being created:

```<code>html += '<div class="inputFormRow">';
//...
html += '<button type="button" class="removeRow btn btn-danger"><i class="fas fa-times-circle"></i></button>';
</code>```

The interesting bit is the last line of that function, because you'll need to target a specific instance of .newRow.  You can use the jQuery .siblings() function to find the one you want:

```<code>$(this).siblings(".newRow").append(html);
</code>```

Then in the remove functionality switching to class selectors should do the trick:

```<code>$(document).on('click', '.removeRow', function () {
    $(this).closest('.inputFormRow').remove();
});
</code>```

Throughout this, the main thing to keep in mind when switching from id to class so you can re-use the functionality throughout the page is to change the mindset from "globally target this specific element" to one of two concepts:

Globally target all of these elements; or...

Relatively target this specific element, by traversing the DOM from where I am now.

An example of the first one is adding the click handler to all matching .addRow elements.  An example of the second one is already present in the use of .closest(), and was also added here in the use of .siblings().  There are a variety of jQuery DOM traversal functions to help find a specific element you're looking for from the context of the element invoking the event.

Note: You may still have some work to be done here.  I'm noticing that all of your form inputs are still called ingredient[].  So they'll all post as one big array with no difference on the server-side.  If that's not the intent then you'll need to keep making some modifications.

Continuing down the path we've already started here, consider how you might tell this "add row" handler which type of row you want to add.  For example, maybe each .addRow element has a data attribute:

```<code><button type="button" class="addRow btn btn-info" data-rowType="ingredient">Add Ingredient</button>
</code>```

Then in the handler you can get that data:

```<code>const rowType = $(this).data('rowType');
</code>```

And use that value in the HTML being built:

```<code>html += '<input type="text" name="' + rowType + '[]" class="form-control m-input" placeholder="Add ' + rowType + '" autocomplete="off">';
</code>```

Body:
This is all new to me and i don't have that much (or even none) knowledge of javascript. I hoped someone could help me out? I have 2 different form fields and i would like to apply a script to the 2 different form fields.
The thing is to add an extra form row. I found this script on-line and hoped to get it work for both fields.

These are the forms:

Ingredients

                        <form method="post" action="">

                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">

                                                <button id="removeRow" type="button" class="btn btn-danger"></button>

                                    <button id="addRow" type="button" class="btn btn-info">Add Ingredient</button>

                        </form>

Steps

                        <form method="post" action="">

                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add Step" autocomplete="off">

                                                <button id="removeRow" type="button" class="btn btn-danger"></button>

                                    <button id="addRow" type="button" class="btn btn-info">Add Step</button>

                        </form>

This is the script i'm using:

 // add row
$("#addRow").click(function () {
    var html = '';
    html += '
';
    html += '
';
    html += '<input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">';
    html += '
';
    html += '<button id="removeRow" type="button" class="btn btn-danger"></button>';
    html += '
';
    html += '
';

    $('#newRow').append(html);
});

// remove row
$(document).on('click', '#removeRow', function () {
    $(this).closest('#inputFormRow').remove();
});

Body:
You're re-using the same id values throughout your code.  So when you select an element by its id like so:

$("#addRow")

Which element are you expecting that selector to target and why?

To convert this to something that can be used multiple times on a page, your best bet is usually to switch from using an id to using a class.  In your code that'll involve a few changes.  First, change the addRow id values to class values:

<div class="newRow"></div>
<button type="button" class="addRow btn btn-info">Add Ingredient</button>

And target that selector:

$(".addRow").click(function () {
    // ...
});

Within that click handler function, replace the id values with class values in the HTML being created:

html += '<div class="inputFormRow">';
//...
html += '<button type="button" class="removeRow btn btn-danger"><i class="fas fa-times-circle"></i></button>';

The interesting bit is the last line of that function, because you'll need to target a specific instance of .newRow.  You can use the jQuery .siblings() function to find the one you want:

$(this).siblings(".newRow").append(html);

Then in the remove functionality switching to class selectors should do the trick:

$(document).on('click', '.removeRow', function () {
    $(this).closest('.inputFormRow').remove();
});

Throughout this, the main thing to keep in mind when switching from id to class so you can re-use the functionality throughout the page is to change the mindset from "globally target this specific element" to one of two concepts:

Globally target all of these elements; or...

Relatively target this specific element, by traversing the DOM from where I am now.

An example of the first one is adding the click handler to all matching .addRow elements.  An example of the second one is already present in the use of .closest(), and was also added here in the use of .siblings().  There are a variety of jQuery DOM traversal functions to help find a specific element you're looking for from the context of the element invoking the event.

Note: You may still have some work to be done here.  I'm noticing that all of your form inputs are still called ingredient[].  So they'll all post as one big array with no difference on the server-side.  If that's not the intent then you'll need to keep making some modifications.

Continuing down the path we've already started here, consider how you might tell this "add row" handler which type of row you want to add.  For example, maybe each .addRow element has a data attribute:

<button type="button" class="addRow btn btn-info" data-rowType="ingredient">Add Ingredient</button>

Then in the handler you can get that data:

const rowType = $(this).data('rowType');

And use that value in the HTML being built:

html += '<input type="text" name="' + rowType + '[]" class="form-control m-input" placeholder="Add ' + rowType + '" autocomplete="off">';


问:
ElasticSeach Auto Complete using Completion suggester to Return the Complete Document
I am using Elastic search's Completion suggester for one of our Auto Complete text box. I was wondering whether it is possible to return the Documents instead of the strings (Suggestion) using the Completion suggester ?

For eg. Now If i search for "Ban" it will return "Banana", "Bandana". Just the string but is it possible to return the complete document which the string is part of ?

If I wrote normal full text queries on the same field will that be optimized for AutoComplete ?

When I tried running the raw Elastic search completion query. I was getting the complete document instead of suggested strings -

Doc Link : https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html#querying

Query I have used -

```<code>POST /my_entities/_search?pretty
{
    "suggest": {
        "auto-suggest" : {
            "prefix" : "banda",
            "completion" : {
                "field" : "name"
            }
        }
    }
}.
</code>```

Above raw query returned the following source (Only pasting the source of the ouput)-

```<code>{
   "_source":{
      "entityType":"cloth",
      "entityId":"bandana",
      "name":"Bandana",
   }
}
</code>```

答:
Completion suggester will not return the whole document as its just a suggester and doesn't work like full-text search which returns the whole document.

Completion suggester will return the whole document as part of the suggest. You can control which all keys to be returned using the source in while querying.

Refer this link for information on how to extract the source fields using Java Client API.

If you want the whole document, then you implement autosuggest in full-text and there are various ways.

You can also refer https://stackoverflow.com/a/60584211/4039431 for more information on the functional and non-functional requirements to build autocomplete.

Body:
I am using Elastic search's Completion suggester for one of our Auto Complete text box. I was wondering whether it is possible to return the Documents instead of the strings (Suggestion) using the Completion suggester ?

For eg. Now If i search for "Ban" it will return "Banana", "Bandana". Just the string but is it possible to return the complete document which the string is part of ?

If I wrote normal full text queries on the same field will that be optimized for AutoComplete ?

When I tried running the raw Elastic search completion query. I was getting the complete document instead of suggested strings -

Doc Link : https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html#querying

Query I have used -

POST /my_entities/_search?pretty
{
    "suggest": {
        "auto-suggest" : {
            "prefix" : "banda",
            "completion" : {
                "field" : "name"
            }
        }
    }
}.

Above raw query returned the following source (Only pasting the source of the ouput)-

{
   "_source":{
      "entityType":"cloth",
      "entityId":"bandana",
      "name":"Bandana",
   }
}


答: You would need a global variable to keep track of each instance this way, but more likely you would define a parent class, like People, and then have your Person class inherit from People. People would instead be in charge of tracking how many Person instances you've created. The latter option would be best if you have to look at more than just this one relationship between your Person instances. If you wanted to iterate through your Persons, for example, that could be a methods of your People class.</p>

Title: How to count total number of person in a class


问:
React native Deprecated Gradle features when Builing apk
I'm trying to build my apk using ./gradlew bundleRelease but I always get this error:

```<code>error EISDIR: illegal operation on a directory, open 'P:\React'. Run CLI with --verbose flag for more details.
Error: EISDIR: illegal operation on a directory, open 'P:\React'

> Task :app:bundleReleaseJsAndAssets FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
> Process 'command 'npx.cmd'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings
</code>```

I also tried ./gradlew app:assembleRelease but I get the same error. I also created my project using npx.

答:
I tried everything, I even updated the project gradle verion but I would still get the same error. But the solution was just this:

```<code>cd android
</code>```

clean your gradle:

```<code>./gradlew clean
</code>```

then:

```<code>./gradlew assembleRelease -x bundleReleaseJsAndAssets
</code>```

Body:
I'm trying to build my apk using ./gradlew bundleRelease but I always get this error:

error EISDIR: illegal operation on a directory, open 'P:\React'. Run CLI with --verbose flag for more details.
Error: EISDIR: illegal operation on a directory, open 'P:\React'

> Task :app:bundleReleaseJsAndAssets FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
> Process 'command 'npx.cmd'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings

I also tried ./gradlew app:assembleRelease but I get the same error. I also created my project using npx.

Body:
I tried everything, I even updated the project gradle verion but I would still get the same error. But the solution was just this:

cd android

clean your gradle:

./gradlew clean

then:

./gradlew assembleRelease -x bundleReleaseJsAndAssets


问:
Python regex function to arrange key:value in descending order. Wherein the key is alphanumeric and the value is digits
Say I have a column which has values like:

```<code>**Input**

A12:67, A18:24, B11:89
A12:78, A19:100
B12:100, A20:19, A01:91
</code>```

I would like the piece of code that I am working on to return:

```<code>**Expected Output**

B11:89, A12:67, A18:24
A19:100, A12:78
B12:100, A01:91, A20:19
</code>```

I'm trying to get the code to sort this key-value pair based on the value of the item in descending order
This is the code I have written as of now, but it's sorting based on the digits in the Key and not the value.

```<code>def sortitem(df):
    sorteddf = df.apply(lambda x :",".join(sorted(x.split(", "), key=lambda y: int(re.search(r"(\d+)", y).group(1)), reverse=True)))
    return sorteddf
</code>```

The code outputs:

```<code>**Output received**

A18:24, A12:67, B11:89
A19:100, A12:78
A20:19, B12:100, A01:91
</code>```

Which is not the expected output. Please help with the corrections in the code required to achieve the desired output.
Thank you.

答:
You may use

```<code>df['Input'].apply(lambda r: ', '.join(sorted(r.split(', '), key=lambda s: int(s.split(':')[-1]), reverse=True)))
</code>```

Pandas test:

```<code>df = pd.DataFrame({'Input':['A12:67, A18:24, B11:89','A12:78, A19:100','B12:100, A20:19, A01:91']})
df['Input'] = df['Input'].apply(lambda r: ', '.join(sorted(r.split(', '), key=lambda s: int(s.split(':')[-1]), reverse=True)))
>>> df
                     Input
0   B11:89, A12:67, A18:24
1          A19:100, A12:78
2  B12:100, A01:91, A20:19
</code>```

NOTES:

r.split(', ') - splits each cell value with comma+space

sorted(..., key=lambda s: int(s.split(':')[-1]), reverse=True) - sorts the split chunks by the integer value that is after : (obtained by splitting the cell value with : and last item accessed with [-1] and then cast to int using int(s.split(':')[-1])) in descending order (due to reverse=True

', '.join(...) - combines back the split chunks

Body:
Say I have a column which has values like:

**Input**

A12:67, A18:24, B11:89
A12:78, A19:100
B12:100, A20:19, A01:91

I would like the piece of code that I am working on to return:

**Expected Output**

B11:89, A12:67, A18:24
A19:100, A12:78
B12:100, A01:91, A20:19

I'm trying to get the code to sort this key-value pair based on the value of the item in descending order
This is the code I have written as of now, but it's sorting based on the digits in the Key and not the value.

def sortitem(df):
    sorteddf = df.apply(lambda x :",".join(sorted(x.split(", "), key=lambda y: int(re.search(r"(\d+)", y).group(1)), reverse=True)))
    return sorteddf

The code outputs:

**Output received**

A18:24, A12:67, B11:89
A19:100, A12:78
A20:19, B12:100, A01:91

Which is not the expected output. Please help with the corrections in the code required to achieve the desired output.
Thank you.

Body:
You may use

df['Input'].apply(lambda r: ', '.join(sorted(r.split(', '), key=lambda s: int(s.split(':')[-1]), reverse=True)))

Pandas test:

df = pd.DataFrame({'Input':['A12:67, A18:24, B11:89','A12:78, A19:100','B12:100, A20:19, A01:91']})
df['Input'] = df['Input'].apply(lambda r: ', '.join(sorted(r.split(', '), key=lambda s: int(s.split(':')[-1]), reverse=True)))
>>> df
                     Input
0   B11:89, A12:67, A18:24
1          A19:100, A12:78
2  B12:100, A01:91, A20:19

NOTES:

r.split(', ') - splits each cell value with comma+space

sorted(..., key=lambda s: int(s.split(':')[-1]), reverse=True) - sorts the split chunks by the integer value that is after : (obtained by splitting the cell value with : and last item accessed with [-1] and then cast to int using int(s.split(':')[-1])) in descending order (due to reverse=True

', '.join(...) - combines back the split chunks


问:
regex - remove partial text from duplicate strings
with some hassle i've come up with the following reg ex: (?m)(XXX).*\R(?s).*?\K\1 where XXX is the text i am selecting in the duplicate string (in this case (?m)(#  .*).*\R(?s).*?\K\1).

When I go for finds everything is ok but somehow Notepad++ gets stuck when I am trying to apply it and failing replaces. Sometimes find also fails too. any help about?

E.g.:

```<code>#Tfr.msg.FoldCleanup#   Folder Cleanup
#Tfr.msg.FoldCleanup#   Folder Cleanup
</code>```

I need to select and change everything after '# ' of every second duplicate string.

update: i've tried it here (https://regex101.com/r/WQXFy6/42) and it works correctly. but it goes completely nothing with N++...

答:
I also have found out myself the correct regex for my first question:</p>
```<code>(#  .*)\r(?s).*?
</code>```

Body:
with some hassle i've come up with the following reg ex: (?m)(XXX).*\R(?s).*?\K\1 where XXX is the text i am selecting in the duplicate string (in this case (?m)(#  .*).*\R(?s).*?\K\1).

When I go for finds everything is ok but somehow Notepad++ gets stuck when I am trying to apply it and failing replaces. Sometimes find also fails too. any help about?

E.g.:

#Tfr.msg.FoldCleanup#   Folder Cleanup
#Tfr.msg.FoldCleanup#   Folder Cleanup

I need to select and change everything after '# ' of every second duplicate string.

update: i've tried it here (https://regex101.com/r/WQXFy6/42) and it works correctly. but it goes completely nothing with N++...

Body:
I also have found out myself the correct regex for my first question:

(#  .*)\r(?s).*?


问:
How to keep my test methods with proguard.cfg
For my Android instrumentation test I need a few extra entry point into my classes. Those methods are not used in the actual application. My idea was to start them all with test_ and have a general rule to exclude them from being optimized away. This is how far I got:

```<code>-keepclassmembers class com.xxx.**.* {
    public ** test_* ();
    public ** test_* (**);
    public static ** test_* ();
    public static ** test_* (**);
}
</code>```

But it still does not work. public static void test_destroy (final android.content.Context context) and private void dropTables (final SQLiteDatabase db) has just been removed from the code. And I have no idea why.

How is it properly used for wildcard patterns?

答:
The solution is</p>

```<code>-keepclassmembers class com.XXX.**.* {
    *** test_* (...);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For my Android instrumentation test I need a few extra entry point into my classes. Those methods are not used in the actual application. My idea was to start them all with test_ and have a general rule to exclude them from being optimized away. This is how far I got:

-keepclassmembers class com.xxx.**.* {
    public ** test_* ();
    public ** test_* (**);
    public static ** test_* ();
    public static ** test_* (**);
}

But it still does not work. public static void test_destroy (final android.content.Context context) and private void dropTables (final SQLiteDatabase db) has just been removed from the code. And I have no idea why.

How is it properly used for wildcard patterns?

Body:
The solution is

-keepclassmembers class com.XXX.**.* {
    *** test_* (...);
}


问:
why my django slug is not working properly
I want to allow user to search in database for the topic. and show the topic name in url.
I already created slug field in database but when i am trying to fetch the data from the database the url is not showing correctly.

url is showing:

```<code>http://127.0.0.1:8000/topic/<slug:topicname>/
</code>```

what I want to show:

```<code>http://127.0.0.1:8000/topic/introduction-to-python/
</code>```

My urls.py file

from django.urls import path
from . import views

```<code>urlpatterns = [
    path('', views.apphome),
    path('topic/<slug:topicname>/', views.searchtopic, name = 'searchtopic'),

]
</code>```

My model for the project

```<code>class blogposts(models.Model):
    topic = models.CharField(max_length = 200)
    slug = models.SlugField(max_length = 150, null=True, blank = True)
    post = models.TextField(max_length = 500)

    def __str__(self):
        return self.topic
</code>```

This is my view

```<code>def searchtopic(request,topicname):
    if request.method == 'POST':
        topicname = request.POST.get('searchtopicname')

        mypost = mypostlist.objects.filter(slug = topicname)
        context = {
            'mypost':mypost,
            }
        return render(request, 'blog/result.html',context)
</code>```

My form for searching topic

```<code><form action="topic/<slug:topicname>/" method="POST">
       {% csrf_token %}
       <input type="search" placeholder="Search topics or keywords" name="searchtopicname">
       <button type="submit">Search</button>
</form>
</code>```

答:
You can use 'GET' method insted of 'POST'
replace form with:

```<code><form action="{%url 'searchtopic' %}" method="GET">
   {% csrf_token %}
   <input type="search" placeholder="Search topics or keywords" name="searchtopicname">
   <button type="submit">Search</button>
</form>
</code>```

replace urls.py:

```<code>urlpatterns = [
path('', views.apphome),
path('topic/', views.searchtopic, name = 'searchtopic'),
]
</code>```

replace views:

```<code>def searchtopic(request):
if request.method == 'GET':
    topicname = request.GET['searchtopicname']

    mypost = mypostlist.objects.filter(slug = topicname)
    context = {
        'mypost':mypost,
        }
    return render(request, 'blog/result.html',context)
</code>```

Body:
I want to allow user to search in database for the topic. and show the topic name in url.
I already created slug field in database but when i am trying to fetch the data from the database the url is not showing correctly.

url is showing:

http://127.0.0.1:8000/topic/<slug:topicname>/

what I want to show:

http://127.0.0.1:8000/topic/introduction-to-python/

My urls.py file

from django.urls import path
from . import views

urlpatterns = [
    path('', views.apphome),
    path('topic/<slug:topicname>/', views.searchtopic, name = 'searchtopic'),

]

My model for the project

class blogposts(models.Model):
    topic = models.CharField(max_length = 200)
    slug = models.SlugField(max_length = 150, null=True, blank = True)
    post = models.TextField(max_length = 500)

    def __str__(self):
        return self.topic

This is my view

def searchtopic(request,topicname):
    if request.method == 'POST':
        topicname = request.POST.get('searchtopicname')

        mypost = mypostlist.objects.filter(slug = topicname)
        context = {
            'mypost':mypost,
            }
        return render(request, 'blog/result.html',context)

My form for searching topic

<form action="topic/<slug:topicname>/" method="POST">
       {% csrf_token %}
       <input type="search" placeholder="Search topics or keywords" name="searchtopicname">
       <button type="submit">Search</button>
</form>

Body:
You can use 'GET' method insted of 'POST'
replace form with:

<form action="{%url 'searchtopic' %}" method="GET">
   {% csrf_token %}
   <input type="search" placeholder="Search topics or keywords" name="searchtopicname">
   <button type="submit">Search</button>
</form>

replace urls.py:

urlpatterns = [
path('', views.apphome),
path('topic/', views.searchtopic, name = 'searchtopic'),
]

replace views:

def searchtopic(request):
if request.method == 'GET':
    topicname = request.GET['searchtopicname']

    mypost = mypostlist.objects.filter(slug = topicname)
    context = {
        'mypost':mypost,
        }
    return render(request, 'blog/result.html',context)


问:
How to get witch values of specific enum passed to a method
I'm trying get which values of specific enum passed to a method and also what the diffrence between | and & operator when passing enums?

Enum:

```<code>enum VectorAxis
{
    X,Y,Z
}
</code>```

Method:

```<code>void SampleMethod(VectorAxis ignoredAxis)
{
// Get witch enums passed
}
</code>```

Caller:

```<code>SampleMethod(VectorAxis.X | VectorAxis.Y);
</code>```

or

```<code>SampleMethod(VectorAxis.X & VectorAxis.Y);
</code>```

答:
Enums work just like an integer, every enum value has a numerical value. If you don't set that value to anything and leave it default (like you did with VectorAxis) they will have values from 0 up to the limit of the underlying type (usually int, unless you change it). This means performing bitwise operations on them is the same as bitwise operations on integers.

If you don't know how bitwise operations work you can read about them here.

If you want to be able to use them as flags you have to set the values to powers of 2. Let's do that:

```<code>enum VectorAxis
{
    X = 1,
    Y = 2,
    Z = 4,
}
</code>```

And to make printing easier let's add the flags attribute.

```<code>[Flags]
enum VectorAxis
</code>```

Now if you print VectorAxis.X | VectorAxis.Y to console you get X, Y.
If you want to know if the passed value has the Z flag, you can use the bitwise and:

```<code>(ignoredAxis & VectorAxis.Z) != 0
</code>```

If you call the SampleMethod with VectorAxis.X | VectorAxis.Y the result is false. but if you change the parameter to VectorAxis.X | VectorAxis.Z the result will be true. You can use this to check every axis.

Body:
I'm trying get which values of specific enum passed to a method and also what the diffrence between | and & operator when passing enums?

Enum:

enum VectorAxis
{
    X,Y,Z
}

Method:

void SampleMethod(VectorAxis ignoredAxis)
{
// Get witch enums passed
}

Caller:

SampleMethod(VectorAxis.X | VectorAxis.Y);

or

SampleMethod(VectorAxis.X & VectorAxis.Y);

Body:
Enums work just like an integer, every enum value has a numerical value. If you don't set that value to anything and leave it default (like you did with VectorAxis) they will have values from 0 up to the limit of the underlying type (usually int, unless you change it). This means performing bitwise operations on them is the same as bitwise operations on integers.

If you don't know how bitwise operations work you can read about them here.

If you want to be able to use them as flags you have to set the values to powers of 2. Let's do that:

enum VectorAxis
{
    X = 1,
    Y = 2,
    Z = 4,
}

And to make printing easier let's add the flags attribute.

[Flags]
enum VectorAxis

Now if you print VectorAxis.X | VectorAxis.Y to console you get X, Y.
If you want to know if the passed value has the Z flag, you can use the bitwise and:

(ignoredAxis & VectorAxis.Z) != 0

If you call the SampleMethod with VectorAxis.X | VectorAxis.Y the result is false. but if you change the parameter to VectorAxis.X | VectorAxis.Z the result will be true. You can use this to check every axis.


问:
Spark: Merging 2 columns of a DataSet into a single column
I have a table with ids as 2 different columns. I have another table which contains objects associated with the ids. I would like filter out the ids from the table2 for which id exists in either id1 or id2 in Table 1.

Table 1:

```<code>| id1  | id2 |
|  1   |  1  |
|  1   |  1  |
|  1   |  3  |
|  2   |  5  |
|  3   |  1  |
|  3   |  2  |
|  3   |  3  |
</code>```

Table 2:

```<code>| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  4  |  'D'  |
|  5  |  'E'  |
|  6  |  'F'  |
|  7  |  'G'  |
</code>```

What I am thinking is to create out a list from table1 containing the unique ids which will be [1, 2, 3, 5] from above example.

Then filter out the data frame on the basis of the list, which will give the result.

```<code>| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  5  |  'E'  |
</code>```

Though I have concerns regarding the scalability of the solution. The list can be large and it may even fail to load into memory for some cases. Any recommendations here in this case?

Thanks.

答:
The following approach would work

```<code>      import spark.implicits._
      val t1 = Seq((1,1),(1,1),(1,3),(2,5),(3,1),(3,2),(3,3))
      val t2 = Seq((1,"A"),(2,"B"),(3,"C"),(4,"D"),(5,"E"),(6,"F"),(7,"G"))
      val tt1 = sc.parallelize(t1).toDF("id1","id2")
                  .persist(StorageLevel.MEMORY_AND_DISK)
      val tt2 = sc.parallelize(t2).toDF("id", "obj")
                  .persist(StorageLevel.MEMORY_AND_DISK)

      tt1.show()
      tt2.show()

      tt1.createOrReplaceTempView("table1")
      tt2.createOrReplaceTempView("table2")

     val output = sqlContext.sql(
        """
          |SELECT DISTINCT id, obj
          |FROM table1 t1
          |JOIN table2 t2 ON(t1.id1 = t2.id) OR (t1.id2 = id)
          |ORDER BY id
          |""".stripMargin).persist(StorageLevel.MEMORY_AND_DISK)

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

output

```<code>+---+---+
| id|obj|
+---+---+
|  1|  A|
|  2|  B|
|  3|  C|
|  5|  E|
+---+---+
</code>```

For memory issues you can persist the data to memory and disk, however there are more options, you can choose the best option that fit with your particular problem, you can follow this link:
RDD Persistence

I would consider too the number of partitions by configuring:

```<code>spark.sql.shuffle.partitions
/*
Configures the number of partitions to use when shuffling data for joins or aggregations.
*/

  val spark = SparkSession
    .builder()
    .appName("MySparkProcess")
    .master("local[*]")
    .config("spark.sql.shuffle.partitions","400") //Change to a more reasonable default number of partitions for our data
    .config("spark.app.id","MySparkProcess") // To silence Metrics warning
    .getOrCreate()
</code>```

I would take a look to this link too for further configuration:

Performance Tuning

Body:
I have a table with ids as 2 different columns. I have another table which contains objects associated with the ids. I would like filter out the ids from the table2 for which id exists in either id1 or id2 in Table 1.

Table 1:

| id1  | id2 |
|  1   |  1  |
|  1   |  1  |
|  1   |  3  |
|  2   |  5  |
|  3   |  1  |
|  3   |  2  |
|  3   |  3  |

Table 2:

| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  4  |  'D'  |
|  5  |  'E'  |
|  6  |  'F'  |
|  7  |  'G'  |

What I am thinking is to create out a list from table1 containing the unique ids which will be [1, 2, 3, 5] from above example.

Then filter out the data frame on the basis of the list, which will give the result.

| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  5  |  'E'  |

Though I have concerns regarding the scalability of the solution. The list can be large and it may even fail to load into memory for some cases. Any recommendations here in this case?

Thanks.

Body:
The following approach would work

      import spark.implicits._
      val t1 = Seq((1,1),(1,1),(1,3),(2,5),(3,1),(3,2),(3,3))
      val t2 = Seq((1,"A"),(2,"B"),(3,"C"),(4,"D"),(5,"E"),(6,"F"),(7,"G"))
      val tt1 = sc.parallelize(t1).toDF("id1","id2")
                  .persist(StorageLevel.MEMORY_AND_DISK)
      val tt2 = sc.parallelize(t2).toDF("id", "obj")
                  .persist(StorageLevel.MEMORY_AND_DISK)

      tt1.show()
      tt2.show()

      tt1.createOrReplaceTempView("table1")
      tt2.createOrReplaceTempView("table2")

     val output = sqlContext.sql(
        """
          |SELECT DISTINCT id, obj
          |FROM table1 t1
          |JOIN table2 t2 ON(t1.id1 = t2.id) OR (t1.id2 = id)
          |ORDER BY id
          |""".stripMargin).persist(StorageLevel.MEMORY_AND_DISK)

      output.show()

output

+---+---+
| id|obj|
+---+---+
|  1|  A|
|  2|  B|
|  3|  C|
|  5|  E|
+---+---+

For memory issues you can persist the data to memory and disk, however there are more options, you can choose the best option that fit with your particular problem, you can follow this link:
RDD Persistence

I would consider too the number of partitions by configuring:

spark.sql.shuffle.partitions
/*
Configures the number of partitions to use when shuffling data for joins or aggregations.
*/

  val spark = SparkSession
    .builder()
    .appName("MySparkProcess")
    .master("local[*]")
    .config("spark.sql.shuffle.partitions","400") //Change to a more reasonable default number of partitions for our data
    .config("spark.app.id","MySparkProcess") // To silence Metrics warning
    .getOrCreate()

I would take a look to this link too for further configuration:

Performance Tuning


问:
GradientTape not computing gradient
I understand that so long as i am defining a computation in tf.GradientTape() context, the gradient tape would compute the gradient w.r.t all the variables that the output of the computation depends on. However, i think i am not quite grasping the subtelties of the gradient as the following code does not execute as i expect it to:

```<code>import tensorflow as tf
x = tf.Variable(2.)
loss_ = x**2-2*x+1
with tf.GradientTape(persistent=True) as g:
    loss = loss_*1
print(g.gradient(loss,x))
output: None
</code>```

Why is the gradient wrt x not computed?

I am able to compute only the gradients that are wrt to the variables that are getting explicitly used within the context. for example the following code does not compute gradients as well:

```<code>import tensorflow as tf
tf.compat.v1.disable_eager_execution()
x = tf.Variable(2.)
t1 = x**2
t2 = -2*x
t3 = 1.
with tf.GradientTape(persistent=True) as g:
    loss = t1+t2+t3
print(g.gradient(loss,x))
</code>```

答:
The GradientTape object g goes out of scope after the with statement ends.

In other words, try printing the gradient inside the with statement.

Here's what works for me:

```<code>def get_gradients(inputs, target, model):
    with tf.GradientTape() as tape:
        prediction = model(inputs)
        loss = loss_object(target, prediction)
        gradient = tape.gradient(loss, model.trainable_variables)

    return gradient
</code>```

Title: GradientTape not computing gradient

Body:
I understand that so long as i am defining a computation in tf.GradientTape() context, the gradient tape would compute the gradient w.r.t all the variables that the output of the computation depends on. However, i think i am not quite grasping the subtelties of the gradient as the following code does not execute as i expect it to:

import tensorflow as tf
x = tf.Variable(2.)
loss_ = x**2-2*x+1
with tf.GradientTape(persistent=True) as g:
    loss = loss_*1
print(g.gradient(loss,x))
output: None

Why is the gradient wrt x not computed?

I am able to compute only the gradients that are wrt to the variables that are getting explicitly used within the context. for example the following code does not compute gradients as well:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
x = tf.Variable(2.)
t1 = x**2
t2 = -2*x
t3 = 1.
with tf.GradientTape(persistent=True) as g:
    loss = t1+t2+t3
print(g.gradient(loss,x))

Body:
The GradientTape object g goes out of scope after the with statement ends.

In other words, try printing the gradient inside the with statement.

Here's what works for me:

def get_gradients(inputs, target, model):
    with tf.GradientTape() as tape:
        prediction = model(inputs)
        loss = loss_object(target, prediction)
        gradient = tape.gradient(loss, model.trainable_variables)

    return gradient


问:
using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function
Currently I faced this error, can anyone help solve it?

---------------------------------------------------------------------------
OperatorNotAllowedInGraphError            Traceback (most recent call last)
<ipython-input-24-0211c82920d0> in <module>
      7 warnings.filterwarnings("ignore")
      8 model.train(dataset_train,dataset_val, learning_rate=config.LEARNING_RATE,epochs=5,
----> 9             layers='heads')
/kaggle/working/maskrcnn/Mask_RCNN-master/mrcnn/model.py in train(self, train_dataset, val_dataset, learning_rate, epochs, layers, augmentation, custom_callbacks, no_augmentation_sources)
   2355         log("Checkpoint Path: {}".format(self.checkpoint_path))
   2356         self.set_trainable(layers)
-> 2357         self.compile(learning_rate, self.config.LEARNING_MOMENTUM)
   2358
   2359         # Work-around for Windows: Keras fails on Windows when using
/kaggle/working/maskrcnn/Mask_RCNN-master/mrcnn/model.py in compile(self, learning_rate, momentum)
   2168         for name in loss_names:
   2169             layer = self.keras_model.get_layer(name)
-> 2170             if layer.output in self.keras_model.losses:
   2171                 continue
   2172             loss = (
/opt/conda/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in __bool__(self)
    763       `TypeError`.
    764     """
--> 765     self._disallow_bool_casting()
    766
    767   def __nonzero__(self):

/opt/conda/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in _disallow_bool_casting(self)
    532     else:
    533       # Default: V1-style Graph execution.
--> 534       self._disallow_in_graph_mode("using a `tf.Tensor` as a Python `bool`")
    535
    536   def _disallow_iteration(self):

/opt/conda/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in _disallow_in_graph_mode(self, task)
    521     raise errors.OperatorNotAllowedInGraphError(
    522         "{} is not allowed in Graph execution. Use Eager execution or decorate"
--> 523         " this function with @tf.function.".format(task))
    524
    525   def _disallow_bool_casting(self):

OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
```

答:
I have stumble over this also hence i am leaving my solution to this problem to help anyone.

There is a catch when you are in eager execution mode since tf upgraded to 2.x, if you are using keras API loss and metrics you should instantiate them in order to compile.

See the example below:

model.compile(optimizer="...",
              loss=keras.losses.AnyLoss,
              metrics=[keras.metrics.AnyMetric])
```
<p>Above code will give <code>OperatorNotAllowedInGraphError</code>. To overcome do this;</p>
<pre class="lang-py prettyprint-override"><code>my_loss = keras.losses.AnyLoss(lr, *args, **kwargs)
my_metric = keras.metrics.AnyMetric(*args, **kwargs)

model.compile(optimizer,
              loss = my_loss
              metrics = [my_metric_1, my_metric_2...]
</code>```

That should do the trick

Body:
I have stumble over this also hence i am leaving my solution to this problem to help anyone.

There is a catch when you are in eager execution mode since tf upgraded to 2.x, if you are using keras API loss and metrics you should instantiate them in order to compile.

See the example below:

model.compile(optimizer="...",
              loss=keras.losses.AnyLoss,
              metrics=[keras.metrics.AnyMetric])

Above code will give OperatorNotAllowedInGraphError. To overcome do this;

my_loss = keras.losses.AnyLoss(lr, *args, **kwargs)
my_metric = keras.metrics.AnyMetric(*args, **kwargs)

model.compile(optimizer,
              loss = my_loss
              metrics = [my_metric_1, my_metric_2...]

That should do the trick


问:
Platform IO :undefined reference to `init'/[.pio\build\uno\firmware.elf] Error 1
I use visual studio code for programing arduino uno using platform io. But when I build my code there is no mistake I seen on problem. there is no error script on there. but on terminal says like this:

Executing task: C:\Users\ridho.platformio\penv\Scripts\platformio.exe run <

Processing uno (platform: atmelavr; board: uno; framework: arduino)

Verbose mode can be enabled via -v, --verbose option

CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/uno.html

PLATFORM: Atmel AVR 2.1.0 > Arduino Uno

HARDWARE: ATMEGA328P 16MHz, 2KB RAM, 31.50KB Flash

DEBUG: Current (simavr) On-board (simavr)

PACKAGES:

framework-arduino-avr 5.0.0

toolchain-atmelavr 1.50400.190710 (5.4.0)

LDF: Library Dependency Finder ->

LDF Modes: Finder ~ chain, Compatibility ~ soft

Found 6 compatible libraries

Scanning dependencies...

No dependencies

Building in release mode

Linking .pio\build\uno\firmware.elf

C:\Users\ridho\AppData\Local\Temp\ccrKx04Q.ltrans0.ltrans.o: In function main':
***<artificial>:(.text.startup+0x0): undefined reference toinit'*
collect2.exe: error: ld returned 1 exit status
****** [.pio\build\uno\firmware.elf] Error 1*
==================================================== [FAILED] Took 1.43 seconds ====================================================
The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

I assume that the main problem is : undefined reference to `init' or*** [.pio\build\uno\firmware.elf] Error 1

I have read all same problem like this ask in platform io community ,and professional said that the solution is disable any antivirus. I just have kaspersky antivirus on my pc. I also disable win defender,win firewall. but when I build again. still same. anyone can help me?

this my antivirus that have been disabled by me:
this image by clicking

答:
this the solution:

https://www.youtube.com/watch?v=CUfci2AEBNk&t=3s

type this/copy&paste:   %userprofile%.platformio\packages,

you'ill find framework-arduino-avr folder

and then you deleting the framework-arduino-avr folder


问:
string manipulation: partly convert to lowercase
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

```<code>>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2
</code>```

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

```<code>>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee
</code>```

This is exactly what I wanted. Thanks everyone for helping. Cheers!!

答:
I don't really get why you are using a regular expression? Why don't you just do:</p>

```<code>x, y = ss.split('(')
'('.join((x.lower(), y))
</code>```

Body:
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee

This is exactly what I wanted. Thanks everyone for helping. Cheers!!

Body:
I don't really get why you are using a regular expression? Why don't you just do:

x, y = ss.split('(')
'('.join((x.lower(), y))


问:
How to add action from redux connect to component props typescript
I want to declare props in my react component. Here is code:

```<code>interface HeaderProps {
  getUserData: typeof _getUserData;
}

const Header: React.FC<HeaderProps> = ({ getUserData }) => {
  useEffect(() => {
    getUserData();
  }, []);

  return <div>Test</div>;
};

const mapDispatchToProps = {
  getUserData: _getUserData,
};

export default connect(() => ({}), mapDispatchToProps)(Header);

</code>```

But TS is throwing error. I have tried to rewrite connect like this
connect<{}, HeaderProps>(() => ({}), mapDispatchToProps)(Header);
But it have not worked.
I have tried to look for answer in the web, but was not ably to find any.
TS Error:

```<code>rgument of type 'FC<HeaderProps>' is not assignable to parameter of type 'ComponentType<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
  Type 'FunctionComponent<HeaderProps>' is not assignable to type 'FunctionComponent<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
    Types of property 'propTypes' are incompatible.
      Type 'WeakValidationMap<HeaderProps> | undefined' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>> | undefined'.
        Type 'WeakValidationMap<HeaderProps>' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
          Types of property 'getUserData' are incompatible.
            Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>> | undefined' is not assignable to type 'Validator<() => Promise<void>> | undefined'.
              Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>>' is not assignable to type 'Validator<() => Promise<void>>'.
                Type '() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>' is not assignable to type '() => Promise<void>'.ts(2345)

</code>```

答:
I have found a solution. In react-redux they have added ConnectedProps.
So I have changed code to this:

import { connect, ConnectedProps } from 'react-redux';

type Props = PropsFromRedux;

const Header: React.FC<PropsFromRedux> = ({ getUserData }) => {
  useEffect(() => {
    getUserData();
  }, []);

  return
Test
;
};

const mapDispatchToProps = {
  getUserData: _getUserData,
};

const connector = connect(() => ({}), mapDispatchToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;
export default connect(() => ({}), mapDispatchToProps)(Header);
```

And it worked

Body:
I want to declare props in my react component. Here is code:

interface HeaderProps {
  getUserData: typeof _getUserData;
}

const Header: React.FC<HeaderProps> = ({ getUserData }) => {
  useEffect(() => {
    getUserData();
  }, []);

  return
Test
;
};

const mapDispatchToProps = {
  getUserData: _getUserData,
};

export default connect(() => ({}), mapDispatchToProps)(Header);

But TS is throwing error. I have tried to rewrite connect like this
connect<{}, HeaderProps>(() => ({}), mapDispatchToProps)(Header);
But it have not worked.
I have tried to look for answer in the web, but was not ably to find any.
TS Error:

rgument of type 'FC<HeaderProps>' is not assignable to parameter of type 'ComponentType<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
  Type 'FunctionComponent<HeaderProps>' is not assignable to type 'FunctionComponent<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
    Types of property 'propTypes' are incompatible.
      Type 'WeakValidationMap<HeaderProps> | undefined' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>> | undefined'.
        Type 'WeakValidationMap<HeaderProps>' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
          Types of property 'getUserData' are incompatible.
            Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>> | undefined' is not assignable to type 'Validator<() => Promise<void>> | undefined'.
              Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>>' is not assignable to type 'Validator<() => Promise<void>>'.
                Type '() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>' is not assignable to type '() => Promise<void>'.ts(2345)

Body:
I have found a solution. In react-redux they have added ConnectedProps.
So I have changed code to this:

import { connect, ConnectedProps } from 'react-redux';

type Props = PropsFromRedux;

const Header: React.FC<PropsFromRedux> = ({ getUserData }) => {
  useEffect(() => {
    getUserData();
  }, []);

  return <div>Test</div>;
};

const mapDispatchToProps = {
  getUserData: _getUserData,
};

const connector = connect(() => ({}), mapDispatchToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;
export default connect(() => ({}), mapDispatchToProps)(Header);

And it worked