问:
How to extract specific String from rows of a dataframe?
this is a part of my dataframe:

```<code>RefactoringDetail
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Move Class GameLogic.PlayerHuman moved to blokusgame.mi.android.hazi.blokus.GameLogic.PlayerHuman"
</code>```

I need just this part:

```<code> blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
 blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
 blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
 GameLogic.PlayerHuman
</code>```

this is my code :

```<code>import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep=';')
refactoring_details = df['RefactoringDetail']
print(refactoring_details)
a=refactoring_details.to_frame(name=None)
</code>```

And then to extract what i need from the data frame I tried to use substring but it did not work

```<code>for elem in a:
  s = substring.substringByChar("elem", startChar="c", endChar="n")
</code>```

I tried to extract the data after the String class and then I found that in the same row I have 2 Strings class butI need just the data after the first class

Thanks for help !

答:
Please check if you're perhaps searching for</p>

```<code>df.RefactoringDetail.str.extract(r'lass ([^ ]*)')
</code>```

Body:
this is a part of my dataframe:

RefactoringDetail
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Move Class GameLogic.PlayerHuman moved to blokusgame.mi.android.hazi.blokus.GameLogic.PlayerHuman"

I need just this part:

 blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
 blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
 blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
 GameLogic.PlayerHuman

this is my code :

import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep=';')
refactoring_details = df['RefactoringDetail']
print(refactoring_details)
a=refactoring_details.to_frame(name=None)

And then to extract what i need from the data frame I tried to use substring but it did not work

for elem in a:
  s = substring.substringByChar("elem", startChar="c", endChar="n")

I tried to extract the data after the String class and then I found that in the same row I have 2 Strings class butI need just the data after the first class

Thanks for help !

Body:
Please check if you're perhaps searching for

df.RefactoringDetail.str.extract(r'lass ([^ ]*)')


来源: stackexchange

问:
Trying to solve python problem with binary search
Hey I am trying to solve this python practice question but my solution is not under the given time limit can someone please explain. It will be very helpful of yours because no where I can find this python solution of this question and their they have given solution in Java which is almost same to mine

https://www.hackerearth.com/practice/algorithms/searching/binary-search/practice-problems/algorithm/victory-over-power-4a0cb459/description/

```<code>tasks_count = int(input())

tasks = []

def binarysearch(x):
    arr = tasks
    if arr == [] or x > arr[0]: return 0
    elif x < arr[-1]: return len(arr)
    l  = 0
    r = len(arr)
    while l <= r:
        mid = int((l + r) / 2);
        if arr[mid] == x:
            return mid
        elif arr[mid] > x:
            l = mid - 1
        else:
            r = mid + 1
    return mid

for i in range(0, tasks_count):
    n = input().split(' ')
    if n[0] == '1':
        pos = binarysearch(int(n[1]))
        tasks.insert(pos, int(n[1]))
    elif len(tasks) < 3:
        print('Not enough enemies')
    else:
        print(tasks[(int(len(tasks)/3))])
</code>```

Solution 2:

```<code>tasks_count = int(input())

tasks = []

for i in range(0, tasks_count):
    n = input().split(' ')
    if n[0] == '1':
        tasks.append(int(n[1]))
    elif len(tasks) < 3:
        print('Not enough enemies')
    else:
        tasks.sort(reverse=True)
        print(tasks[int(len(tasks)/3)-1])
</code>```

答:
Solution #2 is mostly on target, but it's got a few issues that needlessly slow it down. For one, the input function is a lot slower than directly reading from sys.stdin; from my brief experiments, it takes about 10x longer to loop over a range and call input than it does to loop over an islice of sys.stdin.

It also performs some rigmarole computing the index converting to float and back to int which could be avoided:

```<code>int(len(tasks)/3)-1
</code>```

could be computed directly as:

```<code>len(tasks) // 3 - 1
</code>```

using the // floor division operator to directly compute an int.

A minor improvement would be to split the lines with str.partition so you don't have to deal with manual indexing (which can be surprisingly slow, not to mention less obvious to read).

A final microoptimization would be to bundle up your work in a function call; CPython variable stores and loads at global scope entail dict operations, while at local scope, they're simple C array lookups that run faster.

Factoring in all of these, you'd end up with code more like:

```<code>import sys

from itertools import islice

def main():

    tasks_count = int(next(sys.stdin))

    tasks = []

    for line in islice(sys.stdin, tasks_count):
        task_type, sep, task_value = line.partition(' ')
        if task_type == '1':
            tasks.append(int(task_value))
        elif len(tasks) < 3:
            print('Not enough enemies')
        else:
            tasks.sort(reverse=True)
            print(tasks[len(tasks) // 3 - 1])

if __name__ == '__main__':  # Standard import guard
    main()  # Call main
</code>```

