问:
CS 50 Edges filter
Could someone tell me where in my code I made a mistake? The values are failing check50. The loops seem to be correct, I really can't tell where the problem is.

I've looked at https://medium.com/swlh/cs50-pset-4-filter-8cbf734b0dbc and the code seems pretty much the same...

Thank you so much!

https://pastebin.com/MkZPFbEK

```<code>void edges(int height, int width, RGBTRIPLE image[height][width])
{
// for pixels at the border, treat value as B.G.R value as 0
// compute gx and gy for each value of B, G, R
// square root of gx and gy squared

    RGBTRIPLE tempstore[height][width];

    int Gx[3][3] = {
                    {-1, 0 , 1},
                    {-2, 0 , 2},
                    {-1, 0 , 1}
                    };

    int Gy[3][3] = {
                    {-2, -1 , -1},
                    {0, 0 , 0},
                    {2, -1 , 1}
                    };

    // for each row
    for (int i = 0; i < height; i = i + 1)
        {
            // for each column
            for (int j = 0; j < width; j = j + 1)
            {
                // float horvalueB=0;
                // float horvalueG=0;
                // float horvalueR=0;

                // float vertvalueB=0;
                // float vertvalueG=0;
                // float vertvalueR=0;
                float sumhorB=0;
                float sumhorG=0;
                float sumhorR=0;

                float sumvertB=0;
                float sumvertG=0;
                float sumvertR=0;

                // check if height of neighbor cell
                for (int k = -1; k <= 1; k = k + 1)
                {
                        for (int l = -1; l <= 1; l = l + 1)
                        {
                           int htcheck = i + k;
                           int wdcheck = j + l;
                            // check if height of neighbor cell is within bounds
                            if (((htcheck) >= 0) && ((htcheck) < height))
                            {
                                // check if width of neighbor cell is within bounds
                                if (((wdcheck) >= 0) && ((wdcheck) < width))
                                {
                                    sumhorB += image[htcheck][wdcheck].rgbtBlue * Gx[k+1][l+1];
                                    sumhorG += image[htcheck][wdcheck].rgbtGreen * Gx[k+1][l+1];
                                    sumhorR += image[htcheck][wdcheck].rgbtRed * Gx[k+1][l+1];

                                    sumvertB += image[htcheck][wdcheck].rgbtBlue * Gy[k+1][l+1];
                                    sumvertG += image[htcheck][wdcheck].rgbtGreen * Gy[k+1][l+1];
                                    sumvertR += image[htcheck][wdcheck].rgbtRed * Gy[k+1][l+1];

                                    // sumhorB = sumhorB + horvalueB;
                                    // sumhorG = sumhorG + horvalueG;
                                    // sumhorR = sumhorR + horvalueR;

                                    // sumvertB = sumvertB + vertvalueB;
                                    // sumvertG = sumvertG + vertvalueG;
                                    // sumvertR = sumvertR + vertvalueR;
                            }
                        }
                    }
                }
                int blue = round(sqrt( sumhorB*sumhorB + sumvertB*sumhorB ));
                int green = round(sqrt( sumhorG*sumhorG + sumvertG*sumhorG ));
                int red = round(sqrt( sumhorR*sumhorR + sumvertR*sumhorR ));

                // Cap at 255
                if (red > 255)
                {
                    red = 255;
                }
                if (green > 255)
                {
                    green = 255;
                }
                if (blue > 255)
                {
                    blue = 255;
                }            // Assign new values to pixels
                tempstore[i][j].rgbtRed = red;
                tempstore[i][j].rgbtGreen = green;
                tempstore[i][j].rgbtBlue = blue;

            }
        }

    for (int i = 0; i < height; i = i + 1)
    {
        for (int j = 0; j < width; j = j + 1)
        {
            image[i][j].rgbtBlue = tempstore[i][j].rgbtBlue;
            image[i][j].rgbtGreen = tempstore[i][j].rgbtGreen;
            image[i][j].rgbtRed = tempstore[i][j].rgbtRed;
        }
    }

    return;
}
</code>```

答:
Ahh.... The problem is I was multiplying the wrong things... Sorry about it. Was multiplying sumvert with sumhor...

```<code>            int blue = round(sqrt( (sumhorB*sumhorB) + (sumvertB*sumhorB) ));
            int green = round(sqrt( (sumhorG*sumhorG) + (sumvertG*sumhorG) ));
            int red = round(sqrt( (sumhorR*sumhorR) + (sumvertR*sumhorR) ));
</code>```

Should be

```<code>            int blue = round(sqrt( (sumhorB*sumhorB) + (sumvertB*sumvertB) ));
            int green = round(sqrt( (sumhorG*sumhorG) + (sumvertG*sumvertG) ));
            int red = round(sqrt( (sumhorR*sumhorR) + (sumvertR*sumvertR) ));
</code>```

Title: CS 50 Edges filter

Body:
Could someone tell me where in my code I made a mistake? The values are failing check50. The loops seem to be correct, I really can't tell where the problem is.

I've looked at https://medium.com/swlh/cs50-pset-4-filter-8cbf734b0dbc and the code seems pretty much the same...

Thank you so much!

https://pastebin.com/MkZPFbEK

void edges(int height, int width, RGBTRIPLE image[height][width])
{
// for pixels at the border, treat value as B.G.R value as 0
// compute gx and gy for each value of B, G, R
// square root of gx and gy squared

    RGBTRIPLE tempstore[height][width];

    int Gx[3][3] = {
                    {-1, 0 , 1},
                    {-2, 0 , 2},
                    {-1, 0 , 1}
                    };

    int Gy[3][3] = {
                    {-2, -1 , -1},
                    {0, 0 , 0},
                    {2, -1 , 1}
                    };

    // for each row
    for (int i = 0; i < height; i = i + 1)
        {
            // for each column
            for (int j = 0; j < width; j = j + 1)
            {
                // float horvalueB=0;
                // float horvalueG=0;
                // float horvalueR=0;

                // float vertvalueB=0;
                // float vertvalueG=0;
                // float vertvalueR=0;
                float sumhorB=0;
                float sumhorG=0;
                float sumhorR=0;

                float sumvertB=0;
                float sumvertG=0;
                float sumvertR=0;

                // check if height of neighbor cell
                for (int k = -1; k <= 1; k = k + 1)
                {
                        for (int l = -1; l <= 1; l = l + 1)
                        {
                           int htcheck = i + k;
                           int wdcheck = j + l;
                            // check if height of neighbor cell is within bounds
                            if (((htcheck) >= 0) && ((htcheck) < height))
                            {
                                // check if width of neighbor cell is within bounds
                                if (((wdcheck) >= 0) && ((wdcheck) < width))
                                {
                                    sumhorB += image[htcheck][wdcheck].rgbtBlue * Gx[k+1][l+1];
                                    sumhorG += image[htcheck][wdcheck].rgbtGreen * Gx[k+1][l+1];
                                    sumhorR += image[htcheck][wdcheck].rgbtRed * Gx[k+1][l+1];

                                    sumvertB += image[htcheck][wdcheck].rgbtBlue * Gy[k+1][l+1];
                                    sumvertG += image[htcheck][wdcheck].rgbtGreen * Gy[k+1][l+1];
                                    sumvertR += image[htcheck][wdcheck].rgbtRed * Gy[k+1][l+1];

                                    // sumhorB = sumhorB + horvalueB;
                                    // sumhorG = sumhorG + horvalueG;
                                    // sumhorR = sumhorR + horvalueR;

                                    // sumvertB = sumvertB + vertvalueB;
                                    // sumvertG = sumvertG + vertvalueG;
                                    // sumvertR = sumvertR + vertvalueR;
                            }
                        }
                    }
                }
                int blue = round(sqrt( sumhorB*sumhorB + sumvertB*sumhorB ));
                int green = round(sqrt( sumhorG*sumhorG + sumvertG*sumhorG ));
                int red = round(sqrt( sumhorR*sumhorR + sumvertR*sumhorR ));

                // Cap at 255
                if (red > 255)
                {
                    red = 255;
                }
                if (green > 255)
                {
                    green = 255;
                }
                if (blue > 255)
                {
                    blue = 255;
                }            // Assign new values to pixels
                tempstore[i][j].rgbtRed = red;
                tempstore[i][j].rgbtGreen = green;
                tempstore[i][j].rgbtBlue = blue;

            }
        }

    for (int i = 0; i < height; i = i + 1)
    {
        for (int j = 0; j < width; j = j + 1)
        {
            image[i][j].rgbtBlue = tempstore[i][j].rgbtBlue;
            image[i][j].rgbtGreen = tempstore[i][j].rgbtGreen;
            image[i][j].rgbtRed = tempstore[i][j].rgbtRed;
        }
    }

    return;
}