If they're intentionally forcing frequent sorts, this may still be too slow (because while Python's TimSort tries to handle mostly sorted inputs efficiently, it's still quite a lot of work relative to simple indexing and appending). It's possible you may want to keep it sorted as you go using the bisect module (which implements your binary search for you, but in an extension module that runs much faster), in which case you remove the sort call entirely in favor of keeping it ordered as you insert (replacing O(n log n) work per task #2 with O(n) work per task #1). Conveniently, you don't have to keep it ordered by descending value, as Python allow negative indices, so it's equally easy (if not slightly easier) to compute the required index in the ascending direction:

```<code>import sys
from bisect import insort
from itertools import islice

def main():

    tasks_count = int(next(sys.stdin))

    tasks = []

    for line in islice(sys.stdin, tasks_count):
        task_type, sep, task_value = line.partition(' ')
        if task_type == '1':
            insort(tasks, int(task_value))  # Task 1 more expensive, O(n) instead of O(1)
        elif len(tasks) < 3:
            print('Not enough enemies')
        else:
            print(tasks[-(len(tasks) // 3)])  # Task 2 cheaper; O(1) instead of O(n log n)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hey I am trying to solve this python practice question but my solution is not under the given time limit can someone please explain. It will be very helpful of yours because no where I can find this python solution of this question and their they have given solution in Java which is almost same to mine

https://www.hackerearth.com/practice/algorithms/searching/binary-search/practice-problems/algorithm/victory-over-power-4a0cb459/description/

tasks_count = int(input())

tasks = []

def binarysearch(x):
    arr = tasks
    if arr == [] or x > arr[0]: return 0
    elif x < arr[-1]: return len(arr)
    l  = 0
    r = len(arr)
    while l <= r:
        mid = int((l + r) / 2);
        if arr[mid] == x:
            return mid
        elif arr[mid] > x:
            l = mid - 1
        else:
            r = mid + 1
    return mid

for i in range(0, tasks_count):
    n = input().split(' ')
    if n[0] == '1':
        pos = binarysearch(int(n[1]))
        tasks.insert(pos, int(n[1]))
    elif len(tasks) < 3:
        print('Not enough enemies')
    else:
        print(tasks[(int(len(tasks)/3))])

Solution 2:

tasks_count = int(input())

tasks = []

for i in range(0, tasks_count):
    n = input().split(' ')
    if n[0] == '1':
        tasks.append(int(n[1]))
    elif len(tasks) < 3:
        print('Not enough enemies')
    else:
        tasks.sort(reverse=True)
        print(tasks[int(len(tasks)/3)-1])

Body:
Solution #2 is mostly on target, but it's got a few issues that needlessly slow it down. For one, the input function is a lot slower than directly reading from sys.stdin; from my brief experiments, it takes about 10x longer to loop over a range and call input than it does to loop over an islice of sys.stdin.

It also performs some rigmarole computing the index converting to float and back to int which could be avoided:

int(len(tasks)/3)-1

could be computed directly as:

len(tasks) // 3 - 1

using the // floor division operator to directly compute an int.

A minor improvement would be to split the lines with str.partition so you don't have to deal with manual indexing (which can be surprisingly slow, not to mention less obvious to read).

A final microoptimization would be to bundle up your work in a function call; CPython variable stores and loads at global scope entail dict operations, while at local scope, they're simple C array lookups that run faster.

Factoring in all of these, you'd end up with code more like:

import sys

from itertools import islice

def main():

    tasks_count = int(next(sys.stdin))

    tasks = []

    for line in islice(sys.stdin, tasks_count):
        task_type, sep, task_value = line.partition(' ')
        if task_type == '1':
            tasks.append(int(task_value))
        elif len(tasks) < 3:
            print('Not enough enemies')
        else:
            tasks.sort(reverse=True)
            print(tasks[len(tasks) // 3 - 1])

if __name__ == '__main__':  # Standard import guard
    main()  # Call main

If they're intentionally forcing frequent sorts, this may still be too slow (because while Python's TimSort tries to handle mostly sorted inputs efficiently, it's still quite a lot of work relative to simple indexing and appending). It's possible you may want to keep it sorted as you go using the bisect module (which implements your binary search for you, but in an extension module that runs much faster), in which case you remove the sort call entirely in favor of keeping it ordered as you insert (replacing O(n log n) work per task #2 with O(n) work per task #1). Conveniently, you don't have to keep it ordered by descending value, as Python allow negative indices, so it's equally easy (if not slightly easier) to compute the required index in the ascending direction:

import sys
from bisect import insort
from itertools import islice

def main():

    tasks_count = int(next(sys.stdin))

    tasks = []

    for line in islice(sys.stdin, tasks_count):
        task_type, sep, task_value = line.partition(' ')
        if task_type == '1':
            insort(tasks, int(task_value))  # Task 1 more expensive, O(n) instead of O(1)
        elif len(tasks) < 3:
            print('Not enough enemies')
        else:
            print(tasks[-(len(tasks) // 3)])  # Task 2 cheaper; O(1) instead of O(n log n)


问:
I Need to remove distinct rows from my table
As you can see by the picture all i need to do is to remove all the row who are multiple but leave only one

https://imgur.com/4RUajPQ

答:
You can also create a Row_number() over ( Partition by ID, Name, Temperature, activity,   Order by ID, Name, Temperature, activity, create date desc ). Once the Rw number is created, you can delete the other rows from DELETE TABLE COMMAND

I'm assuming that you want only want one-row per to create date.


问:
How to not allow override description fields of a product for a specific language using webservice?
I try to sync some products between two prestashop websites using webservice. For example the description of a product from the destination website should be the same as the description of the product from source website after synchronization.

Both websites(source and destination) are multi-languages.
Source website has English and French languages, the destination website has English(id=4), French(id=5) and Spanish(id=6) languages.

The problem is that existing description for Spanish language from destination website is overridden with blank text after sync. The same issue is for the other fields: short description, meta description, meta title. Interesting is the text for link_rewrite field is kept for Spanish language.

Here is a part of the XML which is SENT with webservice:

```<code><?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<product>
  <id>8224</id>
  <description>
    <language id="4">English text</language>
    <language id="5">Franch text</language>
  </description>
</product>
</prestashop>
</code>```

I want to keep the existing description from Spanish language even if I don't send the text for it on XML.

答:
The best solution would be to retrieve the existing object, and only update the language you are interested in updating.

Here's an example of updating a product name only in one language

```<code><?php

include(__DIR__.'/config/config.inc.php');
include(__DIR__.'/init.php');
include(__DIR__.'/PSWebServiceLibrary.php');

/* Connect to the PrestaShop Web-service */
define('PS_SHOP_URL', 'http://localhost/prestashop');
define('PS_WS_AUTH_KEY', 'YOURKEYHERE');
$ws = new PrestaShopWebservice(PS_SHOP_URL, PS_WS_AUTH_KEY, false);

/* Retrieve the existing product (Product ID = 1) */
$xml = $ws->get(['url' => PS_SHOP_URL.'/api/products/1']);
echo 'Before: ```';
print_r($xml->product->name->language);
echo '```';

/* Update only the name in French */
$xml->product->name->language[1] = 'New Name';
unset($xml->product->manufacturer_name, $xml->product->quantity, $xml->product->position_in_category); /* Removing fields which are not writeable */
$result = $ws->edit(['resource' => 'products', 'id' => 1, 'putXml' => $xml->asXML()]);

/* Check new values */
$xml = $ws->get(array('url' => PS_SHOP_URL.'/api/products/1'));
echo 'After: ```';
print_r($xml->product->name->language);
echo '```';
</code>```

Result/Output

```<code>Before:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 1
        )

    [0] => Hummingbird printed t-shirt
    [1] => Hummingbird printed t-shirt
)

After:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 1
        )

    [0] => Hummingbird printed t-shirt
    [1] => New Name
)
</code>```

The PSWebServiceLibrary.php file can be downloaded here:
https://github.com/PrestaShop/PrestaShop-webservice-lib/blob/master/PSWebServiceLibrary.php

And you can find more example of using the PrestaShop web-service here:

For PrestaShop 1.6.x: http://doc.prestashop.com/display/PS16/Web+service+one-page+documentation

For PrestaShop 1.7.x: https://devdocs.prestashop.com/1.7/development/webservice/tutorials/prestashop-webservice-lib/

I hope this helps!

Body:
I try to sync some products between two prestashop websites using webservice. For example the description of a product from the destination website should be the same as the description of the product from source website after synchronization.

Both websites(source and destination) are multi-languages.
Source website has English and French languages, the destination website has English(id=4), French(id=5) and Spanish(id=6) languages.

The problem is that existing description for Spanish language from destination website is overridden with blank text after sync. The same issue is for the other fields: short description, meta description, meta title. Interesting is the text for link_rewrite field is kept for Spanish language.

Here is a part of the XML which is SENT with webservice:

<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<product>
  <id>8224</id>
  <description>
    <language id="4">English text</language>
    <language id="5">Franch text</language>
  </description>
</product>
</prestashop>

I want to keep the existing description from Spanish language even if I don't send the text for it on XML.

Body:
The best solution would be to retrieve the existing object, and only update the language you are interested in updating.

Here's an example of updating a product name only in one language

<?php

include(__DIR__.'/config/config.inc.php');
include(__DIR__.'/init.php');
include(__DIR__.'/PSWebServiceLibrary.php');

/* Connect to the PrestaShop Web-service */
define('PS_SHOP_URL', 'http://localhost/prestashop');
define('PS_WS_AUTH_KEY', 'YOURKEYHERE');
$ws = new PrestaShopWebservice(PS_SHOP_URL, PS_WS_AUTH_KEY, false);

/* Retrieve the existing product (Product ID = 1) */
$xml = $ws->get(['url' => PS_SHOP_URL.'/api/products/1']);
echo 'Before: <pre>';
print_r($xml->product->name->language);
echo '</pre>';

/* Update only the name in French */
$xml->product->name->language[1] = 'New Name';
unset($xml->product->manufacturer_name, $xml->product->quantity, $xml->product->position_in_category); /* Removing fields which are not writeable */
$result = $ws->edit(['resource' => 'products', 'id' => 1, 'putXml' => $xml->asXML()]);

/* Check new values */
$xml = $ws->get(array('url' => PS_SHOP_URL.'/api/products/1'));
echo 'After: <pre>';
print_r($xml->product->name->language);
echo '</pre>';

Result/Output

Before:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 1
        )

    [0] => Hummingbird printed t-shirt
    [1] => Hummingbird printed t-shirt
)

After:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 1
        )

    [0] => Hummingbird printed t-shirt
    [1] => New Name
)

The PSWebServiceLibrary.php file can be downloaded here:
https://github.com/PrestaShop/PrestaShop-webservice-lib/blob/master/PSWebServiceLibrary.php

And you can find more example of using the PrestaShop web-service here:

For PrestaShop 1.6.x: http://doc.prestashop.com/display/PS16/Web+service+one-page+documentation

For PrestaShop 1.7.x: https://devdocs.prestashop.com/1.7/development/webservice/tutorials/prestashop-webservice-lib/

I hope this helps!


问:
QML Slider adjusting rectangle
I have a few questions here, as I'm new to qml. I have a simple interface where I want the slider to adjust the size of the Rectangle (which will eventually be an svg icon). Questions below the image:

When adjusting the slider, it properly changes the blue rectangle size, however how can i make it properly auto-resize the green bounding rectangle to encompass it? It should look something like the image below. Currently the thumbnail exceeds the bounds of the green rect. If it helps the combobox can have a static width of 150.

How can i make the blue rectangle always be vertically center aligned? It appears to always be anchored to the top left.

QML

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ColumnLayout {
    anchors.fill: parent

    Flow {
        Layout.fillWidth: true
        spacing: 10

        Repeater {
            model: 5

            Rectangle {
                id: delegateBackground
                width: 200;
                height: contentContainer.height + 10
                border.width: 1
                color: "lightgreen"

                Item {
                    id: contentContainer
                    width: parent.width - 10
                    height: rowContainer.height
                    anchors.centerIn: delegateBackground

                    RowLayout {
                        id: rowContainer
                        width: parent.width

                        Rectangle {
                            id: icon
                            width: thumbnailsize.value
                            height: thumbnailsize.value
                            color: "steelblue"
                            Layout.alignment: Qt.AlignCenter
                        }

                        ComboBox {
                            id: selector
                            Layout.fillWidth: true
                            model: [ "Banana", "Apple", "Coconut" ]
                            Layout.alignment: Qt.AlignCenter
                        }
                    }
                }
            }
        }
    }

    Slider {
        id: thumbnailsize
        from: 16
        value: 48
        to: 64
    }
}
</code>```

答:
Is that what you want:

QML code:

```<code>ColumnLayout {
    anchors.fill: parent

    Flow {
        Layout.fillWidth: true
        spacing: 10

        Repeater {
            model: 5

            Rectangle {
                id: delegateBackground
                width: 200;
                height: contentContainer.height + 10
                border.width: 1
                color: "lightgreen"

                Item {
                    id: contentContainer
                    width: parent.width - 10
                    height: rowContainer.height
                    anchors.centerIn: delegateBackground

                    RowLayout {
                        id: rowContainer
                        anchors.centerIn: contentContainer
                        height: Math.max(iconContainer.height, selector.height)

                        Item{
                            id: iconContainer
                            width: contentContainer.width - selector.width
                            height: parent.height

                            Rectangle {
                                id: icon
                                width: thumbnailsize.value + selector.width > contentContainer.width ? contentContainer.width - selector.width : thumbnailsize.value
                                height: width
                                color: "steelblue"
                                anchors.centerIn: parent
                            }
                        }

                        ComboBox {
                            id: selector
                            Layout.fillWidth: true
                            model: [ "Banana", "Apple", "Coconut" ]
                            Layout.alignment: Qt.AlignCenter
                        }
                    }
                }
            }
        }
    }

    Slider {
        id: thumbnailsize
        from: 16
        value: 48
        to: 64
    }
}
</code>```

Title: QML Slider adjusting rectangle

Body:
I have a few questions here, as I'm new to qml. I have a simple interface where I want the slider to adjust the size of the Rectangle (which will eventually be an svg icon). Questions below the image:

When adjusting the slider, it properly changes the blue rectangle size, however how can i make it properly auto-resize the green bounding rectangle to encompass it? It should look something like the image below. Currently the thumbnail exceeds the bounds of the green rect. If it helps the combobox can have a static width of 150.

How can i make the blue rectangle always be vertically center aligned? It appears to always be anchored to the top left.

QML

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ColumnLayout {
    anchors.fill: parent

    Flow {
        Layout.fillWidth: true
        spacing: 10

        Repeater {
            model: 5

            Rectangle {
                id: delegateBackground
                width: 200;
                height: contentContainer.height + 10
                border.width: 1
                color: "lightgreen"

                Item {
                    id: contentContainer
                    width: parent.width - 10
                    height: rowContainer.height
                    anchors.centerIn: delegateBackground

                    RowLayout {
                        id: rowContainer
                        width: parent.width

                        Rectangle {
                            id: icon
                            width: thumbnailsize.value
                            height: thumbnailsize.value
                            color: "steelblue"
                            Layout.alignment: Qt.AlignCenter
                        }

                        ComboBox {
                            id: selector
                            Layout.fillWidth: true
                            model: [ "Banana", "Apple", "Coconut" ]
                            Layout.alignment: Qt.AlignCenter
                        }
                    }
                }
            }
        }
    }

    Slider {
        id: thumbnailsize
        from: 16
        value: 48
        to: 64
    }
}

Body:
Is that what you want:

QML code:

ColumnLayout {
    anchors.fill: parent

    Flow {
        Layout.fillWidth: true
        spacing: 10

        Repeater {
            model: 5

            Rectangle {
                id: delegateBackground
                width: 200;
                height: contentContainer.height + 10
                border.width: 1
                color: "lightgreen"

                Item {
                    id: contentContainer
                    width: parent.width - 10
                    height: rowContainer.height
                    anchors.centerIn: delegateBackground

                    RowLayout {
                        id: rowContainer
                        anchors.centerIn: contentContainer
                        height: Math.max(iconContainer.height, selector.height)

                        Item{
                            id: iconContainer
                            width: contentContainer.width - selector.width
                            height: parent.height

                            Rectangle {
                                id: icon
                                width: thumbnailsize.value + selector.width > contentContainer.width ? contentContainer.width - selector.width : thumbnailsize.value
                                height: width
                                color: "steelblue"
                                anchors.centerIn: parent
                            }
                        }

                        ComboBox {
                            id: selector
                            Layout.fillWidth: true
                            model: [ "Banana", "Apple", "Coconut" ]
                            Layout.alignment: Qt.AlignCenter
                        }
                    }
                }
            }
        }
    }

    Slider {
        id: thumbnailsize
        from: 16
        value: 48
        to: 64
    }
}


问:
Android Studio: uploading user data after email validation using firebase
I want to upload some user info via firebase libraries in Android Studio. The problem I have is that I am not sure how to glue together the functions so that it works.