Body:
Ahh.... The problem is I was multiplying the wrong things... Sorry about it. Was multiplying sumvert with sumhor...

            int blue = round(sqrt( (sumhorB*sumhorB) + (sumvertB*sumhorB) ));
            int green = round(sqrt( (sumhorG*sumhorG) + (sumvertG*sumhorG) ));
            int red = round(sqrt( (sumhorR*sumhorR) + (sumvertR*sumhorR) ));

Should be

            int blue = round(sqrt( (sumhorB*sumhorB) + (sumvertB*sumvertB) ));
            int green = round(sqrt( (sumhorG*sumhorG) + (sumvertG*sumvertG) ));
            int red = round(sqrt( (sumhorR*sumhorR) + (sumvertR*sumvertR) ));


来源: stackexchange

问:
how to play sound using java
I am trying to play a sound(a.mp3 ) on button ckick in java.

I tried this code

AudioPlayer.player.start(new FileInputStream(new File("E://a.mp3")));

but the sound is not clear....

What should I do,(I'm a beginner in java).

答:
Try taking a look at this article.
http://www.morgenstille.at/blog/how-to-play-a-mp3-file-in-java-simple-and-beautiful/

Also JFugue can load and play midi files.

ContentLicense: CC BY-SA 3.0

Title: how to play sound using java


问:
Splitting a string and retaining the separator (without RegEx)
I have the following string foo:

```<code>foo = 'F9B2Z1F8B30Z4'
</code>```

Without using re, I'd like to split on 'F' and then add 'F' back to the resulting list.

My attempt is:

```<code>['F'+elem for elem in foo.split('F')]
</code>```

This gives us:

```<code>['F', 'F9B2Z1', 'F8B30Z4']
</code>```

But, I was expecting:

```<code>['F9B2Z1', 'F8B30Z4']
</code>```

Is it possible to modify the list comprehension to catch this case?  If not, is there another approach that I can use?

Thanks!

答:
Without regex we can do it by replacing the F with some other delimiter before it then spiting it at the replaced delimiter and filtering empty strings

[elem for elem in foo.replace("F","-F").split("-") if elem]

ContentLicense: CC BY-SA 4.0

Body:
I have the following string foo:

foo = 'F9B2Z1F8B30Z4'

Without using re, I'd like to split on 'F' and then add 'F' back to the resulting list.

My attempt is:

['F'+elem for elem in foo.split('F')]

This gives us:

['F', 'F9B2Z1', 'F8B30Z4']

But, I was expecting:

['F9B2Z1', 'F8B30Z4']

Is it possible to modify the list comprehension to catch this case?  If not, is there another approach that I can use?

Thanks!


问:
I'm try to grant access to Enable and Disable Bluetooth on Android Studio using JAVA; but startActivityForResult has been Deprecated. What I can do?
I would like grant access to Enable and Disable Bluetooth from Android Studio. I also pretend to use other functionalities of Bluetooth as list of devices and connect to previous pared device and more.

Since starActivityForResult has been Deprecated, I'm having trouble to lunch the pop up activity that ask the user for allowance.

This is my manifest

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.bluetoothonofftest"
    tools:ignore="CoarseFineLocation">

    <!-- Request legacy Bluetooth permissions on older devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH"
        android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
        android:maxSdkVersion="30"
        tools:ignore="CoarseFineLocation" />

    <!-- Needed only if your app looks for Bluetooth devices.
         If your app doesn't use Bluetooth scan results to derive physical
         location information, you can strongly assert that your app
         doesn't derive physical location. -->
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

    <!-- Needed only if your app makes the device discoverable to Bluetooth
         devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />

    <!-- Needed only if your app communicates with already-paired Bluetooth
         devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

    <!-- Needed only if your app uses Bluetooth scan results to derive physical location. -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

    <uses-feature android:name="android.hardware.bluetooth" android:required="true"/>

    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BlUetoothTest">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

This is my ManinActivity

```<code>package com.example.bluetoothexamples;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVER_BT = 1;

    TextView mStatusBlueTv;
    TextView mPairedTv;

    ImageView mBlueIv;

    Button mOnBtn;
    Button mOffBtn;
    Button mDiscoverBtn;
    Button mPairedBtn;

    BluetoothAdapter mBlueAdapter;

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

        mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
        mPairedTv = findViewById(R.id.pairedTv);

        mBlueIv = findViewById(R.id.bluetoothIv);

        mOnBtn = findViewById(R.id.onBtn);
        mOffBtn = findViewById(R.id.offBtn);
        mDiscoverBtn = findViewById(R.id.discoverableBtn);
        mPairedBtn = findViewById(R.id.pairedBtn);

        // Adapter
        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Check if bluetooth is available or not
        if (mBlueAdapter == null) {
            mStatusBlueTv.setText("Bluetooth is NOT Available");
        } else {
            mStatusBlueTv.setText("Bluetooth is Available");

            // Set image according to bluetooth status (on/off)
            if (mBlueAdapter.isEnabled()) {
                mBlueIv.setImageResource(R.drawable.ic_action_on);
            } else {
                mBlueIv.setImageResource(R.drawable.ic_action_off);
            }

            mOnBtn.setOnClickListener(this);          // Turn on Bluetooth btn click
            mDiscoverBtn.setOnClickListener(this);    // Discover bluetooth btn click
            mOffBtn.setOnClickListener(this);         // Turn off Bluetooth btn click
            mPairedBtn.setOnClickListener(this);      // Get Paired devices button click
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            // Turn on Bluetooth btn click
            case R.id.onBtn:

                if (!mBlueAdapter.isEnabled()) {
                   // showToast("Turning On Bluetooth...");

//                    if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
//                    } else {
//                        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
//                    }

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    // Intent to On Bluetooth
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, REQUEST_ENABLE_BT);
                }
                else {
                    showToast("Bluetooth is already on");
                }

            break;

            // Discover bluetooth btn click
            case R.id.discoverableBtn:

                if (!mBlueAdapter.isDiscovering()){
                    showToast("Making Your Device Discoverable");
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    startActivityForResult(intent ,REQUEST_DISCOVER_BT);
                }

            break;

            // Turn off Bluetooth btn click
            case R.id.offBtn:

                if (mBlueAdapter.isEnabled()) {
                    mBlueAdapter.disable();
                    showToast("Turning Bluetooth Off");
                    mBlueIv.setImageResource(R.drawable.ic_action_off);
                }
                else {
                    showToast("Bluetooth is already off");
                }

             break;
                // Get Paired devices button click
            case R.id.pairedBtn:

                if (mBlueAdapter.isEnabled()) {
                    mPairedTv.setText("Paired Devices");
                    Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
                    for (BluetoothDevice device: devices){
                        mPairedTv.append("\nDevice: " + device.getName() + ", " + device);
                    }
                }
                else {
                    //bluetooth is off so can't get paired devices
                    showToast("Turn ON Bluetooth to get paired devices");
                }

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                showToast("Permission Granted");
            }
            else {
                showToast("Permission Denied");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case REQUEST_ENABLE_BT:

                if (resultCode == RESULT_OK) {
                    // Bluetooth is on
                    mBlueIv.setImageResource(R.drawable.ic_action_on);
                    showToast("Bluetooth is on");
                }
                else {
                    showToast("Failed to connect to bluetooth");
                }

            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //Toast message function
    private void showToast (String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

</code>```

This is my XML

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

<!--    Display whether bluetooth is available or not-->
    <TextView
        android:id="@+id/statusBluetoothTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAlignment="center"
        android:textSize="20sp"
        android:textColor="#000" />

<!--    Bluetooth icon-->
    <ImageView
        android:id="@+id/bluetoothIv"
        android:layout_width="100dp"
        android:layout_height="100dp" />

<!--    on Button-->
    <Button
        android:id="@+id/onBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Turn On"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    off Button-->
    <Button
        android:id="@+id/offBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Turn Off"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    Discoverable button-->
    <Button
        android:id="@+id/discoverableBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Discoverable"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    Get list of paired devices button-->
    <Button
        android:id="@+id/pairedBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Paired Devices"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    Show paired devices here-->
    <TextView
        android:id="@+id/pairedTv"
        android:minWidth="200dp"
        android:text=""
        android:textColor="#000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

答:
Currently the recommended approach is using a ActivityResultLauncher to get the results like so:

```<code>ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
             if (result.getResultCode() == Activity.RESULT_OK) {
                 Log.e("Activity result","OK");
                 // There are no request codes
                Intent data = result.getData();
            }
        });
</code>```

so just call it like:

```<code>Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activityResultLauncher.launch(intent);
</code>```

and for your case assuming everything else is working fine ,you update to something like below:

```<code>package com.example.bluetoothexamples;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import android.app.Activity;
import android.util.Log;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVER_BT = 1;

    TextView mStatusBlueTv;
    TextView mPairedTv;

    ImageView mBlueIv;

    Button mOnBtn;
    Button mOffBtn;
    Button mDiscoverBtn;
    Button mPairedBtn;

    BluetoothAdapter mBlueAdapter;
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                 if (result.getResultCode() == Activity.RESULT_OK) {
                     Log.e("Activity result","OK");
                     // There are no request codes
                    Intent data = result.getData();
                }
            });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
        mPairedTv = findViewById(R.id.pairedTv);

        mBlueIv = findViewById(R.id.bluetoothIv);

        mOnBtn = findViewById(R.id.onBtn);
        mOffBtn = findViewById(R.id.offBtn);
        mDiscoverBtn = findViewById(R.id.discoverableBtn);
        mPairedBtn = findViewById(R.id.pairedBtn);

        // Adapter
        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Check if bluetooth is available or not
        if (mBlueAdapter == null) {
            mStatusBlueTv.setText("Bluetooth is NOT Available");
        } else {
            mStatusBlueTv.setText("Bluetooth is Available");

            // Set image according to bluetooth status (on/off)
            if (mBlueAdapter.isEnabled()) {
                mBlueIv.setImageResource(R.drawable.ic_action_on);
            } else {
                mBlueIv.setImageResource(R.drawable.ic_action_off);
            }

            mOnBtn.setOnClickListener(this);          // Turn on Bluetooth btn click
            mDiscoverBtn.setOnClickListener(this);    // Discover bluetooth btn click
            mOffBtn.setOnClickListener(this);         // Turn off Bluetooth btn click
            mPairedBtn.setOnClickListener(this);      // Get Paired devices button click
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            // Turn on Bluetooth btn click
            case R.id.onBtn:

                if (!mBlueAdapter.isEnabled()) {
                   // showToast("Turning On Bluetooth...");

//                    if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
//                    } else {
//                        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
//                    }

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    // Intent to On Bluetooth
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                  //  startActivityForResult(intent, REQUEST_ENABLE_BT);

        activityResultLauncher.launch(intent);
                }
                else {
                    showToast("Bluetooth is already on");
                }

            break;

            // Discover bluetooth btn click
            case R.id.discoverableBtn:

                if (!mBlueAdapter.isDiscovering()){
                    showToast("Making Your Device Discoverable");
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    //startActivityForResult(intent ,REQUEST_DISCOVER_BT);
                     activityResultLauncher.launch(intent);
                }

            break;

            // Turn off Bluetooth btn click
            case R.id.offBtn:

                if (mBlueAdapter.isEnabled()) {
                    mBlueAdapter.disable();
                    showToast("Turning Bluetooth Off");
                    mBlueIv.setImageResource(R.drawable.ic_action_off);
                }
                else {
                    showToast("Bluetooth is already off");
                }

             break;
                // Get Paired devices button click
            case R.id.pairedBtn:

                if (mBlueAdapter.isEnabled()) {
                    mPairedTv.setText("Paired Devices");
                    Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
                    for (BluetoothDevice device: devices){
                        mPairedTv.append("\nDevice: " + device.getName() + ", " + device);
                    }
                }
                else {
                    //bluetooth is off so can't get paired devices
                    showToast("Turn ON Bluetooth to get paired devices");
                }

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                showToast("Permission Granted");
            }
            else {
                showToast("Permission Denied");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case REQUEST_ENABLE_BT:

                if (resultCode == RESULT_OK) {
                    // Bluetooth is on
                    mBlueIv.setImageResource(R.drawable.ic_action_on);
                    showToast("Bluetooth is on");
                }
                else {
                    showToast("Failed to connect to bluetooth");
                }

            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //Toast message function
    private void showToast (String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}
</code>```

for java <8 :

```<code>   ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Log.e("Activity result", "OK");
                        // There are no request codes
                        Intent data = result.getData();
                    }
                }
            }
            );
</code>```

Body:
I would like grant access to Enable and Disable Bluetooth from Android Studio. I also pretend to use other functionalities of Bluetooth as list of devices and connect to previous pared device and more.

Since starActivityForResult has been Deprecated, I'm having trouble to lunch the pop up activity that ask the user for allowance.

This is my manifest

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.bluetoothonofftest"
    tools:ignore="CoarseFineLocation">

    <uses-permission android:name="android.permission.BLUETOOTH"
        android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
        android:maxSdkVersion="30"
        tools:ignore="CoarseFineLocation" />

    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />

    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

    <uses-feature android:name="android.hardware.bluetooth" android:required="true"/>

    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BlUetoothTest">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

This is my ManinActivity

package com.example.bluetoothexamples;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVER_BT = 1;

    TextView mStatusBlueTv;
    TextView mPairedTv;

    ImageView mBlueIv;

    Button mOnBtn;
    Button mOffBtn;
    Button mDiscoverBtn;
    Button mPairedBtn;

    BluetoothAdapter mBlueAdapter;

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

        mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
        mPairedTv = findViewById(R.id.pairedTv);

        mBlueIv = findViewById(R.id.bluetoothIv);

        mOnBtn = findViewById(R.id.onBtn);
        mOffBtn = findViewById(R.id.offBtn);
        mDiscoverBtn = findViewById(R.id.discoverableBtn);
        mPairedBtn = findViewById(R.id.pairedBtn);

        // Adapter
        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Check if bluetooth is available or not
        if (mBlueAdapter == null) {
            mStatusBlueTv.setText("Bluetooth is NOT Available");
        } else {
            mStatusBlueTv.setText("Bluetooth is Available");

            // Set image according to bluetooth status (on/off)
            if (mBlueAdapter.isEnabled()) {
                mBlueIv.setImageResource(R.drawable.ic_action_on);
            } else {
                mBlueIv.setImageResource(R.drawable.ic_action_off);
            }

            mOnBtn.setOnClickListener(this);          // Turn on Bluetooth btn click
            mDiscoverBtn.setOnClickListener(this);    // Discover bluetooth btn click
            mOffBtn.setOnClickListener(this);         // Turn off Bluetooth btn click
            mPairedBtn.setOnClickListener(this);      // Get Paired devices button click
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            // Turn on Bluetooth btn click
            case R.id.onBtn:

                if (!mBlueAdapter.isEnabled()) {
                   // showToast("Turning On Bluetooth...");

//                    if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
//                    } else {
//                        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
//                    }

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    // Intent to On Bluetooth
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, REQUEST_ENABLE_BT);
                }
                else {
                    showToast("Bluetooth is already on");
                }

            break;

            // Discover bluetooth btn click
            case R.id.discoverableBtn:

                if (!mBlueAdapter.isDiscovering()){
                    showToast("Making Your Device Discoverable");
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    startActivityForResult(intent ,REQUEST_DISCOVER_BT);
                }

            break;

            // Turn off Bluetooth btn click
            case R.id.offBtn:

                if (mBlueAdapter.isEnabled()) {
                    mBlueAdapter.disable();
                    showToast("Turning Bluetooth Off");
                    mBlueIv.setImageResource(R.drawable.ic_action_off);
                }
                else {
                    showToast("Bluetooth is already off");
                }

             break;
                // Get Paired devices button click
            case R.id.pairedBtn:

                if (mBlueAdapter.isEnabled()) {
                    mPairedTv.setText("Paired Devices");
                    Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
                    for (BluetoothDevice device: devices){
                        mPairedTv.append("\nDevice: " + device.getName() + ", " + device);
                    }
                }
                else {
                    //bluetooth is off so can't get paired devices
                    showToast("Turn ON Bluetooth to get paired devices");
                }

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                showToast("Permission Granted");
            }
            else {
                showToast("Permission Denied");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case REQUEST_ENABLE_BT:

                if (resultCode == RESULT_OK) {
                    // Bluetooth is on
                    mBlueIv.setImageResource(R.drawable.ic_action_on);
                    showToast("Bluetooth is on");
                }
                else {
                    showToast("Failed to connect to bluetooth");
                }

            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //Toast message function
    private void showToast (String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

This is my XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/statusBluetoothTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAlignment="center"
        android:textSize="20sp"
        android:textColor="#000" />

    <ImageView
        android:id="@+id/bluetoothIv"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <Button
        android:id="@+id/onBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Turn On"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

    <Button
        android:id="@+id/offBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Turn Off"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

    <Button
        android:id="@+id/discoverableBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Discoverable"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

    <Button
        android:id="@+id/pairedBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Paired Devices"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

    <TextView
        android:id="@+id/pairedTv"
        android:minWidth="200dp"
        android:text=""
        android:textColor="#000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Body:
Currently the recommended approach is using a ActivityResultLauncher to get the results like so:

ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
             if (result.getResultCode() == Activity.RESULT_OK) {
                 Log.e("Activity result","OK");
                 // There are no request codes
                Intent data = result.getData();
            }
        });