So far I have the email validation function and also the upload user data function, but when I hit the register button, the email verification is sent and it works(the user is registered, but the user data is not uploaded to the firebase data base.

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity {

    private EditText userName, userPassword, userEmail, phoneNumber;
    private Button logButton, regButton;
    private FirebaseAuth firebaseAuth;
    String email, name, phone, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        setupUIViews();

        firebaseAuth = FirebaseAuth.getInstance();

        regButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(validate()){
                    //upload everithing to the database
                    String user_name = userName.getText().toString().trim();
                    String user_email = userEmail.getText().toString().trim();
                    String user_password = userPassword.getText().toString().trim();
                    String user_phone = phoneNumber.getText().toString().trim();

                    firebaseAuth.createUserWithEmailAndPassword(userEmail.getText().toString().trim(), userPassword.getText().toString().trim()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(task.isSuccessful()) {
                               sendEmailVerification();
                            }
                            else{
                                Toast.makeText(RegisterActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
            }
        });
        logButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
            }
        });
    }

    private void setupUIViews(){
        userName = (EditText)findViewById(R.id.etUser2);
        userPassword = (EditText)findViewById(R.id.etPas2);
        userEmail = (EditText)findViewById(R.id.etEmail2);
        phoneNumber = (EditText)findViewById(R.id.etPhone1);
        regButton = (Button)findViewById(R.id.registerButton2);
        logButton = (Button)findViewById(R.id.loginButton2);

    }

    private Boolean validate(){
        Boolean result = false;

         name = userName.getText().toString().trim();
         email = userEmail.getText().toString().trim();
         phone = phoneNumber.getText().toString().trim();
         password = userPassword.getText().toString().trim();

        if(name.isEmpty() || password.isEmpty() || email.isEmpty()){
           Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT).show();
        }
        else{
            result = true;
        }
        return result;
    }

    private void sendEmailVerification(){
        final FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();

        if(firebaseUser != null){
            firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        sendUserData();
                        Toast.makeText(RegisterActivity.this, "Sucessfully registered", Toast.LENGTH_SHORT).show();
                        firebaseAuth.signOut();
                        finish();
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    }
                    else{
                        Toast.makeText(RegisterActivity.this, "Verification email was not sent", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void sendUserData(){
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
        UserProfile userProfile = new UserProfile(name, email, phone);
        myRef.child(firebaseAuth.getUid()).setValue(userProfile);
    }
}
```

<p>and also the UserProfile class:</p>

<pre class="lang-java prettyprint-override"><code>package com.example.myapplication;

public class UserProfile {
    public String userName;
    public String userEmail;
    public String userPhone;

    public UserProfile(String userName, String userEmail, String userPhone) {
        this.userName = userName;
        this.userEmail = userEmail;
        this.userPhone = userPhone;
    }
}

</code>```

So in conclusion I want to have the user data into the database while also having the email validation.
Thanks in advance!

答:
Add a listener for the setValue() method and call signOut() when the data is written successfully.

```<code>private void sendUserData(){
    FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
    UserProfile userProfile = new UserProfile(name, email, phone);
    myRef.child(firebaseAuth.getUid()).setValue(userProfile).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            firebaseAuth.signOut();
        }
    });
}
</code>```

Hope this will fix the issue. BTW your code seems to have many duplications such as reading the inputs from the textviews many times.

Body:
I want to upload some user info via firebase libraries in Android Studio. The problem I have is that I am not sure how to glue together the functions so that it works.

So far I have the email validation function and also the upload user data function, but when I hit the register button, the email verification is sent and it works(the user is registered, but the user data is not uploaded to the firebase data base.

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity {

    private EditText userName, userPassword, userEmail, phoneNumber;
    private Button logButton, regButton;
    private FirebaseAuth firebaseAuth;
    String email, name, phone, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        setupUIViews();

        firebaseAuth = FirebaseAuth.getInstance();

        regButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(validate()){
                    //upload everithing to the database
                    String user_name = userName.getText().toString().trim();
                    String user_email = userEmail.getText().toString().trim();
                    String user_password = userPassword.getText().toString().trim();
                    String user_phone = phoneNumber.getText().toString().trim();

                    firebaseAuth.createUserWithEmailAndPassword(userEmail.getText().toString().trim(), userPassword.getText().toString().trim()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(task.isSuccessful()) {
                               sendEmailVerification();
                            }
                            else{
                                Toast.makeText(RegisterActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
            }
        });
        logButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
            }
        });
    }

    private void setupUIViews(){
        userName = (EditText)findViewById(R.id.etUser2);
        userPassword = (EditText)findViewById(R.id.etPas2);
        userEmail = (EditText)findViewById(R.id.etEmail2);
        phoneNumber = (EditText)findViewById(R.id.etPhone1);
        regButton = (Button)findViewById(R.id.registerButton2);
        logButton = (Button)findViewById(R.id.loginButton2);

    }

    private Boolean validate(){
        Boolean result = false;

         name = userName.getText().toString().trim();
         email = userEmail.getText().toString().trim();
         phone = phoneNumber.getText().toString().trim();
         password = userPassword.getText().toString().trim();

        if(name.isEmpty() || password.isEmpty() || email.isEmpty()){
           Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT).show();
        }
        else{
            result = true;
        }
        return result;
    }

    private void sendEmailVerification(){
        final FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();

        if(firebaseUser != null){
            firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        sendUserData();
                        Toast.makeText(RegisterActivity.this, "Sucessfully registered", Toast.LENGTH_SHORT).show();
                        firebaseAuth.signOut();
                        finish();
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    }
                    else{
                        Toast.makeText(RegisterActivity.this, "Verification email was not sent", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void sendUserData(){
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
        UserProfile userProfile = new UserProfile(name, email, phone);
        myRef.child(firebaseAuth.getUid()).setValue(userProfile);
    }
}

and also the UserProfile class:

package com.example.myapplication;

public class UserProfile {
    public String userName;
    public String userEmail;
    public String userPhone;

    public UserProfile(String userName, String userEmail, String userPhone) {
        this.userName = userName;
        this.userEmail = userEmail;
        this.userPhone = userPhone;
    }
}

So in conclusion I want to have the user data into the database while also having the email validation.
Thanks in advance!

Body:
Add a listener for the setValue() method and call signOut() when the data is written successfully.

private void sendUserData(){
    FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
    UserProfile userProfile = new UserProfile(name, email, phone);
    myRef.child(firebaseAuth.getUid()).setValue(userProfile).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            firebaseAuth.signOut();
        }
    });
}

Hope this will fix the issue. BTW your code seems to have many duplications such as reading the inputs from the textviews many times.


问:
os.path.abspath is not producing the absolute path for the directory python
its a simple program which outputs the full file path using a given path that does not include the root. But It just prints out the given path. why?

operating system Ubutu18.04 Lts, IDE Pycharm , python 3.7
I've tried installing pathlib and path.py but it still does not work.

```<code>from os.path import abspath, relpath

x = '/python/100 exercises/24.py'

print(abspath(x))
</code>```

The expected output is

```<code>/home/tasif/Documents/python/100 exercises/24.py
</code>```

actual result is

```<code>/python/100 exercises/24.py
</code>```

答:
I think this is true but I could be corrected: You need to run it as os.path.abspath(x) otherwise the script does not know where to get that function from and is doing nothing but printing your string with a non-function ran on it.

You should also rename your directory to 100_exercises/ or something more posix friendly.

Body:
its a simple program which outputs the full file path using a given path that does not include the root. But It just prints out the given path. why?

operating system Ubutu18.04 Lts, IDE Pycharm , python 3.7
I've tried installing pathlib and path.py but it still does not work.

from os.path import abspath, relpath

x = '/python/100 exercises/24.py'

print(abspath(x))

The expected output is

/home/tasif/Documents/python/100 exercises/24.py

actual result is

/python/100 exercises/24.py


问:
How to do na_values when creating pandas dataframe from Google BigQuery
I had used pd.read_csv(my_csv, na_values=['N/A', '--']) such that string 'N/A' and '--' get interpreted as NULL, NaN, etc.

But if I used BigQuery client, I couldn't figure how to achieve the same feat. I read the quick help from .to_dataframe() which "Return a pandas DataFrame from a QueryJob" but it didn't seem to take in any extra argument.

Is this possible? Or I have to do my own custom post-processing to track missing values?

答:
you can achieve same from below:</p>

```<code>dataFrame.applymap(lambda x: np.nan if x in ['N/A', '--'] else x)
</code>```

Body:
you can achieve same from below:

dataFrame.applymap(lambda x: np.nan if x in ['N/A', '--'] else x)


问:
C# Finding specific values from messageformat strings
Given a messageformat string such as str below. I want to be able to get the "notifications" & "name" values which are used to display the text values.

```<code>var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";
</code>```

I have tried using a regex such as:

```<code>var matches = Regex.Matches(str, @"{(.*?)}");
//var matches = Regex.Matches(str, @"(?<=\{)[^}{]*(?=\})");
var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();
</code>```

But the above does not take in to account that {notifications,.. is itself wraped in curly braces and includes the inner values that are not needed, which are wrapped in curly braces also.

So in brief I just want to be able to parse a string such as str above and get notifications & name at the returned values.

A string such as var str2 = @"Hello {name}" should just return name as the value.

EDIT

The values notifications & name will not be known in advance - I have just used this as an example, for the values I require to return from the string.

答:
TL;DR: Here is an optional solution

```<code>var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

// get matches skipping nested curly braces
var matches =
    Regex.Matches(str, @"{((?:[^{}]|(?<counter>{)|(?<-counter>}))+(?(counter)(?!)))}");

var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct()
    .Select(v => Regex.Match(v, @"^\w+").Value) // take 1st word
    .ToList();
</code>```

which results in (copied from Visual Studio Locals window while debugging)

results Count = 2   System.Collections.Generic.List<string>
    [0] "notifications"
    [1] "name"
```

<p>... original answer follows ...</p>

<hr>

<p>One thing to note about the current solution in the original question:</p>

<ul>
<li>the use of <code>.</code> doesn't match line breaks, so that's one reason why it currently matches the nested values (see this source)</li>
</ul>

<h3>If I understand your goal, this article is a nice explanation and demonstration of a related problem and solution:</h3>

<p>(this article addresses the main challenge noted in the original question--the <strong>nested curly braces</strong>)</p>

<p>https://blogs.msdn.microsoft.com/timart/2013/05/14/nestedrecursive-regex-and-net-balancing-groups-detect-a-function-with-a-regex/</p>

<h3>From that article, I'd suggest the below pattern as an optional solution:</h3>

```var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

// get matches skipping nested curly braces
var matches =
    Regex.Matches(str, @"{((?:[^{}]|(?<counter>{)|(?<-counter>}))+(?(counter)(?!)))}");
var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();
```

<p><strong>which results in</strong> (copied from Visual Studio Locals window while debugging)</p>

<pre class="lang-none prettyprint-override"><code>results Count = 2   System.Collections.Generic.List<string>
    [0] "notifications, plural,\r\n          zero {no notifications}\r\n           one {one notification}\r\n           =42 {a universal amount of notifications}\r\n         other {# notifications}\r\n        "
    [1] "name"
</code>```

(or if you were to print these results to the console):

// Result 0 would look like:
notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}

// Result 1 would look like:
name
```

<hr>

<h1>Update</h1>

<p>I came back to this and realized that the question asked for just the single words as results.</p>

<h3>Then take the first word from each result</h3>

<p>(I'm repeating the above snippet with the additional select statement to show the full solution)</p>

```var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

// get matches skipping nested curly braces
var matches =
    Regex.Matches(str, @"{((?:[^{}]|(?<counter>{)|(?<-counter>}))+(?(counter)(?!)))}");

var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct()
    .Select(v => Regex.Match(v, @"^\w+").Value) // take 1st word
    .ToList();
```

<p><strong>which results in</strong> (copied from Visual Studio Locals window while debugging)</p>

<pre class="lang-none prettyprint-override"><code>results Count = 2   System.Collections.Generic.List<string>
    [0] "notifications"
    [1] "name"
</code>```

A little more information

(I just found this interesting and spent a little more time researching/learning and thought it worth including some more related information)

Conversations here and here include some opinions for and against using regex for this type of problem.

I think it's interesting to read these opinions and get a more well-rounded point of view

Regardless of the above opinions, .NET creators deemed it appropriate to implement balancing group definitions--a functionality this answer uses:

from Microsoft: balancing group definitions

related source: Matching Nested Constructs with Balancing Groups

Body:
Given a messageformat string such as str below. I want to be able to get the "notifications" & "name" values which are used to display the text values.

var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

I have tried using a regex such as:

var matches = Regex.Matches(str, @"{(.*?)}");
//var matches = Regex.Matches(str, @"(?<=\{)[^}{]*(?=\})");
var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();

But the above does not take in to account that {notifications,.. is itself wraped in curly braces and includes the inner values that are not needed, which are wrapped in curly braces also.

So in brief I just want to be able to parse a string such as str above and get notifications & name at the returned values.

A string such as var str2 = @"Hello {name}" should just return name as the value.

EDIT

The values notifications & name will not be known in advance - I have just used this as an example, for the values I require to return from the string.

Body:
TL;DR: Here is an optional solution

var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

// get matches skipping nested curly braces
var matches =
    Regex.Matches(str, @"{((?:[^{}]|(?<counter>{)|(?<-counter>}))+(?(counter)(?!)))}");

var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct()
    .Select(v => Regex.Match(v, @"^\w+").Value) // take 1st word
    .ToList();

which results in (copied from Visual Studio Locals window while debugging)

results Count = 2   System.Collections.Generic.List<string>
    [0] "notifications"
    [1] "name"

... original answer follows ...

One thing to note about the current solution in the original question:

the use of . doesn't match line breaks, so that's one reason why it currently matches the nested values (see this source)

If I understand your goal, this article is a nice explanation and demonstration of a related problem and solution:

(this article addresses the main challenge noted in the original question--the nested curly braces)

https://blogs.msdn.microsoft.com/timart/2013/05/14/nestedrecursive-regex-and-net-balancing-groups-detect-a-function-with-a-regex/

From that article, I'd suggest the below pattern as an optional solution:

var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

// get matches skipping nested curly braces
var matches =
    Regex.Matches(str, @"{((?:[^{}]|(?<counter>{)|(?<-counter>}))+(?(counter)(?!)))}");
var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();

which results in (copied from Visual Studio Locals window while debugging)

results Count = 2   System.Collections.Generic.List<string>
    [0] "notifications, plural,\r\n          zero {no notifications}\r\n           one {one notification}\r\n           =42 {a universal amount of notifications}\r\n         other {# notifications}\r\n        "
    [1] "name"

(or if you were to print these results to the console):

// Result 0 would look like:
notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}

// Result 1 would look like:
name

Update

I came back to this and realized that the question asked for just the single words as results.

Then take the first word from each result