so just call it like:

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activityResultLauncher.launch(intent);

and for your case assuming everything else is working fine ,you update to something like below:

package com.example.bluetoothexamples;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import android.app.Activity;
import android.util.Log;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVER_BT = 1;

    TextView mStatusBlueTv;
    TextView mPairedTv;

    ImageView mBlueIv;

    Button mOnBtn;
    Button mOffBtn;
    Button mDiscoverBtn;
    Button mPairedBtn;

    BluetoothAdapter mBlueAdapter;
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                 if (result.getResultCode() == Activity.RESULT_OK) {
                     Log.e("Activity result","OK");
                     // There are no request codes
                    Intent data = result.getData();
                }
            });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
        mPairedTv = findViewById(R.id.pairedTv);

        mBlueIv = findViewById(R.id.bluetoothIv);

        mOnBtn = findViewById(R.id.onBtn);
        mOffBtn = findViewById(R.id.offBtn);
        mDiscoverBtn = findViewById(R.id.discoverableBtn);
        mPairedBtn = findViewById(R.id.pairedBtn);

        // Adapter
        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Check if bluetooth is available or not
        if (mBlueAdapter == null) {
            mStatusBlueTv.setText("Bluetooth is NOT Available");
        } else {
            mStatusBlueTv.setText("Bluetooth is Available");

            // Set image according to bluetooth status (on/off)
            if (mBlueAdapter.isEnabled()) {
                mBlueIv.setImageResource(R.drawable.ic_action_on);
            } else {
                mBlueIv.setImageResource(R.drawable.ic_action_off);
            }

            mOnBtn.setOnClickListener(this);          // Turn on Bluetooth btn click
            mDiscoverBtn.setOnClickListener(this);    // Discover bluetooth btn click
            mOffBtn.setOnClickListener(this);         // Turn off Bluetooth btn click
            mPairedBtn.setOnClickListener(this);      // Get Paired devices button click
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            // Turn on Bluetooth btn click
            case R.id.onBtn:

                if (!mBlueAdapter.isEnabled()) {
                   // showToast("Turning On Bluetooth...");

//                    if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
//                    } else {
//                        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
//                    }

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    // Intent to On Bluetooth
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                  //  startActivityForResult(intent, REQUEST_ENABLE_BT);

        activityResultLauncher.launch(intent);
                }
                else {
                    showToast("Bluetooth is already on");
                }

            break;

            // Discover bluetooth btn click
            case R.id.discoverableBtn:

                if (!mBlueAdapter.isDiscovering()){
                    showToast("Making Your Device Discoverable");
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    //startActivityForResult(intent ,REQUEST_DISCOVER_BT);
                     activityResultLauncher.launch(intent);
                }

            break;

            // Turn off Bluetooth btn click
            case R.id.offBtn:

                if (mBlueAdapter.isEnabled()) {
                    mBlueAdapter.disable();
                    showToast("Turning Bluetooth Off");
                    mBlueIv.setImageResource(R.drawable.ic_action_off);
                }
                else {
                    showToast("Bluetooth is already off");
                }

             break;
                // Get Paired devices button click
            case R.id.pairedBtn:

                if (mBlueAdapter.isEnabled()) {
                    mPairedTv.setText("Paired Devices");
                    Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
                    for (BluetoothDevice device: devices){
                        mPairedTv.append("\nDevice: " + device.getName() + ", " + device);
                    }
                }
                else {
                    //bluetooth is off so can't get paired devices
                    showToast("Turn ON Bluetooth to get paired devices");
                }

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                showToast("Permission Granted");
            }
            else {
                showToast("Permission Denied");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case REQUEST_ENABLE_BT:

                if (resultCode == RESULT_OK) {
                    // Bluetooth is on
                    mBlueIv.setImageResource(R.drawable.ic_action_on);
                    showToast("Bluetooth is on");
                }
                else {
                    showToast("Failed to connect to bluetooth");
                }

            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //Toast message function
    private void showToast (String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

for java <8 :

   ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Log.e("Activity result", "OK");
                        // There are no request codes
                        Intent data = result.getData();
                    }
                }
            }
            );