(I'm repeating the above snippet with the additional select statement to show the full solution)

var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

// get matches skipping nested curly braces
var matches =
    Regex.Matches(str, @"{((?:[^{}]|(?<counter>{)|(?<-counter>}))+(?(counter)(?!)))}");

var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct()
    .Select(v => Regex.Match(v, @"^\w+").Value) // take 1st word
    .ToList();

which results in (copied from Visual Studio Locals window while debugging)

results Count = 2   System.Collections.Generic.List<string>
    [0] "notifications"
    [1] "name"

A little more information

(I just found this interesting and spent a little more time researching/learning and thought it worth including some more related information)

Conversations here and here include some opinions for and against using regex for this type of problem.

I think it's interesting to read these opinions and get a more well-rounded point of view

Regardless of the above opinions, .NET creators deemed it appropriate to implement balancing group definitions--a functionality this answer uses:

from Microsoft: balancing group definitions

related source: Matching Nested Constructs with Balancing Groups


问:
Xcode/Swift - Cannot resolve memory issues with Instruments
My application has memory issues where after a certain threshold, the application will crash.

I've been instructed to use Instruments and select the Allocation option.

However, I can never seem to get a "direct" answer to my issue, I have attached screenshots below to help describe the issue better.

The memory issues are not linked to any ViewControllers or files that I have created. Rather other libraries/frameworks which I had no idea were being used. I have been battling this issue for a few weeks, I have altered my code/implemented a variety of methods which I believed may have resolved the issue. However, no luck.

Could someone please tell me how I can combat this issue? As I cannot seem to force the memory to be released which in turn means I have this giant memory bug within my application.

Thank you.

Edit - Added a screenshot of the memory usage when viewing an image at full resolution and returning to the home screen.

答:
I fixed the issues which I had. Just in case anyone in future experiences the same issues this is what I did:

If declared my outlets/delegates as weak

Wherever I used the keyword self in a block where XCode demanded I use self,  I added either [weak self] in or [unowned self] in

Remove any instances of the word self which were not required

Added a deinit and included a print statement

Added a breakpoint where the deinit method is called

Commented out functions in my viewDidLoad method and go through each one to see which one/if one caused the issue.


问:
How to import the `∃-syntax`?
```<code>open import Data.Product using (_×_; ∃; ∃-syntax)
open import Data.List

Any-∃ : ∀ {A : Set} {P : A → Set} {xs : List A} → ∃[ x ∈ xs ] P x
</code>```

```<code>Could not parse the application ∃[ x ∈ xs ] P x
Operators used in the grammar:
  ∃[_] (prefix notation, level 20) [∃-syntax (C:\Users\Marko\AppData\Roaming\cabal\x86_64-windows-ghc-8.6.5\Agda-2.6.0\lib\agda-stdlib\src\Data\Product.agda:78,1-9)]
when scope checking ∃[ x ∈ xs ] P x
</code>```

For some reason it seems like it is not importing the precedence properly from the standard library module. Defining it as...

```<code>Any-∃ : ∀ {A : Set} {P : A → Set} {xs : List A} → ∃[ x ] P x
</code>```

...will make it pass parsing, but I am not sure this is doing the right thing for one of the problems I am trying to solve.

What should I do here?

答:
∃ is precisely for the cases where you can leave out the domain of the function
because it's evident. Otherwise you are supposed to use Σ. And indeed Σ-syntax
does give you the ability to write Σ[ x ∈ A ] B.

Title: How to import the `∃-syntax`?

Body:
open import Data.Product using (_×_; ∃; ∃-syntax)
open import Data.List

Any-∃ : ∀ {A : Set} {P : A → Set} {xs : List A} → ∃[ x ∈ xs ] P x

Could not parse the application ∃[ x ∈ xs ] P x
Operators used in the grammar:
  ∃[_] (prefix notation, level 20) [∃-syntax (C:\Users\Marko\AppData\Roaming\cabal\x86_64-windows-ghc-8.6.5\Agda-2.6.0\lib\agda-stdlib\src\Data\Product.agda:78,1-9)]
when scope checking ∃[ x ∈ xs ] P x

For some reason it seems like it is not importing the precedence properly from the standard library module. Defining it as...

Any-∃ : ∀ {A : Set} {P : A → Set} {xs : List A} → ∃[ x ] P x

...will make it pass parsing, but I am not sure this is doing the right thing for one of the problems I am trying to solve.

What should I do here?


问:
Objective-C release is not called explicitly
```<code>NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];
</code>```

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly

答:
There is no need to delete the memory block, this will use up an unneeded cycle.
The memory will be overridden when an new object is allocated an occupy that memory block. </p>

ContentLicense: CC BY-SA 3.0

Body:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly


问:
How to randomly fill the rows of the matrix?
I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.</p>

```<code>let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"
</code>```

答:
You can do that in following steps:

First create a function which takes two parameters rows and cols

Then create a helper function shuffleArray which takes an array as argument and return a new array which is shuffled.

In the main function create an array of number for the no of cols. In the case it will be [1,2,3,4,5]. You can do that using map()

Then create an array of undefined of length equal to the given rows.

Use map() on that and return a new shuffled array that we created before([1,2,3,4,5])

function shuffleArray(arr){
  //create a copy of the array
  arr = arr.slice();
  //create an array on which random items from 'arr' will be added
  let res = [];
  //create while loop which will run until all the elements from arr are removed
  while(arr.length){
    //generate a random index in range of length of 'arr'
    let i = Math.floor(arr.length * Math.random())
    //push element at that index to result array
    res.push(arr[i]);
    //remove that element from the orignal array i.e 'arr'
    arr.splice(i,1);
  }

  return res;
}

function randMatrix(rows,cols){
  //create an array which will shuffled again and again.
  let genArr = [...Array(cols)].map((x,i) => i + 1);

  return [...Array(rows)] // create an array of undefined of length equal to rows
           .map(x => shuffleArray(genArr)) // change that each to another shuffled array.
}

console.log(randMatrix(3,5).join('\n'))```

Body:
I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.

let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"


问:
Why I cannot deploy my UWP service to my PC?
I learn UWP programming on my Windows 10 PC. And I learn this example step by step.
https://learn.microsoft.com/en-us/windows/uwp/launch-resume/how-to-create-and-consume-an-app-service

But finally I find that I cannot deploy the "MyAppService" project like this. Why?

答: An appservice by itself is not a deployable project, it's just a WinRT component. It needs to be referenced by an application and will then be deployed automatically along with that application.</p>


问:
How encrypt SQLite database with FireDAC?
I'm create SQLite databse with DB Browser for SQLite (non encrypted) and open with FireDAC in delphi.(Can retrive data Eg. Select * from abc).

How encrypt this SQLite database with FireDAC? When enter username, password and encrypt get message  "Cipher DB is not encrypdet"

Note:

When create SQLite database from Delphi FireDac I can use encryption!

答:
Recent Delphi versions come with an example project for working with encryption on Sqlite databases, see this documentation.  I have not used this myself, btw.

It includes this section

```<code>Encrypt DB
    Encrypt: Encrypts the database according to the Encryption mode and the password provided.

The sampe uses TFDSQLiteSecurity.SetPassword to encrypt the database with the password provided.

The database password is the combination of <encryption algorythm>:<password>.
</code>```

Body:
Recent Delphi versions come with an example project for working with encryption on Sqlite databases, see this documentation.  I have not used this myself, btw.

It includes this section

Encrypt DB
    Encrypt: Encrypts the database according to the Encryption mode and the password provided.

The sampe uses TFDSQLiteSecurity.SetPassword to encrypt the database with the password provided.

The database password is the combination of <encryption algorythm>:<password>.


问:
Change display of field.value on a per field basis?
I'm using reusable form templates to manually render form fields and I want to display the values of the form fields in a specific way.

I'm looping over the fields in the form and filtering field.value  based on the field name which feels sloppy. I feel like I should be able to tie how a field's value displays to the field itself, not on conditional logic within the loop.

I've already tried making my fields Select widgets with explicit choices, but that has no effect on field.value, and that's what I want to display differently.

Here's what I'm currently doing:

{% if field.name == 'sending_domain' %}
   {{ field.value | default:"[ANY DOMAIN]" }}
{% elif field.name == 'from_email' %}
   {{ field.value | default:"Not set. Required!"  }}
{% elif field.name == 'custom_api_key' %}
   {{ field.value | default:"Required custom API key not set."  }}
{% elif field.name == 'custom_subaccount' %}
   {{ field.value | default:"Not set."  }}
{% else %}
   {{ field.value | default:"None" }}
{% endif %}
```

That code works - Sending Domain displays "[ANY DOMAIN]" by default, From Email displays "Not set. Required!" by default, etc -  but it also hurts my soul. What's a better way of doing this?

答:
Normally a switch statement would be the more elegant solution. But to my understanding, python does not have switch statements.
Article

I have a similar set of code in my latest project.

Possible option

Body:
I'm using reusable form templates to manually render form fields and I want to display the values of the form fields in a specific way.

I'm looping over the fields in the form and filtering field.value  based on the field name which feels sloppy. I feel like I should be able to tie how a field's value displays to the field itself, not on conditional logic within the loop.

I've already tried making my fields Select widgets with explicit choices, but that has no effect on field.value, and that's what I want to display differently.

Here's what I'm currently doing:

{% if field.name == 'sending_domain' %}
   {{ field.value | default:"[ANY DOMAIN]" }}
{% elif field.name == 'from_email' %}
   {{ field.value | default:"Not set. Required!"  }}
{% elif field.name == 'custom_api_key' %}
   {{ field.value | default:"Required custom API key not set."  }}
{% elif field.name == 'custom_subaccount' %}
   {{ field.value | default:"Not set."  }}
{% else %}
   {{ field.value | default:"None" }}
{% endif %}

That code works - Sending Domain displays "[ANY DOMAIN]" by default, From Email displays "Not set. Required!" by default, etc -  but it also hurts my soul. What's a better way of doing this?


问:
C# CSV Filehelpers compare two rows in the same file, add and remove rows
I want to write a simple program to ease my life at work, but I'm not too familiar with C# so I'm trying to read the documentation and some examples, but I don't find the documentation too good, and can't find any examples to feed off.

I have a CSV file (wireless temperature sensor that sometimes loses connection or sends multiple readouts in quick succession) and I want to compare two DateTimes (TimeSpan) from 2 subsequent rows, and depending on result remove that row, or add another in between these. If TimeSpan between 2 DateTimes is less than 10 minutes, delete that row. If it's longer than 10 minutes create a new row with time that is 10 minutes after the first one. All readouts are between themselves in multiples of 10 minutes.

Example file:

```<code>[DelimitedRecord(","), IgnoreFirst(1)]
public class CSVDataFields{
  [FieldQuoted('"')] [FieldConverter(ConverterKind.Date, "MM/dd/yyyy h:mm tt")]
  public DateTime Date;
  [FieldQuoted('"')]
  public float Value;
}

"Date","Value"
"03/19/2019 3:10 PM","20.5"
"03/19/2019 3:10 PM","20.5"
"03/19/2019 3:10 PM","20.4"
"03/19/2019 3:20 PM","20.2"
"03/19/2019 3:50 PM","20.0"
"03/19/2019 4:00 PM","19.8"
</code>```

So the first check is [0] and [1], it's less than 10, so delete that row, [0] and [2] less than 10 - delete, [0] and [3] it's ok,

[3] and [4] is longer than 10 minutes, create a new row with time([3] + 10) and value average (20.2, 20.0),

new [4] and [5] is longer than 10 minutes, create a new row with time ([4] + 10) and value average (20.1, 20.0), and so on.

In the example on FileHelpers.net there is only this example. Here you can only access 1 row at a time I think, while I need to have access to 2 rows at the same time.

```<code>private void DetectDupes(ref CSVDataFields[] csv){
  foreach(CSVDataFields csvData in csv){

  }
}
</code>```

I've also not gotten that far as how to save the new file with the modified rows.

答:
You can accomplish this with Linq's Aggregate method:

```<code>var engine = new FileHelperEngine<CSVDataFields>();

var result = engine.ReadFile(@"c:\temp\some_source_file.txt");

List<CSVDataFields> newRows = new List<CSVDataFields>();
newRows.Add(result.First());

result.Aggregate((a, b) =>
{
    var diff = Math.Abs((a.Date - b.Date).Minutes);
    if (diff < 10)
    {
        return a;
    }
    else if (diff == 10)
    {
        newRows.Add(b);
        return b;
    }
    else
    {
        var newRow = new CSVDataFields()
        {
            Date = a.Date.AddMinutes(10),
            Value = (a.Value + b.Value) / 2
        };
        newRows.Add(newRow);
        return newRow;
    }
});

engine.WriteFile(@"C:\temp\destination_file_deduped.txt", newRows);
</code>```

Output:

03/19/2019 3:10 PM, 20.5

03/19/2019 3:20 PM, 20.2

03/19/2019 3:30 PM, 20.1

03/19/2019 3:40 PM, 19.95

Explanation:
The Aggregate method iterates through an enumerable, executing a function delegate which takes as parameters the current value (a) and the next value (b) for each item in the enumerable. On each iteration, it decides if it should skip the new item b (diff < 10), add it to dedupped list (diff==10) or merge it (diff > 10). The key thing to understand here is that b is always the next item in the enumerable and the value that is returned from the current iteration becomes the current value (a) of the next iteration. In other words, a represents the result of the execution of the function for each iteration.

It's generally not a good idea to overwrite the source file (unless you have it backed up somewhere) so I am outputting to a new file but you can change that if you have to.

Also, this is a simplistic example. Make sure to account for situations like the file having no rows and what not.

Body:
I want to write a simple program to ease my life at work, but I'm not too familiar with C# so I'm trying to read the documentation and some examples, but I don't find the documentation too good, and can't find any examples to feed off.

I have a CSV file (wireless temperature sensor that sometimes loses connection or sends multiple readouts in quick succession) and I want to compare two DateTimes (TimeSpan) from 2 subsequent rows, and depending on result remove that row, or add another in between these. If TimeSpan between 2 DateTimes is less than 10 minutes, delete that row. If it's longer than 10 minutes create a new row with time that is 10 minutes after the first one. All readouts are between themselves in multiples of 10 minutes.

Example file:

[DelimitedRecord(","), IgnoreFirst(1)]
public class CSVDataFields{
  [FieldQuoted('"')] [FieldConverter(ConverterKind.Date, "MM/dd/yyyy h:mm tt")]
  public DateTime Date;
  [FieldQuoted('"')]
  public float Value;
}

"Date","Value"
"03/19/2019 3:10 PM","20.5"
"03/19/2019 3:10 PM","20.5"
"03/19/2019 3:10 PM","20.4"
"03/19/2019 3:20 PM","20.2"
"03/19/2019 3:50 PM","20.0"
"03/19/2019 4:00 PM","19.8"

So the first check is [0] and [1], it's less than 10, so delete that row, [0] and [2] less than 10 - delete, [0] and [3] it's ok,

[3] and [4] is longer than 10 minutes, create a new row with time([3] + 10) and value average (20.2, 20.0),

new [4] and [5] is longer than 10 minutes, create a new row with time ([4] + 10) and value average (20.1, 20.0), and so on.

In the example on FileHelpers.net there is only this example. Here you can only access 1 row at a time I think, while I need to have access to 2 rows at the same time.

private void DetectDupes(ref CSVDataFields[] csv){
  foreach(CSVDataFields csvData in csv){

  }
}

I've also not gotten that far as how to save the new file with the modified rows.

Body:
You can accomplish this with Linq's Aggregate method:

var engine = new FileHelperEngine<CSVDataFields>();

var result = engine.ReadFile(@"c:\temp\some_source_file.txt");

List<CSVDataFields> newRows = new List<CSVDataFields>();
newRows.Add(result.First());

result.Aggregate((a, b) =>
{
    var diff = Math.Abs((a.Date - b.Date).Minutes);
    if (diff < 10)
    {
        return a;
    }
    else if (diff == 10)
    {
        newRows.Add(b);
        return b;
    }
    else
    {
        var newRow = new CSVDataFields()
        {
            Date = a.Date.AddMinutes(10),
            Value = (a.Value + b.Value) / 2
        };
        newRows.Add(newRow);
        return newRow;
    }
});

engine.WriteFile(@"C:\temp\destination_file_deduped.txt", newRows);

Output:

03/19/2019 3:10 PM, 20.5

03/19/2019 3:20 PM, 20.2

03/19/2019 3:30 PM, 20.1

03/19/2019 3:40 PM, 19.95

Explanation:
The Aggregate method iterates through an enumerable, executing a function delegate which takes as parameters the current value (a) and the next value (b) for each item in the enumerable. On each iteration, it decides if it should skip the new item b (diff < 10), add it to dedupped list (diff==10) or merge it (diff > 10). The key thing to understand here is that b is always the next item in the enumerable and the value that is returned from the current iteration becomes the current value (a) of the next iteration. In other words, a represents the result of the execution of the function for each iteration.

It's generally not a good idea to overwrite the source file (unless you have it backed up somewhere) so I am outputting to a new file but you can change that if you have to.

Also, this is a simplistic example. Make sure to account for situations like the file having no rows and what not.


问:
Crashlytics crash report mentions XposedBridge
I released an update to an Android app yesterday, and today I am seeing a few crash logs in Crashlytics:

```<code>   Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MyWebViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
          at android.app.ActivityThread.-wrap12(ActivityThread.java)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:154)
          at android.app.ActivityThread.main(ActivityThread.java:6119)
          at java.lang.reflect.Method.invoke(Method.java)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
          at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)

   Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
          at com.example.myapp.MyWebViewActivity.onCreate(MyWebViewActivity.java:77)
          at android.app.Activity.performCreate(Activity.java:6679)
          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
          at android.app.ActivityThread.-wrap12(ActivityThread.java)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:154)
          at android.app.ActivityThread.main(ActivityThread.java:6119)
          at java.lang.reflect.Method.invoke(Method.java)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
          at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)
</code>```

At the bottom this report mentions XposedBridge, which I find kind of odd. Is this caused by someone experimenting with my app using the Xposed framework? Or could this happen to a "normal user"? Crashlytics says the issue has affected 3 users so far, but I'm skeptical since they all have the exact same phone model and Android version (Motorola Nexus 6, Android 7.1.1) and happened within 10 minutes of each other.

The NPE is caused by getIntent().getStringExtra("some_string").equals("another_string") in an onCreate method, even though I am setting the "some_string" in all places where I'm creating this activity.

So what I'm wondering is if this sort of crash could be the result of anything other than a user who is experimenting with Xposed? I.e. should I take it seriously or not?

答:
In general having the XposedBridge in the stack trace just means that the app runs on an device with XPosed installed. XPosed changes the Dalvik VM system wide, even if your app isn't modified by any XPosed module.

I don't have much experience with Crashlytics, however the "3 users" I would interpret as one user having cleared the app data two times.

Anyway I would always use safe coding, therefore your call

```<code>getIntent().getStringExtra("some_string").equals("another_string")
</code>```

should be reformulated to:

```<code>"another_string".equals(getIntent().getStringExtra("some_string"))
</code>```

This way is may be a bit unfamiliar to read, but it is safe against NullPointerException in case the current Intent does not has the "some_string" value.

Body:
I released an update to an Android app yesterday, and today I am seeing a few crash logs in Crashlytics:

   Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MyWebViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
          at android.app.ActivityThread.-wrap12(ActivityThread.java)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:154)
          at android.app.ActivityThread.main(ActivityThread.java:6119)
          at java.lang.reflect.Method.invoke(Method.java)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
          at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)

   Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
          at com.example.myapp.MyWebViewActivity.onCreate(MyWebViewActivity.java:77)
          at android.app.Activity.performCreate(Activity.java:6679)
          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
          at android.app.ActivityThread.-wrap12(ActivityThread.java)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:154)
          at android.app.ActivityThread.main(ActivityThread.java:6119)
          at java.lang.reflect.Method.invoke(Method.java)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
          at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)