问:
Why are these solid lines appearing below my plot in ggplot?

Here is my code:

```<code>pokemon <- read_csv("https://uwmadison.box.com/shared/static/hf5cmx3ew3ch0v6t0c2x56838er1lt2c.csv")

pokemon %>%
  select(Name, type_1, Attack, Defense) %>%
  mutate(AttDefRatio = Attack/Defense) %>%
  ggplot(
    aes(Name, AttDefRatio)
  ) +
  geom_point(size = 0.5) +
  facet_wrap(type_1 ~ .) +
  theme(legend.position = "bottom")
</code>```

for this home work assignment we are working with faceting, and everything pretty much looks how it should, but there those two thick lines at the bottom of the plot.  If anyone has any idea why its happening that would be awesome!

答:
The two lines are actually the x axis labels, but you can remove them with axis.text.x=element_blank():

```<code>pokemon %>%
    select(Name, type_1, Attack, Defense) %>%
    mutate(AttDefRatio = Attack/Defense) %>%
    ggplot(
        aes(Name, AttDefRatio)
    ) +
    geom_point(size = 0.5) +
    facet_wrap(type_1 ~ .) +
    theme(legend.position = "bottom", axis.text.x=element_blank())
</code>```

Alternatively, if you want to show the individual Names by setting to free_x in facet_wrap, then change the text size in theme. Though it is a lot of information to show on one graph and will be difficult to see.

```<code>pokemon %>%
  select(Name, type_1, Attack, Defense) %>%
  mutate(AttDefRatio = Attack/Defense) %>%
  ggplot(
    aes(Name, AttDefRatio)
  ) +
  geom_point(size = 0.5) +
  facet_wrap(type_1 ~ ., ncol = 5, scales = "free_x") +
  theme(legend.position = "bottom", axis.text.x=element_text(angle = 90, vjust = 0.5, hjust=1, size = 3))
</code>```

Body:
Here is my code:

pokemon <- read_csv("https://uwmadison.box.com/shared/static/hf5cmx3ew3ch0v6t0c2x56838er1lt2c.csv")

pokemon %>%
  select(Name, type_1, Attack, Defense) %>%
  mutate(AttDefRatio = Attack/Defense) %>%
  ggplot(
    aes(Name, AttDefRatio)
  ) +
  geom_point(size = 0.5) +
  facet_wrap(type_1 ~ .) +
  theme(legend.position = "bottom")

for this home work assignment we are working with faceting, and everything pretty much looks how it should, but there those two thick lines at the bottom of the plot.  If anyone has any idea why its happening that would be awesome!

Body:
The two lines are actually the x axis labels, but you can remove them with axis.text.x=element_blank():

pokemon %>%
    select(Name, type_1, Attack, Defense) %>%
    mutate(AttDefRatio = Attack/Defense) %>%
    ggplot(
        aes(Name, AttDefRatio)
    ) +
    geom_point(size = 0.5) +
    facet_wrap(type_1 ~ .) +
    theme(legend.position = "bottom", axis.text.x=element_blank())

Alternatively, if you want to show the individual Names by setting to free_x in facet_wrap, then change the text size in theme. Though it is a lot of information to show on one graph and will be difficult to see.

pokemon %>%
  select(Name, type_1, Attack, Defense) %>%
  mutate(AttDefRatio = Attack/Defense) %>%
  ggplot(
    aes(Name, AttDefRatio)
  ) +
  geom_point(size = 0.5) +
  facet_wrap(type_1 ~ ., ncol = 5, scales = "free_x") +
  theme(legend.position = "bottom", axis.text.x=element_text(angle = 90, vjust = 0.5, hjust=1, size = 3))


问:
How can I access Data Class Properties created from JSON in Kotlin/Android
I am just getting started with Android/Kotlin and I am having issues with something very basic. I use retrofit to return JSON:

```<code>[
  {
    "id": "45837",
    "date_time": "2022-02-02 12:50:06",
    "pool_filter_status": "0",
    "pool_temperature": "97.59",
    "target_temperature": "97.3",
    "status_changed": "1"
  }
]
</code>```

In my viewmodel class, I have the following function that does retrieve the code from the server:

```<code>...

   private val _pooldata = MutableLiveData<List<PoolData>>()
   val pooldata: LiveData<List<PoolData>> = _pooldata

...

private fun getPoolData() {

        viewModelScope.launch {
            _status.value = PoolApiStatus.LOADING
            try {
                _pooldata.value = PoolDataApi.retrofitService.getPoolData()
                _status.value = PoolApiStatus.DONE
            } catch (e: Exception) {
                _status.value = PoolApiStatus.ERROR

            }

        }

    }
</code>```

For what its worth, its always just a single JSON object (though its in a single element array)

My really dumb question is how to access the properties of the data object / returned JSON.

If I log _pooldata.value.toString(), I just get:

```<code>[PoolData(id=45833, date_time=2022-02-02 12:30:02, pool_filter_status=1, pool_temperature=96.91, target_temperature=97.3, status_changed=0)]
</code>```

I am just trying to understand Kotlin "by doing" at this point, but I don't understand how to access those values (id, date_time, etc). its not _pooldata.id.value, _pooldata[0].id.value etc.

The data class is setup as:

```<code>data class PoolData(
    val id: String,
    val date_time: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val target_temperature: String,
    val status_changed: String
)

</code>```

Thanks.

答:
You need to create two classes. First for the array and second for the JSON object which is present in the array.

For array

```<code>class Data : ArrayList<DataItem>()
//Ignore class name
</code>```

For JSON object

```<code>data class DataItem(
    val date_time: String,
    val id: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val status_changed: String,
    val target_temperature: String
)
</code>```

If you don't want to create the data class on your own then in the android studio there is a plugin named JSON to Kotlin class.

Visit this link to know more
https://www.instagram.com/p/CW7UNzZj0gv/

Body:
I am just getting started with Android/Kotlin and I am having issues with something very basic. I use retrofit to return JSON:

[
  {
    "id": "45837",
    "date_time": "2022-02-02 12:50:06",
    "pool_filter_status": "0",
    "pool_temperature": "97.59",
    "target_temperature": "97.3",
    "status_changed": "1"
  }
]

In my viewmodel class, I have the following function that does retrieve the code from the server:

...

   private val _pooldata = MutableLiveData<List<PoolData>>()
   val pooldata: LiveData<List<PoolData>> = _pooldata

...

private fun getPoolData() {

        viewModelScope.launch {
            _status.value = PoolApiStatus.LOADING
            try {
                _pooldata.value = PoolDataApi.retrofitService.getPoolData()
                _status.value = PoolApiStatus.DONE
            } catch (e: Exception) {
                _status.value = PoolApiStatus.ERROR

            }

        }

    }

For what its worth, its always just a single JSON object (though its in a single element array)

My really dumb question is how to access the properties of the data object / returned JSON.

If I log _pooldata.value.toString(), I just get:

[PoolData(id=45833, date_time=2022-02-02 12:30:02, pool_filter_status=1, pool_temperature=96.91, target_temperature=97.3, status_changed=0)]

I am just trying to understand Kotlin "by doing" at this point, but I don't understand how to access those values (id, date_time, etc). its not _pooldata.id.value, _pooldata[0].id.value etc.

The data class is setup as:

data class PoolData(
    val id: String,
    val date_time: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val target_temperature: String,
    val status_changed: String
)

Thanks.

Body:
You need to create two classes. First for the array and second for the JSON object which is present in the array.

For array

class Data : ArrayList<DataItem>()
//Ignore class name

For JSON object

data class DataItem(
    val date_time: String,
    val id: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val status_changed: String,
    val target_temperature: String
)

If you don't want to create the data class on your own then in the android studio there is a plugin named JSON to Kotlin class.

Visit this link to know more
https://www.instagram.com/p/CW7UNzZj0gv/


问:
Scala - what is this map + case syntax?
I can't seem to find further information on this language feature where you can put a case inside a map like this:

```<code>   val sVersion = CrossVersion.partialVersion(scalaVersion)
      .map { case (major:Long, minor: Long) => s"_$major.$minor" } getOrElse ""
</code>```

I've been starting to use this syntax, but what is it called and where can I find more information on it?

答:
In Scala 2, it's called  pattern-matching decomposition

see: https://docs.scala-lang.org/scala3/reference/other-new-features/parameter-untupling.html

in Scala 3, you can just

val sVersion = CrossVersion.partialVersion(scalaVersion)
      .map { (major:Long, minor: Long) => s"_$major.$minor" } getOrElse ""
```

Title: Scala - what is this map + case syntax?

Body:
I can't seem to find further information on this language feature where you can put a case inside a map like this:

   val sVersion = CrossVersion.partialVersion(scalaVersion)
      .map { case (major:Long, minor: Long) => s"_$major.$minor" } getOrElse ""

I've been starting to use this syntax, but what is it called and where can I find more information on it?


问:
How to remove stop words from dataframe, pyspark or sql?
So for instance I have this dataframe.

```<code>data = Seq(("Novelist Sparks turns screenwriter with this film, which combines his usual themes (beaches, grieving teens, cancer) as a vehicle for Cyrus to put her childhood career behind her. It's exactly what we expect, but it's also fairly watchable."))
df = data.toDF("sentence")
</code>```

What I want to do is remove all stop words from this row or column value and count the words after removing stop words.

pyspark or sql code example, both are good.

答:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First we start with a test Pandas DataFrame:

import pandas as pd

df = pd.DataFrame({"id": [1,2,3], "sentences": ["this is sentence one.", "this is sentence two.", "this is sentence three"]})
```
<p>Then we create a pandas-based function to handle stopwords</p>
<pre class="lang-py prettyprint-override"><code>def process(df:pd.DataFrame) -> pd.DataFrame:
    from nltk.corpus import stopwords
    from nltk.tokenize import word_tokenize
    stop = set(stopwords.words('english'))
    df['processed_sentences'] = df['sentences'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)])
    return df
</code>```

If you want to count the words, just add it as another column. Now we can bring this function to Fugue and test it.

from fugue import transform
transform(df, process, schema="*, processed_sentences:str")
```
<p>Now that we see it works, we can use it on Spark by specifying the engine</p>
<pre class="lang-py prettyprint-override"><code>import fugue_spark
transform(df, process, schema="*, processed_sentences:str", engine="spark").show()
</code>```

Note .show() is needed because of Spark's lazy evaluation.
The output is:

```<code>+---+--------------------+-------------------+
| id|           sentences|processed_sentences|
+---+--------------------+-------------------+
|  1|this is sentence ...|      sentence one.|
|  2|this is sentence ...|      sentence two.|
|  3|this is sentence ...|     sentence three|
+---+--------------------+-------------------+
</code>```

The Fugue transform function can take in a Pandas DataFrame or Spark DataFrame, and it will output a Spark DataFrame if you are using the Spark engine.

I think you have to import the nltk.corpus inside the function so that it is executed on the workers rather than the driver. You need nltk installed on the workers because they need access to stopwords.words.

Body:
So for instance I have this dataframe.

data = Seq(("Novelist Sparks turns screenwriter with this film, which combines his usual themes (beaches, grieving teens, cancer) as a vehicle for Cyrus to put her childhood career behind her. It's exactly what we expect, but it's also fairly watchable."))
df = data.toDF("sentence")

What I want to do is remove all stop words from this row or column value and count the words after removing stop words.

pyspark or sql code example, both are good.

Body:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First we start with a test Pandas DataFrame:

import pandas as pd

df = pd.DataFrame({"id": [1,2,3], "sentences": ["this is sentence one.", "this is sentence two.", "this is sentence three"]})

Then we create a pandas-based function to handle stopwords

def process(df:pd.DataFrame) -> pd.DataFrame:
    from nltk.corpus import stopwords
    from nltk.tokenize import word_tokenize
    stop = set(stopwords.words('english'))
    df['processed_sentences'] = df['sentences'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)])
    return df

If you want to count the words, just add it as another column. Now we can bring this function to Fugue and test it.

from fugue import transform
transform(df, process, schema="*, processed_sentences:str")

Now that we see it works, we can use it on Spark by specifying the engine

import fugue_spark
transform(df, process, schema="*, processed_sentences:str", engine="spark").show()

Note .show() is needed because of Spark's lazy evaluation.
The output is:

+---+--------------------+-------------------+
| id|           sentences|processed_sentences|
+---+--------------------+-------------------+
|  1|this is sentence ...|      sentence one.|
|  2|this is sentence ...|      sentence two.|
|  3|this is sentence ...|     sentence three|
+---+--------------------+-------------------+

The Fugue transform function can take in a Pandas DataFrame or Spark DataFrame, and it will output a Spark DataFrame if you are using the Spark engine.

I think you have to import the nltk.corpus inside the function so that it is executed on the workers rather than the driver. You need nltk installed on the workers because they need access to stopwords.words.


问:
Fixing hook call outside of the body of a function component
I made a custom ReactJS hook to handle a couple of specific mouse events, as below:

```<code>const HealthcareServices = ({
  filterToRemove,
  filters,
  onChange,
  onClear,
  selectedAmbulatoryCareFilterValue,
  shouldClear,
}: Props): JSX.Element => {
  const classes = useStyles();
  ...

  useEffect(() => {
    shouldClear && clearFilters();
  }, [shouldClear]);

  const useSingleAndDoubleClick = (actionSimpleClick: () => void, actionDoubleClick: () => void, delay = 250) => {
    const [click, setClick] = useState(0);

    useEffect(() => {
      const timer = setTimeout(() => {
        // simple click
        if (click === 1) actionSimpleClick();
        setClick(0);
      }, delay);

      // the duration between this click and the previous one
      // is less than the value of delay = double-click
      if (click === 2) actionDoubleClick();

      return () => clearTimeout(timer);
    }, [click]);

    return () => setClick((prev) => prev + 1);
  };

  const handleSelectedItem = (service: Filter) => {
    service.selected = !service.selected;
    setHealthcareServices([...healthcareServices]);
    onChange(healthcareServices);
  };

  const handleSingleClick = (service: Filter) => {
    console.log('single-click');
    if (service.isRequired) {
      service.checkedIcon = <Icons.CheckboxSingleClick />;
    }
    handleSelectedItem(service);
  };

  const handleDoubleClick = (service: Filter) => {
    console.log('double-click');
    if (service.isRequired) {
      service.checkedIcon = <Icons.CheckboxDoubleClick />;
    }
    handleSelectedItem(service);
  };

  const handleClick = (service: Filter) =>
    useSingleAndDoubleClick(
      () => handleSingleClick(service),
      () => handleDoubleClick(service)
    );
  ...

  return (
    <div className={classes.filter_container}>
      ...
      <div className={classes.filter_subgroup}>
        {filters.map((filter) => (
          <div key={`${filter.label}-${filter.value}`} className={classes.filter}>
            <Checkbox
              label={filter.label}
              className={classes.checkbox}
              checked={filter.selected}
              onChange={() => handleClick(filter)}
              checkedIcon={filter.checkedIcon}
            />
          </div>
        ))}
      </div>
      ...
    </div>
  );
};
</code>```

When I click on my <Checkbox />, the whole thing crashes. The error is:

The top of my stacktrace points to useState inside my hook. If I move it outside, so the hook looks as:

```<code>const [click, setClick] = useState(0);

const useSingleAndDoubleClick = (actionSimpleClick: () => void, actionDoubleClick: () => void, delay = 250) => {

    useEffect(() => {
      const timer = setTimeout(() => {
        // simple click
        if (click === 1) actionSimpleClick();
        setClick(0);
      }, delay);

      // the duration between this click and the previous one
      // is less than the value of delay = double-click
      if (click === 2) actionDoubleClick();

      return () => clearTimeout(timer);
    }, [click]);

    return () => setClick((prev) => prev + 1);
  };
</code>```

The problem still happens, only the stacktrace points to the useEffect hook. The code is based on another answer here.

Any suggestions?

答:
You've defined your useSingleAndDoubleClick hook inside of a component. That's not what you want to do. The idea of custom hooks is that you can move logic outside of your components that could otherwise only happen inside of them. This helps with code reuse.

There is no use for a hook being defined inside a function, as the magic of hooks is that they give you access to state variables and such things that are usually only allowed to be interacted with inside function components.

You either need to define your hook outside the component and call it inside the component, or remove the definition of useSingleAndDoubleClick and just do everything inside the component.

EDIT: One more note to help clarify: the rule that you've really broken here is that you've called other hooks (ie, useState, useEffect) inside your useSingleAndDoubleClick function. Even though it's called useSingleAndDoubleClick, it's not actually a hook, because it's not being created or called like a hook. Therefore, you are not allowed to call other hooks inside of it.

EDIT: I mentioned this earlier, but here's an example that could work of moving the hook definition outside the function:

EDIT: Also had to change where you call the hook: you can't call the hook in a nested function, but I don't think you need to.

```<code>const useSingleAndDoubleClick = (actionSimpleClick: () => void, actionDoubleClick: () => void, delay = 250) => {
    const [click, setClick] = useState(0);

    useEffect(() => {
      const timer = setTimeout(() => {
        // simple click
        if (click === 1) actionSimpleClick();
        setClick(0);
      }, delay);

      // the duration between this click and the previous one
      // is less than the value of delay = double-click
      if (click === 2) actionDoubleClick();

      return () => clearTimeout(timer);
    }, [click]);

    return () => setClick((prev) => prev + 1);
  };