At the bottom this report mentions XposedBridge, which I find kind of odd. Is this caused by someone experimenting with my app using the Xposed framework? Or could this happen to a "normal user"? Crashlytics says the issue has affected 3 users so far, but I'm skeptical since they all have the exact same phone model and Android version (Motorola Nexus 6, Android 7.1.1) and happened within 10 minutes of each other.

The NPE is caused by getIntent().getStringExtra("some_string").equals("another_string") in an onCreate method, even though I am setting the "some_string" in all places where I'm creating this activity.

So what I'm wondering is if this sort of crash could be the result of anything other than a user who is experimenting with Xposed? I.e. should I take it seriously or not?

Body:
In general having the XposedBridge in the stack trace just means that the app runs on an device with XPosed installed. XPosed changes the Dalvik VM system wide, even if your app isn't modified by any XPosed module.

I don't have much experience with Crashlytics, however the "3 users" I would interpret as one user having cleared the app data two times.

Anyway I would always use safe coding, therefore your call

getIntent().getStringExtra("some_string").equals("another_string")

should be reformulated to:

"another_string".equals(getIntent().getStringExtra("some_string"))

This way is may be a bit unfamiliar to read, but it is safe against NullPointerException in case the current Intent does not has the "some_string" value.


问:
Argument type does not conform to Encodable
I am trying to create a Struct for a POST request. The struct conforms, to the best of my knowledge to the Codable typealias but I keep getting the error

Argument type 'RegisterUserRequest.Type' does not conform to expected type 'Encodable' " when passing it in as a parameter to my JSONEncoder.