const HealthcareServices = ({
  filterToRemove,
  filters,
  onChange,
  onClear,
  selectedAmbulatoryCareFilterValue,
  shouldClear,
}: Props): JSX.Element => {
  const classes = useStyles();
  ...

  useEffect(() => {
    shouldClear && clearFilters();
  }, [shouldClear]);
  // your other handlers

  // changed this - don't call the hook inside the function.
  // your hook is returning the handler you want anyways, I think
  const handleClick = useSingleAndDoubleClick(handleSingleClick, handleDoubleClick)
</code>```

Body:
I made a custom ReactJS hook to handle a couple of specific mouse events, as below:

const HealthcareServices = ({
  filterToRemove,
  filters,
  onChange,
  onClear,
  selectedAmbulatoryCareFilterValue,
  shouldClear,
}: Props): JSX.Element => {
  const classes = useStyles();
  ...

  useEffect(() => {
    shouldClear && clearFilters();
  }, [shouldClear]);

  const useSingleAndDoubleClick = (actionSimpleClick: () => void, actionDoubleClick: () => void, delay = 250) => {
    const [click, setClick] = useState(0);

    useEffect(() => {
      const timer = setTimeout(() => {
        // simple click
        if (click === 1) actionSimpleClick();
        setClick(0);
      }, delay);

      // the duration between this click and the previous one
      // is less than the value of delay = double-click
      if (click === 2) actionDoubleClick();

      return () => clearTimeout(timer);
    }, [click]);

    return () => setClick((prev) => prev + 1);
  };

  const handleSelectedItem = (service: Filter) => {
    service.selected = !service.selected;
    setHealthcareServices([...healthcareServices]);
    onChange(healthcareServices);
  };

  const handleSingleClick = (service: Filter) => {
    console.log('single-click');
    if (service.isRequired) {
      service.checkedIcon = <Icons.CheckboxSingleClick />;
    }
    handleSelectedItem(service);
  };

  const handleDoubleClick = (service: Filter) => {
    console.log('double-click');
    if (service.isRequired) {
      service.checkedIcon = <Icons.CheckboxDoubleClick />;
    }
    handleSelectedItem(service);
  };

  const handleClick = (service: Filter) =>
    useSingleAndDoubleClick(
      () => handleSingleClick(service),
      () => handleDoubleClick(service)
    );
  ...

  return (

      ...

        {filters.map((filter) => (
          <div key={`${filter.label}-${filter.value}`} className={classes.filter}>
            <Checkbox
              label={filter.label}
              className={classes.checkbox}
              checked={filter.selected}
              onChange={() => handleClick(filter)}
              checkedIcon={filter.checkedIcon}
            />

        ))}

      ...

  );
};

When I click on my <Checkbox />, the whole thing crashes. The error is:

The top of my stacktrace points to useState inside my hook. If I move it outside, so the hook looks as:

const [click, setClick] = useState(0);

const useSingleAndDoubleClick = (actionSimpleClick: () => void, actionDoubleClick: () => void, delay = 250) => {

    useEffect(() => {
      const timer = setTimeout(() => {
        // simple click
        if (click === 1) actionSimpleClick();
        setClick(0);
      }, delay);

      // the duration between this click and the previous one
      // is less than the value of delay = double-click
      if (click === 2) actionDoubleClick();

      return () => clearTimeout(timer);
    }, [click]);

    return () => setClick((prev) => prev + 1);
  };

The problem still happens, only the stacktrace points to the useEffect hook. The code is based on another answer here.

Any suggestions?

Body:
You've defined your useSingleAndDoubleClick hook inside of a component. That's not what you want to do. The idea of custom hooks is that you can move logic outside of your components that could otherwise only happen inside of them. This helps with code reuse.

There is no use for a hook being defined inside a function, as the magic of hooks is that they give you access to state variables and such things that are usually only allowed to be interacted with inside function components.

You either need to define your hook outside the component and call it inside the component, or remove the definition of useSingleAndDoubleClick and just do everything inside the component.

EDIT: One more note to help clarify: the rule that you've really broken here is that you've called other hooks (ie, useState, useEffect) inside your useSingleAndDoubleClick function. Even though it's called useSingleAndDoubleClick, it's not actually a hook, because it's not being created or called like a hook. Therefore, you are not allowed to call other hooks inside of it.

EDIT: I mentioned this earlier, but here's an example that could work of moving the hook definition outside the function:

EDIT: Also had to change where you call the hook: you can't call the hook in a nested function, but I don't think you need to.

const useSingleAndDoubleClick = (actionSimpleClick: () => void, actionDoubleClick: () => void, delay = 250) => {
    const [click, setClick] = useState(0);

    useEffect(() => {
      const timer = setTimeout(() => {
        // simple click
        if (click === 1) actionSimpleClick();
        setClick(0);
      }, delay);

      // the duration between this click and the previous one
      // is less than the value of delay = double-click
      if (click === 2) actionDoubleClick();

      return () => clearTimeout(timer);
    }, [click]);

    return () => setClick((prev) => prev + 1);
  };

const HealthcareServices = ({
  filterToRemove,
  filters,
  onChange,
  onClear,
  selectedAmbulatoryCareFilterValue,
  shouldClear,
}: Props): JSX.Element => {
  const classes = useStyles();
  ...

  useEffect(() => {
    shouldClear && clearFilters();
  }, [shouldClear]);
  // your other handlers

  // changed this - don't call the hook inside the function.
  // your hook is returning the handler you want anyways, I think
  const handleClick = useSingleAndDoubleClick(handleSingleClick, handleDoubleClick)


问:
Breaking down np.where with nested for-loop and if/else statement
Write Python code equivalent to the following:

```<code>even_odd = np.where(h % 2 == 0, 'even', 'odd')
</code>```

You should use nested for-loop and if/else statement.

You can start your code as the below:

```<code>even_odd = np.empty_like(h, dtype="<U4")

  for i in range(h.shape[0]): # i is row index

  for j in range(h.shape[1]): # j is column index
</code>```

You should get the results below:

```<code>array([['even', 'odd', 'even'],
       ['odd', 'even', 'odd'],
       ['even', 'odd', 'even'],
       ['odd', 'even', 'odd'],
   ['even', 'odd', 'even']], dtype='<U4')
</code>```

My Code Input:

even_odd = np.empty_like(h, dtype="<U4")
for i in range(h.shape[0]):
  for j in range(h.shape[1]):
    if (h[i, j] % 2 == 0):
      h[i, j]
    else:
      h[i, j]
```
<p>Output:</p>
```even_odd

array([['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', '']], dtype='<U4')
```
<p>I am trying to breakdown the code but cannot seem to find the solution. I am confused on how to get "even" or "odd" to show up on my array.</p>
<p>Under my if/else statement, I tried print("even") and print("odd") but I get the list above the array as my output:</p>
```even
odd
even
odd
even
odd
even
odd
even
odd
even
odd
even
odd
even
array([['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', '']], dtype='<U4')
```

I feel like I am close as I simply need to find a way to get the list content in the array.
I researched similar questions on here but all of them seem to be from going from for-loop and if/else statement to np.where, I am trying to do the opposite.

Any insight/help would be greatly appreciated, trying to master the basics!

答:
You forgot to assign values to your matrix!

even_odd = np.empty_like(h, dtype="<U4")
for i in range(h.shape[0]):
 for j in range(h.shape[1]):
  if (h[i, j] % 2 == 0):
    even_odd[i, j]='even'
  else:
    even_odd[i, j]='odd'
print(even_odd)
```

Body:
Write Python code equivalent to the following:

even_odd = np.where(h % 2 == 0, 'even', 'odd')

You should use nested for-loop and if/else statement.

You can start your code as the below:

even_odd = np.empty_like(h, dtype="<U4")

  for i in range(h.shape[0]): # i is row index

  for j in range(h.shape[1]): # j is column index

You should get the results below:

array([['even', 'odd', 'even'],
       ['odd', 'even', 'odd'],
       ['even', 'odd', 'even'],
       ['odd', 'even', 'odd'],
   ['even', 'odd', 'even']], dtype='<U4')

My Code Input:

even_odd = np.empty_like(h, dtype="<U4")
for i in range(h.shape[0]):
  for j in range(h.shape[1]):
    if (h[i, j] % 2 == 0):
      h[i, j]
    else:
      h[i, j]

Output:

even_odd

array([['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', '']], dtype='<U4')

I am trying to breakdown the code but cannot seem to find the solution. I am confused on how to get "even" or "odd" to show up on my array.

Under my if/else statement, I tried print("even") and print("odd") but I get the list above the array as my output:

even
odd
even
odd
even
odd
even
odd
even
odd
even
odd
even
odd
even
array([['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', ''],
       ['', '', '']], dtype='<U4')

I feel like I am close as I simply need to find a way to get the list content in the array.
I researched similar questions on here but all of them seem to be from going from for-loop and if/else statement to np.where, I am trying to do the opposite.

Any insight/help would be greatly appreciated, trying to master the basics!


问:
SQL query to derive average sale of an item
Below are two tables. An item is being sold at different values during different periods. I need to calculate average sale of the item. I need to come to an optimal working query. I think the trick would be to map each sales date with their start_date and end_date and multiply the quatity with their respective price for that period and then derive the avergae using the formula total sales amount/ total quatity.

CREATE TABLE sales(
 item_id varchar(255) ,
 start_date date ,
 end_date date,
 price int
) ;

insert into sales values
('mobile','2021-01-01','2021-01-05',500),
('mobile','2021-01-06','2021-01-09',400),
('mobile','2021-01-10','2021-01-15',900) ;

CREATE TABLE item(
 sales_id int,
 item_id varchar(255) ,
 sales_date date ,
 quatity int
) ;

insert into item values
(101,'mobile','2021-01-01',10),
(102,'mobile','2021-01-06',20),
(103,'mobile','2021-01-15',30) ;
```

答:
```<code>            select item_id, sum(total_amount)/sum(quatity) avg_price from
            (
            select s.item_id, s.price, i.quatity, s.price * i.quatity as total_amount
            from sales s, item i where i.item_id = s.item_id
            and i.sales_date between s.start_date and s.end_date
            ) as A
            group by item_id;
</code>```


问:
Compiling 32 Bit Application on 64 Bit Linux
I'm trying to compile a program for 32 bit on a 64 bit Kali Linux operating system.

Here is my system information:

```<code>root@kali:~/Desktop# cat /proc/version
Linux version 3.18.0-kali3-amd64 (debian-kernel@lists.debian.org) (gcc version 4.7.2 (Debian 4.7.2-5) ) #1 SMP Debian 3.18.6-1~kali2 (2015-03-02)
</code>```

When I try to compile my C project, it cannot find -lgcc:

```<code>root@kali:~/Desktop/Project# make
cc -o libor libor.c -fno-stack-protector -z execstack -m32 -lpthread
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/4.7/libgcc.a when searching for -lgcc
/usr/bin/ld: cannot find -lgcc
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/4.7/libgcc_s.so when searching for -lgcc_s
/usr/bin/ld: cannot find -lgcc_s
collect2: error: ld returned 1 exit status
make: *** [all] Error 1
</code>```

Note that I'm using the -m32 flag to force compilation for 32 bit.

Like suggested elsewhere, the 32 bit libraries should be installed which I did using the following command:

```<code>sudo apt-get install libc6-dev-i386
</code>```

This however only changed the error message to the one seen above. I lost the previous one however I guess it no longer matters.

Please note that existing answers didn't help me so this is not a duplicate.

答:
The problem is you likely only have the gcc for your current architecture and that's 64bit. You need the 32bit support files. For that, you need to install them

```<code>sudo apt install gcc-multilib
</code>```

Once installed, run the below command to compile c-program to 32-bit binary executable

```<code>gcc -o libor libor.c -m32
</code>```

Verify the binary is 32-bit or not by

```<code>file libor
</code>```

Body:
I'm trying to compile a program for 32 bit on a 64 bit Kali Linux operating system.

Here is my system information:

root@kali:~/Desktop# cat /proc/version
Linux version 3.18.0-kali3-amd64 (debian-kernel@lists.debian.org) (gcc version 4.7.2 (Debian 4.7.2-5) ) #1 SMP Debian 3.18.6-1~kali2 (2015-03-02)

When I try to compile my C project, it cannot find -lgcc:

root@kali:~/Desktop/Project# make
cc -o libor libor.c -fno-stack-protector -z execstack -m32 -lpthread
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/4.7/libgcc.a when searching for -lgcc
/usr/bin/ld: cannot find -lgcc
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/4.7/libgcc_s.so when searching for -lgcc_s
/usr/bin/ld: cannot find -lgcc_s
collect2: error: ld returned 1 exit status
make: *** [all] Error 1

Note that I'm using the -m32 flag to force compilation for 32 bit.

Like suggested elsewhere, the 32 bit libraries should be installed which I did using the following command:

sudo apt-get install libc6-dev-i386

This however only changed the error message to the one seen above. I lost the previous one however I guess it no longer matters.

Please note that existing answers didn't help me so this is not a duplicate.

Body:
The problem is you likely only have the gcc for your current architecture and that's 64bit. You need the 32bit support files. For that, you need to install them

sudo apt install gcc-multilib

Once installed, run the below command to compile c-program to 32-bit binary executable

gcc -o libor libor.c -m32

Verify the binary is 32-bit or not by

file libor


问:
Python/increase code efficiency about multiple columns filter
I was wondering if someone could help me find a more efficiency way to run my code.

I have a dataset contains 7 columns, which are country,sector,year,month,week,weekday,value.

the year column have only 3 elements, 2019,2020,2021

What I have to do here is to substract every value in 2020 and 2021 from 2019.
But its more complicated that I need to match the weekday columns.

For example,i need to use year 2020, month 1, week 1, weekday 0(monday) value to substract,
year 2019, month 1, week 1, weekday 0(monday) value, if cant find it, it will pass, and so on, which means, the weekday(monday,Tuesaday....must be matched)

And here is my code, it can run, but it tooks me hours:(

```<code>for i in itertools.product(year_list,country_list, sector_list,month_list,week_list,weekday_list):
    try:
        data_2 = df_carbon[(df_carbon['country'] == i[1])
                  & (df_carbon['sector'] == i[2])
                  & (df_carbon['year'] == i[0])
                  & (df_carbon['month'] == i[3])
                  & (df_carbon['week'] == i[4])
                  & (df_carbon['weekday'] == i[5])]['co2'].tolist()[0]
        data_1 = df_carbon[(df_carbon['country'] == i[1])
                  & (df_carbon['sector'] == i[2])
                  & (df_carbon['year'] == 2019)
                  & (df_carbon['month'] == i[3])
                  & (df_carbon['week'] == i[4])
                  & (df_carbon['weekday'] == i[5])]['co2'].tolist()[0]
        co2.append(data_2-data_1)
        country.append(i[1])
        sector.append(i[2])
        year.append(i[0])
        month.append(i[3])
        week.append(i[4])
        weekday.append(i[5])
    except:
        pass

</code>```

I changed the for loops to itertools, but it still not fast enough, any other ideas?
many thanks:)

##############################
here is the sample dataset

```<code>
    country  co2  sector  date  week  weekday  year  month
    Brazil  108.767782  Power   2019-01-01  0   1   2019    1
    China   14251.044482    Power   2019-01-01  0   1   2019    1
    EU27 & UK   1886.493814  Power  2019-01-01  0   1   2019    1
    France  53.856398   Power   2019-01-01  0   1   2019    1
    Germany  378.323440  Power   2019-01-01  0   1   2019    1
    Japan   21.898788   IA  2021-11-30  48  1   2021    11
    Russia  19.773822   IA  2021-11-30  48  1   2021    11
    Spain   42.293944   IA  2021-11-30  48  1   2021    11
    UK  56.425121   IA  2021-11-30  48  1   2021    11
    US  166.425000  IA  2021-11-30  48  1   2021    11
</code>```

or this

```<code>import pandas as pd
pd.DataFrame({
    'year': [2019, 2020, 2021],
    'co2': [1,2,3],
    'country': ['Brazil', 'Brazil', 'Brazil'],
    'sector': ['power', 'power', 'power'],
    'month': [1, 1, 1],
    'week': [0,0,0],
    'weekday': [0,0,0]
})
</code>```

答:
pandas can subtract two dataframe index-by-index, so the idea would be to separate your data into a minuend and a subtrahend, set ['country', 'sector', 'month', 'week', 'weekday'] as their indices, just subtract them, and remove rows (by dropna) where a match in year 2019 is not found.

```<code>df_carbon = pd.DataFrame({
    'year': [2019, 2020, 2021],
    'co2': [1,2,3],
    'country': ['ab', 'ab', 'bc']
})

index = ['country']
# index = ['country', 'sector', 'month', 'week', 'weekday']

df_2019 = df_carbon[df_carbon['year']==2019].set_index(index)
df_rest = df_carbon[df_carbon['year']!=2019].set_index(index)

ans = (df_rest - df_2019).reset_index().dropna()
ans['year'] += 2019
</code>```

Two additional points:

In this subtraction the year is also covered, so I need to add 2019 back.

I created a small example of df_carbon to test my code. If you had provided a more realistic version in text form, I would have tested my code using your data.

Body:
I was wondering if someone could help me find a more efficiency way to run my code.

I have a dataset contains 7 columns, which are country,sector,year,month,week,weekday,value.

the year column have only 3 elements, 2019,2020,2021

What I have to do here is to substract every value in 2020 and 2021 from 2019.
But its more complicated that I need to match the weekday columns.

For example,i need to use year 2020, month 1, week 1, weekday 0(monday) value to substract,
year 2019, month 1, week 1, weekday 0(monday) value, if cant find it, it will pass, and so on, which means, the weekday(monday,Tuesaday....must be matched)

And here is my code, it can run, but it tooks me hours:(

for i in itertools.product(year_list,country_list, sector_list,month_list,week_list,weekday_list):
    try:
        data_2 = df_carbon[(df_carbon['country'] == i[1])
                  & (df_carbon['sector'] == i[2])
                  & (df_carbon['year'] == i[0])
                  & (df_carbon['month'] == i[3])
                  & (df_carbon['week'] == i[4])
                  & (df_carbon['weekday'] == i[5])]['co2'].tolist()[0]
        data_1 = df_carbon[(df_carbon['country'] == i[1])
                  & (df_carbon['sector'] == i[2])
                  & (df_carbon['year'] == 2019)
                  & (df_carbon['month'] == i[3])
                  & (df_carbon['week'] == i[4])
                  & (df_carbon['weekday'] == i[5])]['co2'].tolist()[0]
        co2.append(data_2-data_1)
        country.append(i[1])
        sector.append(i[2])
        year.append(i[0])
        month.append(i[3])
        week.append(i[4])
        weekday.append(i[5])
    except:
        pass

I changed the for loops to itertools, but it still not fast enough, any other ideas?
many thanks:)

##############################
here is the sample dataset

    country  co2  sector  date  week  weekday  year  month
    Brazil  108.767782  Power   2019-01-01  0   1   2019    1
    China   14251.044482    Power   2019-01-01  0   1   2019    1
    EU27 & UK   1886.493814  Power  2019-01-01  0   1   2019    1
    France  53.856398   Power   2019-01-01  0   1   2019    1
    Germany  378.323440  Power   2019-01-01  0   1   2019    1
    Japan   21.898788   IA  2021-11-30  48  1   2021    11
    Russia  19.773822   IA  2021-11-30  48  1   2021    11
    Spain   42.293944   IA  2021-11-30  48  1   2021    11
    UK  56.425121   IA  2021-11-30  48  1   2021    11
    US  166.425000  IA  2021-11-30  48  1   2021    11

or this

import pandas as pd
pd.DataFrame({
    'year': [2019, 2020, 2021],
    'co2': [1,2,3],
    'country': ['Brazil', 'Brazil', 'Brazil'],
    'sector': ['power', 'power', 'power'],
    'month': [1, 1, 1],
    'week': [0,0,0],
    'weekday': [0,0,0]
})

Body:
pandas can subtract two dataframe index-by-index, so the idea would be to separate your data into a minuend and a subtrahend, set ['country', 'sector', 'month', 'week', 'weekday'] as their indices, just subtract them, and remove rows (by dropna) where a match in year 2019 is not found.

df_carbon = pd.DataFrame({
    'year': [2019, 2020, 2021],
    'co2': [1,2,3],
    'country': ['ab', 'ab', 'bc']
})

index = ['country']
# index = ['country', 'sector', 'month', 'week', 'weekday']

df_2019 = df_carbon[df_carbon['year']==2019].set_index(index)
df_rest = df_carbon[df_carbon['year']!=2019].set_index(index)

ans = (df_rest - df_2019).reset_index().dropna()
ans['year'] += 2019

Two additional points:

In this subtraction the year is also covered, so I need to add 2019 back.

I created a small example of df_carbon to test my code. If you had provided a more realistic version in text form, I would have tested my code using your data.


问:
Timestamp guest/user added to Office365 group
How to find when and by whom a user was added to a Office365 group/SharePoint.

Audit gave no activity of a specified user or the SharePoint folder.

Case: A user was added tot a Office365 Group. we don't know by whom. There is only one group owner and a tenant administrator can add a member.

答:
I have tested in my environment

You can check the details of when and by whom the user is added to office 365 group by below options:

Login to Azure Active Directory --> Under Groups, select the group in which the user is added --> Go to Audit Logs

You can check the details of when and by whom the user is added to office 365 group

Login to Graph Explorer and run the below query:

GET https://graph.microsoft.com/v1.0/auditLogs/directoryAudits


问:
pre decrement operator not working in dart null safety
```<code>if (cart.quantity! > 1) {
  --cart.quantity;
</code>```

this block of code works in previous flutter version after migrate to null safety it's not working anymore. How to properly write pre decrement operator in dart null safety

答:
```<code>    if (cart.quantity! > 1) {
  cart.quantity = cart.quantity! - 1}
</code>```

Body:
if (cart.quantity! > 1) {
  --cart.quantity;

this block of code works in previous flutter version after migrate to null safety it's not working anymore. How to properly write pre decrement operator in dart null safety