I have tried to conform only to Encodable, to write the suggested required init() but nothing seems to work.

This is the way my Struct looks like

```<code>
struct RegisterUserRequest: Codable {
    var firstName: String
    var lastName: String
    var email: String
    var phoneNumber: String
    var dateOfBirth: String

    enum CodingKeys: String, CodingKey {
        case firstName = "first_name"
        case lastName = "last_name"
        case email
        case phoneNumber = "phone"
        case dateOfBirth = "date_of_birth"
    }
}

</code>```

This is the error I get

答:
Here you need to pass an object of a type that conforms to Codable / Encodable not the type itself

```<code>do {
    let instance = RegisterUserRequest(firstname:////////......
    let data = try JSONEncoder().encode(instance)
}
catch {
  print(error)
}
</code>```

Body:
I am trying to create a Struct for a POST request. The struct conforms, to the best of my knowledge to the Codable typealias but I keep getting the error

Argument type 'RegisterUserRequest.Type' does not conform to expected type 'Encodable' " when passing it in as a parameter to my JSONEncoder.

I have tried to conform only to Encodable, to write the suggested required init() but nothing seems to work.

This is the way my Struct looks like

struct RegisterUserRequest: Codable {
    var firstName: String
    var lastName: String
    var email: String
    var phoneNumber: String
    var dateOfBirth: String

    enum CodingKeys: String, CodingKey {
        case firstName = "first_name"
        case lastName = "last_name"
        case email
        case phoneNumber = "phone"
        case dateOfBirth = "date_of_birth"
    }
}

This is the error I get

Body:
Here you need to pass an object of a type that conforms to Codable / Encodable not the type itself

do {
    let instance = RegisterUserRequest(firstname:////////......
    let data = try JSONEncoder().encode(instance)
}
catch {
  print(error)
}


问:
On which thread the callback registered on new CompletableFuture() is executed?
I am new to Completable Futures and trying to understand on which thread a callback registered on CompletableFuture constructed using the the Constructor (new CompletableFuture())

For example:

CompletableFuture<String> future =
        CompletableFuture.supplyAsync(() -> {
            //...
        }, pool);
CompletableFuture<Integer> intFuture =
    future.thenApply(s -> s.length());
```

<p>Transformation in thenApply() is registered and it will be executed immediately after task completion in the same thread as the task.</p>

<pre class="lang-java prettyprint-override"><code>CompletableFuture<String> future = new CompletableFuture();
CompletableFuture<Integer> intFuture =
    future.thenApply(s -> s.length());
future.complete("hello");
</code>```

Transformation in thenApply() is registered and on which thread will it be executed once the task is completed using future.complete("hello")? Will it be executed on the main thread or will it be executed on ForkJoinPool.commonPool()?

答:
Only Async methods are executed by new thread, so in your case thenApply is executed by main thread

All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task).

```<code>public class TestMain {

public static void main(String[] args) {

    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        System.out.println(Thread.currentThread().getName());
        return "hello";
    });
    CompletableFuture<Integer> intFuture = future.thenApply(s -> {
        System.out.println(Thread.currentThread().getName());
        return s.length();
    });

    CompletableFuture<Integer> intFuture2 = future.thenApply(s -> {
        System.out.println(Thread.currentThread().getName());
        return s.length();
        });
       future.complete("hello");

     }

 }
</code>```

Output

```<code>ForkJoinPool.commonPool-worker-1
main
main
</code>```

Body:
I am new to Completable Futures and trying to understand on which thread a callback registered on CompletableFuture constructed using the the Constructor (new CompletableFuture())

For example:

CompletableFuture<String> future =
        CompletableFuture.supplyAsync(() -> {
            //...
        }, pool);
CompletableFuture<Integer> intFuture =
    future.thenApply(s -> s.length());

Transformation in thenApply() is registered and it will be executed immediately after task completion in the same thread as the task.

CompletableFuture<String> future = new CompletableFuture();
CompletableFuture<Integer> intFuture =
    future.thenApply(s -> s.length());
future.complete("hello");

Transformation in thenApply() is registered and on which thread will it be executed once the task is completed using future.complete("hello")? Will it be executed on the main thread or will it be executed on ForkJoinPool.commonPool()?

Body:
Only Async methods are executed by new thread, so in your case thenApply is executed by main thread

All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task).

public class TestMain {

public static void main(String[] args) {

    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        System.out.println(Thread.currentThread().getName());
        return "hello";
    });
    CompletableFuture<Integer> intFuture = future.thenApply(s -> {
        System.out.println(Thread.currentThread().getName());
        return s.length();
    });

    CompletableFuture<Integer> intFuture2 = future.thenApply(s -> {
        System.out.println(Thread.currentThread().getName());
        return s.length();
        });
       future.complete("hello");

     }

 }

Output

ForkJoinPool.commonPool-worker-1
main
main


问:
How to Use Intent for Media Player?
I want to use intent for my homework application. When i click button1, my SoundActivity opening, after playing sound1.mp3 file. But i wanna when i clicked button2, sound2.mp3 file playing in SoundActivity..

This is my MainActivity.java codes:

```<code>button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });

button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });
</code>```

This is my Sound Activity side:

```<code>sound1 = MediaPlayer.create(this, R.raw.bell);
sound2 = MediaPlayer.create(this, R.raw.siren);

sound1.start();
</code>```

答:
```<code>'You can send your sound with intent using putt extras like'

button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", R.raw.bell);
            startActivity(intent);

            }
        });

button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", R.raw.siren);
            startActivity(intent);

            }
        });

'in sound actvity you just get the sound using bundle and pass it to media player like'

Bundle bundle = getIntent().getExtras();
        int sound = bundle.getInt("SOUND");

sound1 = MediaPlayer.create(this, sound);

sound1.start();

'Hope you get the solution.'
</code>```

Title: How to Use Intent for Media Player?

Body:
I want to use intent for my homework application. When i click button1, my SoundActivity opening, after playing sound1.mp3 file. But i wanna when i clicked button2, sound2.mp3 file playing in SoundActivity..

This is my MainActivity.java codes:

button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });

button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });

This is my Sound Activity side:

sound1 = MediaPlayer.create(this, R.raw.bell);
sound2 = MediaPlayer.create(this, R.raw.siren);

sound1.start();


问:
Angular how to show live value of json object
In angular , I am trying to display one json object to client html. Using below route on server side.

```<code>const express = require('express');
const jsonRoute = express.Router();

jsonRoute .route('/json').get(function (req, res) {
    var JsonObj = { rank: 73 } ;
  res.end(JSON.stringify(JsonObj));
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

module.exports = jsonRoute ;
</code>```

this works on http://localhost:4000/json and displays ,

```<code>{"rank":73}
</code>```

But does not show the values changed in setInterval. And same route i am using in a angular service (using http).

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class getjsonService {
  uri = "http://localhost:4000/json";
  constructor(private http: HttpClient) { }
  jsondata(){
    return this.http.get(`${this.uri}`);
  }
}
</code>```

This value i am displaying in component html page. The problem is, it is not showing updated value of json. Please suggest how can i show live json value in angular. Please note, in realtime my json object going to be big in size , around 100 keys and value and i want to show live value for all key. And also change value interval may not be fix as one second. it may be in milliseconds as well.

Thanks

答:
By default http will not persistent the connection. It's http protocol limitation not from angular.If you want to show the value in real time, you need to use web sockets.

There are lot of library out there will help with real time data connection. https://socket.io/ is very popular. check this out

Tutorial :https://alligator.io/angular/socket-io/

Body:
In angular , I am trying to display one json object to client html. Using below route on server side.

const express = require('express');
const jsonRoute = express.Router();

jsonRoute .route('/json').get(function (req, res) {
    var JsonObj = { rank: 73 } ;
  res.end(JSON.stringify(JsonObj));
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

module.exports = jsonRoute ;

this works on http://localhost:4000/json and displays ,

{"rank":73}

But does not show the values changed in setInterval. And same route i am using in a angular service (using http).

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class getjsonService {
  uri = "http://localhost:4000/json";
  constructor(private http: HttpClient) { }
  jsondata(){
    return this.http.get(`${this.uri}`);
  }
}

This value i am displaying in component html page. The problem is, it is not showing updated value of json. Please suggest how can i show live json value in angular. Please note, in realtime my json object going to be big in size , around 100 keys and value and i want to show live value for all key. And also change value interval may not be fix as one second. it may be in milliseconds as well.

Thanks