问:
Android - AlarmManager is not triggered on a device with api 29
I am developing an android application that aims to obtain the location of the cell phone. I am using AlarmManager to, repeatedly, trigger the BroadcastReceiver that obtains the coordinates. Everything worked fine when I ran on the virtual device with api 23. But when I tried to run on the virtual device with api 29 the alarm is not triggered, nothing happens. The same wrong behavior happens when I run the application on a real device (Xiaomi) with api 29. Below is all the implemented code. Can anyone help me fix this problem?

Thank you!

build.gradle (:app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "br.com.detectx.android.locator"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'br.com.detectx.android:celulatronco-android:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.detectx.android.locator">

    <uses-permission android:name="android.permission.INTERNET" android:required="true"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" android:required="true"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" android:required="true"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" android:required="true"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:required="true"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:required="true"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" 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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver android:name="br.com.detectx.android.locator.receiver.GPSReciver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>
</code>```

LocationTracker.java

```<code>public class LocationTracker extends Service implements LocationListener {

    public static final String TAG = "LocationTracker";
    private static final long MIN_TIME_BW_UPDATES = 60000;
    private final Context mContext;
    private Location location = null;
    private double latitude;
    private double longitude;

    public LocationTracker(Context context) {
        this.mContext = context;
        Log.e("Get", "GPS");
        updateLocation();
    }

    public void onCreate() {
        super.onCreate();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_NOT_STICKY;
    }

    public void updateLocation() {
        try {
            LocationManager locationManager = (LocationManager) this.mContext.getSystemService(Context.LOCATION_SERVICE);
            boolean gpsEnabled = locationManager.isProviderEnabled("gps");
            boolean networkEnabled = locationManager.isProviderEnabled("network");
            if (!gpsEnabled && !networkEnabled) {
                Log.i(TAG, "no network provider is enabled");
            } else {
                if (networkEnabled) {
                    if (ActivityCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        Log.e(TAG, "Not allowed to ACCESS_FINE_LOCATION");
                        return;
                    }
                    locationManager.requestLocationUpdates("network", MIN_TIME_BW_UPDATES, 30.0f, this);
                    Log.d("Network", "G");
                    if (locationManager != null) {
                        this.location = locationManager.getLastKnownLocation("network");
                        if (this.location != null) {
                            this.latitude = this.location.getLatitude();
                            this.longitude = this.location.getLongitude();
                        }
                    }
                } else if (gpsEnabled) {
                    if (this.location == null) {
                        locationManager.requestLocationUpdates("gps", MIN_TIME_BW_UPDATES, 30.0f, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            this.location = locationManager.getLastKnownLocation("gps");
                            if (this.location != null) {
                                this.latitude = this.location.getLatitude();
                                this.longitude = this.location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public double getLatitude() {
        Location location = this.location;
        if (location != null) {
            this.latitude = location.getLatitude();
        }
        return this.latitude;
    }

    public double getLongitude() {
        Location location = this.location;
        if (location != null) {
            this.longitude = location.getLongitude();
        }
        return this.longitude;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
        this.latitude = location.getLatitude();
        this.longitude = location.getLongitude();
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

}
</code>```

GPSReciver.java

```<code>public class GPSReciver extends BroadcastReceiver {

    private static final String TAG = "GPSReciver";

    @Override
    public void onReceive(Context context, Intent intent) {
        LocationTracker gps = new LocationTracker(context);
        String slat = String.valueOf(gps.getLatitude());
        String slon = String.valueOf(gps.getLongitude());
        Log.i(TAG, String.format("lat: %s", slat));
        Log.i(TAG, String.format("lon: %s", slon));
        if (!slat.equals("0.0") && !slon.equals("0.0")) {
            //TODO
        }

    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

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

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, ConstantsApp.PERMISSIONS_REQUEST_READ_PHONE_STATE);
        }

    }

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case ConstantsApp.PERMISSIONS_REQUEST_READ_PHONE_STATE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ConstantsApp.PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
            } else {
                finish();
            }
            return;
        }
        case ConstantsApp.PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ConstantsApp.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            } else {
                finish();
            }
            return;
        }
        case ConstantsApp.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT < 29) {
                    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (long) 300000, PendingIntent.getBroadcast(this, 0, new Intent(this, GPSReciver.class), 0));
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, ConstantsApp.PERMISSIONS_REQUEST_ACCESS_BACKGROUND_LOCATION);
                }
            } else {
                finish();
            }
            return;
        }
        case ConstantsApp.PERMISSIONS_REQUEST_ACCESS_BACKGROUND_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (long) 300000, PendingIntent.getBroadcast(this, 0, new Intent(this, GPSReciver.class), 0));
            } else {
                finish();
            }
            return;
        }
    }
}
</code>```

}

答:
For API 29+ you need a new permission to access the location in background.

From the docs,

If your app targets Android 10 (API level 29) or higher, also check for the ACCESS_BACKGROUND_LOCATION

Reference

Body:
I am developing an android application that aims to obtain the location of the cell phone. I am using AlarmManager to, repeatedly, trigger the BroadcastReceiver that obtains the coordinates. Everything worked fine when I ran on the virtual device with api 23. But when I tried to run on the virtual device with api 29 the alarm is not triggered, nothing happens. The same wrong behavior happens when I run the application on a real device (Xiaomi) with api 29. Below is all the implemented code. Can anyone help me fix this problem?

Thank you!

build.gradle (:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "br.com.detectx.android.locator"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'br.com.detectx.android:celulatronco-android:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.detectx.android.locator">

    <uses-permission android:name="android.permission.INTERNET" android:required="true"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" android:required="true"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" android:required="true"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" android:required="true"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:required="true"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:required="true"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" 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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver android:name="br.com.detectx.android.locator.receiver.GPSReciver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>

LocationTracker.java

public class LocationTracker extends Service implements LocationListener {

    public static final String TAG = "LocationTracker";
    private static final long MIN_TIME_BW_UPDATES = 60000;
    private final Context mContext;
    private Location location = null;
    private double latitude;
    private double longitude;

    public LocationTracker(Context context) {
        this.mContext = context;
        Log.e("Get", "GPS");
        updateLocation();
    }

    public void onCreate() {
        super.onCreate();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_NOT_STICKY;
    }

    public void updateLocation() {
        try {
            LocationManager locationManager = (LocationManager) this.mContext.getSystemService(Context.LOCATION_SERVICE);
            boolean gpsEnabled = locationManager.isProviderEnabled("gps");
            boolean networkEnabled = locationManager.isProviderEnabled("network");
            if (!gpsEnabled && !networkEnabled) {
                Log.i(TAG, "no network provider is enabled");
            } else {
                if (networkEnabled) {
                    if (ActivityCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        Log.e(TAG, "Not allowed to ACCESS_FINE_LOCATION");
                        return;
                    }
                    locationManager.requestLocationUpdates("network", MIN_TIME_BW_UPDATES, 30.0f, this);
                    Log.d("Network", "G");
                    if (locationManager != null) {
                        this.location = locationManager.getLastKnownLocation("network");
                        if (this.location != null) {
                            this.latitude = this.location.getLatitude();
                            this.longitude = this.location.getLongitude();
                        }
                    }
                } else if (gpsEnabled) {
                    if (this.location == null) {
                        locationManager.requestLocationUpdates("gps", MIN_TIME_BW_UPDATES, 30.0f, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            this.location = locationManager.getLastKnownLocation("gps");
                            if (this.location != null) {
                                this.latitude = this.location.getLatitude();
                                this.longitude = this.location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public double getLatitude() {
        Location location = this.location;
        if (location != null) {
            this.latitude = location.getLatitude();
        }
        return this.latitude;
    }

    public double getLongitude() {
        Location location = this.location;
        if (location != null) {
            this.longitude = location.getLongitude();
        }
        return this.longitude;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
        this.latitude = location.getLatitude();
        this.longitude = location.getLongitude();
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

}

GPSReciver.java

public class GPSReciver extends BroadcastReceiver {

    private static final String TAG = "GPSReciver";

    @Override
    public void onReceive(Context context, Intent intent) {
        LocationTracker gps = new LocationTracker(context);
        String slat = String.valueOf(gps.getLatitude());
        String slon = String.valueOf(gps.getLongitude());
        Log.i(TAG, String.format("lat: %s", slat));
        Log.i(TAG, String.format("lon: %s", slon));
        if (!slat.equals("0.0") && !slon.equals("0.0")) {
            //TODO
        }

    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

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

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, ConstantsApp.PERMISSIONS_REQUEST_READ_PHONE_STATE);
        }

    }

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case ConstantsApp.PERMISSIONS_REQUEST_READ_PHONE_STATE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ConstantsApp.PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
            } else {
                finish();
            }
            return;
        }
        case ConstantsApp.PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ConstantsApp.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            } else {
                finish();
            }
            return;
        }
        case ConstantsApp.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT < 29) {
                    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (long) 300000, PendingIntent.getBroadcast(this, 0, new Intent(this, GPSReciver.class), 0));
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, ConstantsApp.PERMISSIONS_REQUEST_ACCESS_BACKGROUND_LOCATION);
                }
            } else {
                finish();
            }
            return;
        }
        case ConstantsApp.PERMISSIONS_REQUEST_ACCESS_BACKGROUND_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (long) 300000, PendingIntent.getBroadcast(this, 0, new Intent(this, GPSReciver.class), 0));
            } else {
                finish();
            }
            return;
        }
    }
}

}


来源: stackexchange

问:
How can I create a SQL query for a NEW row based on each column?
I have a SQL table as follows:

```<code>name, email 1, email 2, email 3
John, john@example.com, info@example.com, hello@example.com
Mickey, mickey@disney.com, info@disney.com
</code>```

I want to create a query to create a row for each email.

So the output would look like:

```<code>John, john@example.com
John, info@example.com
John, hello@example.com
Mickey, mickey@disney.com
Mickey, info@disney.com
</code>```

How can I accomplish this?

答:
A database independent solution uses union all:

```<code>select name, email1 as email
from table1
where email1 is not null
union all
select name, email2 as email
from table1
where email2 is not null
union all
select name, email3 as email
from table1
where email3 is not null;
</code>```

This requires scanning the table three times, so it is not the most efficient solution.  However, it is fine for small or medium sized tables.  The best solution depends on the particular database you are using -- if performance is an issue.

ContentLicense: CC BY-SA 4.0

Body:
I have a SQL table as follows:

name, email 1, email 2, email 3
John, john@example.com, info@example.com, hello@example.com
Mickey, mickey@disney.com, info@disney.com

I want to create a query to create a row for each email.

So the output would look like:

John, john@example.com
John, info@example.com
John, hello@example.com
Mickey, mickey@disney.com
Mickey, info@disney.com

How can I accomplish this?

Body:
A database independent solution uses union all:

select name, email1 as email
from table1
where email1 is not null
union all
select name, email2 as email
from table1
where email2 is not null
union all
select name, email3 as email
from table1
where email3 is not null;

This requires scanning the table three times, so it is not the most efficient solution.  However, it is fine for small or medium sized tables.  The best solution depends on the particular database you are using -- if performance is an issue.


问:
Ansible Playbook passing array list as variable
so we currently have a create directories yml and it has 20 or so folders it creates..  I'm attempting to streamline that and pass in the folders with the mode and recurse flag which are all different.  As a test I created this.

```<code>- debug: msg="testing = {{ testing }}"
- name: "loop through list from a variable"
  debug:
    msg: "dest: {{ item.dest }}, mode: {{ item.mode }}, recurse: {{ item.recurse }}"
  with_items: "{{ testing }}"
</code>```

Normally we have something like this:

```<code>- name: Create Multiple Directories
  file:
    path: "{{ item.dest }}"
    mode: "{{ item.mode }}"
    recurse: "{{ item.recurse }}"
    state: directory
  with_items:
    - { dest: '/local/path1', mode: '0775', recurse: yes }
    - { dest: '/local/path2', mode: '0777', recurse: no }
</code>```

So my problem is we use AaaS to pass information over and how the parameter is set.. We have a TextBox on a web page.   I tried the following with no luck.

```<code>- { dest: '/local/path1', mode: '0775', recurse: yes }
- { dest: '/local/path2', mode: '0777', recurse: no }
</code>```

and

```<code>{ dest: '/local/path1', mode: '0775', recurse: yes }
{ dest: '/local/path2', mode: '0777', recurse: no }
</code>```

and

```<code>dest: '/local/path1', mode: '0775', recurse: yes
dest: '/local/path2', mode: '0777', recurse: no
</code>```

The error I'm getting in all cases states 'dest' does not exist.   Is it formatting or is there something else I need to consider?

答:
I don't have rep to make a comment, but i would think that the yaml you're sending in the first example is a list, but sending yaml via HTTP to an AaaS is difficult. You might try sending a JSON blob, so you can send:

```<code>[{"dest": "/local/path1", "mode": "0775", "recurse": true },
{"dest": "/local/path2", "mode": "0777", "recurse": false }]
</code>```

And that would probably make your life easier

EDIT: removed the single quotes as it's likely that a Text Box would be interpreted as a string already

Body:
so we currently have a create directories yml and it has 20 or so folders it creates..  I'm attempting to streamline that and pass in the folders with the mode and recurse flag which are all different.  As a test I created this.

- debug: msg="testing = {{ testing }}"
- name: "loop through list from a variable"
  debug:
    msg: "dest: {{ item.dest }}, mode: {{ item.mode }}, recurse: {{ item.recurse }}"
  with_items: "{{ testing }}"

Normally we have something like this:

- name: Create Multiple Directories
  file:
    path: "{{ item.dest }}"
    mode: "{{ item.mode }}"
    recurse: "{{ item.recurse }}"
    state: directory
  with_items:
    - { dest: '/local/path1', mode: '0775', recurse: yes }
    - { dest: '/local/path2', mode: '0777', recurse: no }

So my problem is we use AaaS to pass information over and how the parameter is set.. We have a TextBox on a web page.   I tried the following with no luck.

- { dest: '/local/path1', mode: '0775', recurse: yes }
- { dest: '/local/path2', mode: '0777', recurse: no }

and

{ dest: '/local/path1', mode: '0775', recurse: yes }
{ dest: '/local/path2', mode: '0777', recurse: no }

and

dest: '/local/path1', mode: '0775', recurse: yes
dest: '/local/path2', mode: '0777', recurse: no

The error I'm getting in all cases states 'dest' does not exist.   Is it formatting or is there something else I need to consider?

Body:
I don't have rep to make a comment, but i would think that the yaml you're sending in the first example is a list, but sending yaml via HTTP to an AaaS is difficult. You might try sending a JSON blob, so you can send:

[{"dest": "/local/path1", "mode": "0775", "recurse": true },
{"dest": "/local/path2", "mode": "0777", "recurse": false }]

And that would probably make your life easier

EDIT: removed the single quotes as it's likely that a Text Box would be interpreted as a string already


问:
Different states for UIButton not working
I have written this code to see different image states...

```<code>UIButton *btnComment = [UIButton buttonWithType:UIButtonTypeCustom];
btnComment.tag=indexPath.row;
[btnComment addTarget:self action:@selector(goToComment:)forControlEvents:UIControlEventTouchDown];

UIImage *img1 = [UIImage  imageNamed:@"commentbtndown.png"];
UIImage *img2 = [UIImage  imageNamed:@"commentbtnup.png"];
UIImage *img3 = [UIImage  imageNamed:@"commentbtnover.png"];

[btnComment setImage:img1 forState:UIControlStateNormal];
[btnComment setImage:img2 forState:UIControlStateHighlighted];
[btnComment setImage:img3 forState:UIControlStateSelected];
[btnComment setImage:img2 forState:(UIControlStateHighlighted+UIControlStateSelected)];

btnComment.frame            =CGRectMake(0, 100, 95, 25);
[cell addSubview:btnComment];

[img1 release];
[img2 release];
[img3 release];
</code>```

but its not working, it is always showing me image 1.

p.s. I have added these images in the table view cell

答:
The problem is that you are creating the UIImage objects with an autorelease method imageNamed, and you are releasing these objects afterwards, which cause your button to have invalid objects and because of that the images will not be displayed

Try removing this lines of code and your button will work

```<code>[img1 release];
[img2 release];
[img3 release];
</code>```

And also, if you want the button to receive the touch events, you will have to add it to the contentView of your cell object, otherwise the button will be shown but you will not be able to tap it.

```<code>[cell.contentView addSubview:btnComment]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have written this code to see different image states...

UIButton *btnComment = [UIButton buttonWithType:UIButtonTypeCustom];
btnComment.tag=indexPath.row;
[btnComment addTarget:self action:@selector(goToComment:)forControlEvents:UIControlEventTouchDown];

UIImage *img1 = [UIImage  imageNamed:@"commentbtndown.png"];
UIImage *img2 = [UIImage  imageNamed:@"commentbtnup.png"];
UIImage *img3 = [UIImage  imageNamed:@"commentbtnover.png"];

[btnComment setImage:img1 forState:UIControlStateNormal];
[btnComment setImage:img2 forState:UIControlStateHighlighted];
[btnComment setImage:img3 forState:UIControlStateSelected];
[btnComment setImage:img2 forState:(UIControlStateHighlighted+UIControlStateSelected)];

btnComment.frame            =CGRectMake(0, 100, 95, 25);
[cell addSubview:btnComment];

[img1 release];
[img2 release];
[img3 release];

but its not working, it is always showing me image 1.

p.s. I have added these images in the table view cell

Body:
The problem is that you are creating the UIImage objects with an autorelease method imageNamed, and you are releasing these objects afterwards, which cause your button to have invalid objects and because of that the images will not be displayed

Try removing this lines of code and your button will work

[img1 release];
[img2 release];
[img3 release];

And also, if you want the button to receive the touch events, you will have to add it to the contentView of your cell object, otherwise the button will be shown but you will not be able to tap it.

[cell.contentView addSubview:btnComment]


问:
Manipulating large dataset with dcast
Apologies if this is a repeat question but I could not find the specific answer I am looking for. I have a dataframe with counts of different species caught on a given trip. A simplified example with 5 trips and 4 species is below:

```<code>trip = c(1,1,1,2,2,3,3,3,3,4,5,5)
species = c("a","b","c","b","d","a","b","c","d","c","c","d")
count = c(5,7,3,1,8,10,1,4,3,1,2,10)

dat = cbind.data.frame(trip, species, count)
dat

> dat
   trip species count
1     1       a     5
2     1       b     7
3     1       c     3
4     2       b     1
5     2       d     8
6     3       a    10
7     3       b     1
8     3       c     4
9     3       d     3
10    4       c     1
11    5       c     2
12    5       d    10
</code>```

I am only interested in the counts of species b for each trip. So I want to manipulate this data frame so I end up with one that looks like this:

```<code>trip2 = c(1,2,3,4,5)
species2 = c("b","b","b","b","b")
count2 = c(7,1,1,0,0)

dat2 = cbind.data.frame(trip2, species2, count2)
dat2

> dat2
  trip2 species2 count2
1     1        b      7
2     2        b      1
3     3        b      1
4     4        b      0
5     5        b      0
</code>```

I want to keep all trips, including trips where species b was not observed. So I can't just subset the data by species b. I know I can cast the data so species are the columns and then just remove the columns for the other species like so:

```<code>library(dplyr)
library(reshape2)
test = dcast(dat, trip ~ species, value.var = "count", fun.aggregate = sum)
test

> test
  trip  a b c  d
1    1  5 7 3  0
2    2  0 1 0  8
3    3 10 1 4  3
4    4  0 0 1  0
5    5  0 0 2 10
</code>```

However, my real dataset has several hundred species caught on thousands of trips, and if I try to cast that many species to columns R  chokes. There are way too many columns. Is there a way to specify in dcast that I only want to cast species b? Or is there another way to do this that doesn't require casting the data? Thank you.

答:
We can use tidyverse

```<code>library(dplyr)
library(tidyr)
dat  %>%
   filter(species == 'b') %>%
   group_by(trip, species) %>%
   summarise(count = sum(count)) %>%
   ungroup %>%
   complete(trip = unique(dat$trip), fill = list(species = 'b', count = 0))
# A tibble: 5 x 3
#   trip species count
#  <dbl> <chr>   <dbl>
#1     1 b           7
#2     2 b           1
#3     3 b           1
#4     4 b           0
#5     5 b           0
</code>```

Title: Manipulating large dataset with dcast

Body:
Apologies if this is a repeat question but I could not find the specific answer I am looking for. I have a dataframe with counts of different species caught on a given trip. A simplified example with 5 trips and 4 species is below:

trip = c(1,1,1,2,2,3,3,3,3,4,5,5)
species = c("a","b","c","b","d","a","b","c","d","c","c","d")
count = c(5,7,3,1,8,10,1,4,3,1,2,10)

dat = cbind.data.frame(trip, species, count)
dat

> dat
   trip species count
1     1       a     5
2     1       b     7
3     1       c     3
4     2       b     1
5     2       d     8
6     3       a    10
7     3       b     1
8     3       c     4
9     3       d     3
10    4       c     1
11    5       c     2
12    5       d    10

I am only interested in the counts of species b for each trip. So I want to manipulate this data frame so I end up with one that looks like this:

trip2 = c(1,2,3,4,5)
species2 = c("b","b","b","b","b")
count2 = c(7,1,1,0,0)

dat2 = cbind.data.frame(trip2, species2, count2)
dat2

> dat2
  trip2 species2 count2
1     1        b      7
2     2        b      1
3     3        b      1
4     4        b      0
5     5        b      0

I want to keep all trips, including trips where species b was not observed. So I can't just subset the data by species b. I know I can cast the data so species are the columns and then just remove the columns for the other species like so:

library(dplyr)
library(reshape2)
test = dcast(dat, trip ~ species, value.var = "count", fun.aggregate = sum)
test

> test
  trip  a b c  d
1    1  5 7 3  0
2    2  0 1 0  8
3    3 10 1 4  3
4    4  0 0 1  0
5    5  0 0 2 10

However, my real dataset has several hundred species caught on thousands of trips, and if I try to cast that many species to columns R  chokes. There are way too many columns. Is there a way to specify in dcast that I only want to cast species b? Or is there another way to do this that doesn't require casting the data? Thank you.

Body:
We can use tidyverse

library(dplyr)
library(tidyr)
dat  %>%
   filter(species == 'b') %>%
   group_by(trip, species) %>%
   summarise(count = sum(count)) %>%
   ungroup %>%
   complete(trip = unique(dat$trip), fill = list(species = 'b', count = 0))
# A tibble: 5 x 3
#   trip species count
#  <dbl> <chr>   <dbl>
#1     1 b           7
#2     2 b           1
#3     3 b           1
#4     4 b           0
#5     5 b           0


问:
Configuring Cypress.env() variable to an imported module file
I'm trying to set & config a new env variable in Cypress.io. In the file cypress/plugins/index.js, I have imported another file like so:

```<code>const { getBranch } = require('path/to/file/goes/here/getBranch');
</code>```

Then, I'm trying to set the new env variable like so:

```<code>// cypress/plugins/index.js

module.exports = (on, config) => {
  terminalReport.installPlugin(on);

  const configuration = config;
  configuration.env.injectMainBranchId = getBranch('develop');

  // more code below...
</code>```

However, this is not working. However, if I hardcode the value it does work:

```<code>configuration.env.injectMainBranchId = 'develop';
</code>```

You see the result in the screenshot below:

This is the dummy content of getBranch module:

```<code>const getBranch = branch => {
  return branch;
};

module.export = { getBranch };
</code>```

What am I doing wrong?

答:
Typo in getBranch:

```<code>const getBranch = branch => {
  return branch;
};

module.export = { getBranch };
</code>```

export should be changed to exports

Body:
I'm trying to set & config a new env variable in Cypress.io. In the file cypress/plugins/index.js, I have imported another file like so:

const { getBranch } = require('path/to/file/goes/here/getBranch');

Then, I'm trying to set the new env variable like so:

// cypress/plugins/index.js

module.exports = (on, config) => {
  terminalReport.installPlugin(on);

  const configuration = config;
  configuration.env.injectMainBranchId = getBranch('develop');

  // more code below...

However, this is not working. However, if I hardcode the value it does work:

configuration.env.injectMainBranchId = 'develop';

You see the result in the screenshot below:

This is the dummy content of getBranch module:

const getBranch = branch => {
  return branch;
};

module.export = { getBranch };

What am I doing wrong?

Body:
Typo in getBranch:

const getBranch = branch => {
  return branch;
};

module.export = { getBranch };

export should be changed to exports


问:
Xamarin.iOS MessagingRemoteException: Build1660001055
MessagingRemoteException: An error occurred on client Build1660001055 while executing a reply for topic xvs/Build/16.6.0.1055/execute-task/CBREApp.iOS/e6f82e0002fCopy
TypeInitializationException: The type initializer for 'Microsoft.Build.Tasks.Copy' threw an exception.
PlatformNotSupportedException: Operation is not supported on this platform.</p>

答:
If you were like me who did not want to install the 16.7 Preview release just to get past this bug, the fix for this issue has luckily been released today (June 1st 2020) as part of update 16.6.1: Release Notes

Bug Report Link: xamarinios-fails-to-build-with-messagingremoteexce

(Note that as per this link, a temporary work around for this bug was to delete or change the build action of the iTunesArtwork@1x.png and iTunesArtwork@2x.png in your iOS project)


问:
how to remove the warnings in Jtidy in java
I am using Jtidy parser in java.

```<code>URL url = new URL("www.yahoo.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
doc = new Tidy().parseDOM(in, null);
</code>```

when I run this, "doc = new Tidy().parseDOM(in, null);"
  I am getting some warnings as follows:

```<code>Tidy (vers 4th August 2000) Parsing "InputStream"
line 140 column 5 - Warning: <table> lacks "summary" attribute

InputStream: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
InputStream: Document content looks like HTML 4.01 Transitional

1 warnings/errors were found!
</code>```

These warnings are getting displayed automatically on console. But I don't want these
warnings to be displayed on my console after running

```<code>doc = new Tidy().parseDOM(in, null);
</code>```

Please help me,how to do this,how to remove these warnings from console.

答:
If you want to redirect the JTidy warnings to (say) a log4j logger, read this blog entry.

If you simply want them to go away (along with other console output), then use System.setOut() and/or System.setErr() to send the output to a file ... or a black hole.

For JTidy release 8 (or later), the Tidy.setMessageListener(TidyMessageListener) method deals with the messages more gracefully.

Alternatively, you could send a bug report to webmaster@yahoo.com. :-)

Body:
I am using Jtidy parser in java.

URL url = new URL("www.yahoo.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
doc = new Tidy().parseDOM(in, null);

when I run this, "doc = new Tidy().parseDOM(in, null);"
  I am getting some warnings as follows:

Tidy (vers 4th August 2000) Parsing "InputStream"
line 140 column 5 - Warning:
 lacks "summary" attribute

InputStream: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
InputStream: Document content looks like HTML 4.01 Transitional

1 warnings/errors were found!

These warnings are getting displayed automatically on console. But I don't want these
warnings to be displayed on my console after running

doc = new Tidy().parseDOM(in, null);

Please help me,how to do this,how to remove these warnings from console.


问:
Cannot delete a pycharm project that i cloned from gitlab (Windows 10)
i deleted this folder entirely through pycharm (when you open the 'pick a directory' option) but the folder wasnt removed (its like an empty inaccessible folder now).
The Folder is a project i cloned from gitlab.
Since somehow its 'deleted', i can not access it or access the .git folder (where i should have started with deleting after reading multiple pages on the internet).

I can not get access to the folder even though I'm an administrator and i tried deleting using cmd (which won't be any different) and i keep getting 'access denied'. its frustrating!
does anyone has any suggestions?

答: Alright, all it needed was a reboot. I feel pretty bad that I've spent an hour searching for an answer, just to forget the good old "have you tried turning it off and then on again?"</p>


问:
Tkinter StringVar() not updating label's background color
I have been working on a project recently, and in it, I have to dynamically change the background color of the variable. I am doing it by using Tkinter String Var(), and it is not showing any error, yet its not working either.  This code below is not the actual project, but also has the same problem of not updating the background color.

```<code>from tkinter import *
w = Tk()
gridcolor = [[StringVar() for i in range (4)]for j in range (4) ]

for k in range(4):
    for l in range(4):
        gridcolor[k][l].set("white")
        print(gridcolor[k][l].get())
labels = [[Label(w,text ="Hi",bg = gridcolor[i][j].get()).grid(row=i, column=j)for i in range(0,4)]for j in range(0,4)]
def colorchange():
global gridcolor
for k in range(4):
    for l in range(4):
        gridcolor[k][l].set("red")
colorchange()
w.mainloop()
</code>```

Any help would be greatly appreciated.

答:
You can't use the StringVar class in this way. The vast majority of widget attributes are static and won't update if you use a StringVar for a value.

If you want to change the color of something by changing an instance of StringVar, you'll have to use the trace method of the variable to call a function that updates your widgets whenever the value changes.

Body:
I have been working on a project recently, and in it, I have to dynamically change the background color of the variable. I am doing it by using Tkinter String Var(), and it is not showing any error, yet its not working either.  This code below is not the actual project, but also has the same problem of not updating the background color.

from tkinter import *
w = Tk()
gridcolor = [[StringVar() for i in range (4)]for j in range (4) ]

for k in range(4):
    for l in range(4):
        gridcolor[k][l].set("white")
        print(gridcolor[k][l].get())
labels = [[Label(w,text ="Hi",bg = gridcolor[i][j].get()).grid(row=i, column=j)for i in range(0,4)]for j in range(0,4)]
def colorchange():
global gridcolor
for k in range(4):
    for l in range(4):
        gridcolor[k][l].set("red")
colorchange()
w.mainloop()

Any help would be greatly appreciated.


问:
How to use a stored procedure to add a row of data to one table and multiple rows of data to another table- Microsoft SQL Server Management Studio
I'm very new to Microsoft SQL Server Management Studio and really need some help on a problem.

I am working on a database for a gym. They want to add/'register' a new member via a stored procedure. I have this figured out thankfully as it only requires adding 1 row of data on a table.

They also want to add the member's custom workout details. I have managed to write a separate stored procedure for this.

However they want to be able to add the member's custom workout at the same time.

This requires adding multiple rows of data to a 'Workout' table for that specific member and adding 1 row to the 'Member' table.

For example:

Member table might look like this:

```<code>MemberID    MemberName
----------------------
   01       John
</code>```

Workout table might look like this:

```<code>MemberID   Exercise
------------------
  01       Deadlift
  01       Burpee
  01       Squat
</code>```

I ideally want the user to exec a stored procedure and insert the below data to populate both the Member and Workout table

```<code>exec ADD_MEMBER 02, Mary, Deadlift, Squat, Jogging
</code>```

The result would be

Member table:

```<code>MemberID   MemberName
-------------------
  01       John
  02       Mary
</code>```

Workout table

```<code>MemberID   Exercise
-----------------
  01       Deadlift
  01       Burpee
  01       Squat
  02       Deadlift
  02       Squat
  02       Jogging
</code>```

Any advice on how to allow the user to do this?

答:
This is a good question. With a rather exhaustive answer, I'm afraid. I'll try to be as short as possible.

For a start, I think you need to consider the fact, that the customer is responsible for specifying functional requirements and quality aspects, and you (as a developer/designer) are responsible for the fancy, geeky, technical implementations.

I assume that the end user will not be using SSMS (SQL Server Management Studio) for calling the stored procedures... right? I assume you will create some kind of application with a nice and flashy user interface, which will execute any SQL queries and/or stored procedures based on the data that is entered by the user... right?

So how you actually implement the storage logic is practically entirely up to you. As I see it, it's just fine to create and call separate stored procedures or execute single queries. But it is important that the application will wait with executing those queries and/or stored procedures until the user is ready with entering all the data about the new member.

I guess it's the idea, that the user can enter and keep all the data in the application's user interface (forms or webpages) until eventually a Save-button is pressed. When that Save-button is pressed, all the required SQL queries and/or stored procedures should be executed (in the right order, of course) to store everything correctly in the database. You probably also want to execute everything within a database transaction, so that in the end of the save routine either everything succeeds or everything fails. (That's what I would actually think what a customer would mean by saying "at the same time".)

Of course, it's technically possible to put everything inside a single stored procedure, but that implementation would become pretty complex quite quickly, I'm afraid. (It would likely involve some stored procedure parameters containing structured data, like table parameters or XML parameters, since SQL Server does not have any native array data types.) So with respect to flexibility, scalability and maintainability aspects of your application, I would strongly advise against that strategy, especially if you are relatively new to developing these kind of database applications.

Body:
I'm very new to Microsoft SQL Server Management Studio and really need some help on a problem.

I am working on a database for a gym. They want to add/'register' a new member via a stored procedure. I have this figured out thankfully as it only requires adding 1 row of data on a table.

They also want to add the member's custom workout details. I have managed to write a separate stored procedure for this.

However they want to be able to add the member's custom workout at the same time.

This requires adding multiple rows of data to a 'Workout' table for that specific member and adding 1 row to the 'Member' table.

For example:

Member table might look like this:

MemberID    MemberName
----------------------
   01       John

Workout table might look like this:

MemberID   Exercise
------------------
  01       Deadlift
  01       Burpee
  01       Squat

I ideally want the user to exec a stored procedure and insert the below data to populate both the Member and Workout table

exec ADD_MEMBER 02, Mary, Deadlift, Squat, Jogging

The result would be

Member table:

MemberID   MemberName
-------------------
  01       John
  02       Mary

Workout table

MemberID   Exercise
-----------------
  01       Deadlift
  01       Burpee
  01       Squat
  02       Deadlift
  02       Squat
  02       Jogging

Any advice on how to allow the user to do this?


问:
Swift: How to use Xcoordinator to set a root view controller from child coordinator?
I'm trying to understand how to use XCoordinator to set a root view controller from a child coordinator.

I have an app delegate that runs the app coordinator.

The pattern I have is:

AppDelegate
   - App Coordinator
   --- Main Menu Coordinator
    --- Game Coorinator

(see image)

The app coordinator should not know about specific view controllers directly because I believe the view controllers should managed by their own respective coordinator.

Thus, the app coordinator should manage the flow between the coordinators and set a root, initial coordinator.

Sadly, the screen is blank, and keeps complaining that I can't as "Pushing a navigation controller is not supported".

But if I directly instantiate the view controller inside my appcoordinator its fine and I don't know why.

```<code>// AppCoordinator
enum AppRoute: Route {
    case mainmenu
    case game
}

class AppCoordinator: NavigationCoordinator<AppRoute> {

    init() {
        super.init(initialRoute: .mainmenu)
    }

    // MARK: Overrides
    override func prepareTransition(for route: AppRoute) -> NavigationTransition {
        let router = MainMenuCoordinator().strongRouter
        return .push(router)
    }
}
</code>```

This should launch the MainMenuCoordinator's initial view controller

```<code>enum MainMenuRoute: Route {
    case mainmenu
}

// MainMenuCoordinator
class MainMenuCoordinator: NavigationCoordinator<MainMenuRoute> {

    init() {
        super.init(initialRoute: .mainmenu)
    }

    override func prepareTransition(for route: MainMenuRoute) -> NavigationTransition {
        print ("route: \(route as Any)")

            let vc = MainMenuViewController.instantiate(.main)
            return .push(vc)
     }
}
</code>```

But this returns a blank screen and it complaining that push is not supported.

But, if I move this code:

```<code>let vc = MainMenuViewController.instantiate(.main)
return .push(vc)
</code>```

to the AppCoordinator

like this:

```<code>// MARK: AppCoordinator Overrides
override func prepareTransition(for route: AppRoute) -> NavigationTransition {
    let vc = MainMenuViewController.instantiate(.main)
    return .push(vc)
}
</code>```

Its fine.  A screen is presented -- but the main menu coordinator is no longer being "followed"

I'm wondering -- how do you make it so that the app coordinator just delegates responsibility to its child coordinator?

I appreciate any assistance you can give.
Thanks

// Edit: I have tried another attempt, following an answer provided, of passing a reference of the parent coordinator to child coordinators.

I want the mainmenucoordinator to use its own collection of routes; I don't want to just rely upon on any routes defined in the AppRoutes.

So my app coordinator has these routes:

```<code>enum AppRoute: Route {
    case mainmenu
    case game
}

class AppCoordinator: NavigationCoordinator<AppRoute> {

init() {
    let defaultRoute: AppRoute = .mainmenu
    super.init(initialRoute: defaultRoute)
    self.rootViewController.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}

}
</code>```

My main coordinator has these routes:

```<code>enum MainMenuRoute: Route {
    case mainmenu
    case selectPlayer
    case playgame
}

class MainMenuCoordinator: NavigationCoordinator<MainMenuRoute> {

    // For my child coordinators, keep a strong reference to parent
    private var router: StrongRouter<AppRoute>?
/// ...
}
</code>```

When I come to init it, I set the parent.

```<code>// MainMenuCoordinator: Init
  convenience init(router: StrongRouter<AppRoute>) {
        self.init(initialRoute: .mainmenu)
    }
</code>```

But now it won't use any routes that I've defined for the MainMenuCoordinator; instead, it uses AppRoute

Example:

Trying to set the router in MainMenuCoordinator.prepareTransition

```<code>override func prepareTransition(for route: MainMenuRoute) -> NavigationTransition {
        print ("route: \(route as Any)")

        switch route {
        case .mainmenu:
            let vc = MainMenuViewController.instantiate(.main)
            vc.router = strongRouter
            return .push(vc)
        // ....
      }
}
</code>```

The main menu view controller holds a reference to:

```<code>class MainMenuViewController: UIViewController, Storyboarded {

    // MARK: - Stored properties
    var router: UnownedRouter<MainMenuRoute>!
}
</code>```

With these edits, the root view controller is now white; but the logger still complains I cannot push view controllers.

答:
I am doing smth like this:

```<code>class MainCoordinator: NavigationCoordinator<ApplicationRoute> {

    convenience init() {
        var defaultRoute: ApplicationRoute = .showAuthentification
        if ApplicationSettings.shared.isLoggedIn {
            defaultRoute = .showApplicationRoot
        }

        self.init(defaultRoute: defaultRoute)
        self.rootViewController.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    }

    override func prepareTransition(for route: ApplicationRoute) -> NavigationTransition {
        switch route {
            case .showAuthentification:
                return .multiple(.dismissToRoot(animation: .fadeInstant),
                                 .presentFullScreen(AuthentificationCoordinator(router: strongRouter),
                                                    animation: .fadeInstant))

            case .showApplicationRoot:
                return .multiple(.dismissToRoot(animation: .fadeInstant),
                                 .presentFullScreen(TabControllerCoordinator(router: strongRouter),
                                                    animation: .fadeInstant))

        }
    }
}
</code>```

and in a one child coordinator:

```<code>class AuthentificationCoordinator: NavigationCoordinator<AuthentificationRoute> {
    // For my child coordinators I keep a strong reference to the parent, so I can use it later
    private var router: StrongRouter<SMCApplicationRoute>?

    convenience init(router: StrongRouter<SMCApplicationRoute>) {
        self.init(defaultRoute: .initial)
        self.router = router
    }

    override func prepareTransition(for route: AuthentificationRoute) -> NavigationTransition {
        switch route {
        case .initial:
            let initialVC = LandingPageViewController.loadFromXIB(type: LandingPageViewController.self)
            initialVC.router = strongRouter
            return .push(initialVC, animation: .fade)

        case .showLogin:
            let loginVC = LoginViewController.loadFromXIB(type: LoginViewController.self)
            loginVC.router = strongRouter
            return .push(loginVC, animation: .fade)

        case .showHome:
            // Here I trigger the other route from MainCoordinator. If I log in, the AuthentificationCoordinator will get destroyed, with all the child coordinators with root controllers
            return .trigger(SMCApplicationRoute.showApplicationRoot, on: router!)
        }
    }
}
</code>```

I think there are better solutions, but I found this to be efective. If the code is not self explaining, just let me know ;)

Body:
I'm trying to understand how to use XCoordinator to set a root view controller from a child coordinator.

I have an app delegate that runs the app coordinator.

The pattern I have is:

AppDelegate
   - App Coordinator
   --- Main Menu Coordinator
    --- Game Coorinator

(see image)

The app coordinator should not know about specific view controllers directly because I believe the view controllers should managed by their own respective coordinator.

Thus, the app coordinator should manage the flow between the coordinators and set a root, initial coordinator.

Sadly, the screen is blank, and keeps complaining that I can't as "Pushing a navigation controller is not supported".

But if I directly instantiate the view controller inside my appcoordinator its fine and I don't know why.

// AppCoordinator
enum AppRoute: Route {
    case mainmenu
    case game
}

class AppCoordinator: NavigationCoordinator<AppRoute> {

    init() {
        super.init(initialRoute: .mainmenu)
    }

    // MARK: Overrides
    override func prepareTransition(for route: AppRoute) -> NavigationTransition {
        let router = MainMenuCoordinator().strongRouter
        return .push(router)
    }
}

This should launch the MainMenuCoordinator's initial view controller

enum MainMenuRoute: Route {
    case mainmenu
}

// MainMenuCoordinator
class MainMenuCoordinator: NavigationCoordinator<MainMenuRoute> {

    init() {
        super.init(initialRoute: .mainmenu)
    }

    override func prepareTransition(for route: MainMenuRoute) -> NavigationTransition {
        print ("route: \(route as Any)")

            let vc = MainMenuViewController.instantiate(.main)
            return .push(vc)
     }
}

But this returns a blank screen and it complaining that push is not supported.

But, if I move this code:

let vc = MainMenuViewController.instantiate(.main)
return .push(vc)

to the AppCoordinator

like this:

// MARK: AppCoordinator Overrides
override func prepareTransition(for route: AppRoute) -> NavigationTransition {
    let vc = MainMenuViewController.instantiate(.main)
    return .push(vc)
}

Its fine.  A screen is presented -- but the main menu coordinator is no longer being "followed"

I'm wondering -- how do you make it so that the app coordinator just delegates responsibility to its child coordinator?

I appreciate any assistance you can give.
Thanks

// Edit: I have tried another attempt, following an answer provided, of passing a reference of the parent coordinator to child coordinators.

I want the mainmenucoordinator to use its own collection of routes; I don't want to just rely upon on any routes defined in the AppRoutes.

So my app coordinator has these routes:

enum AppRoute: Route {
    case mainmenu
    case game
}

class AppCoordinator: NavigationCoordinator<AppRoute> {

init() {
    let defaultRoute: AppRoute = .mainmenu
    super.init(initialRoute: defaultRoute)
    self.rootViewController.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}

}

My main coordinator has these routes:

enum MainMenuRoute: Route {
    case mainmenu
    case selectPlayer
    case playgame
}

class MainMenuCoordinator: NavigationCoordinator<MainMenuRoute> {

    // For my child coordinators, keep a strong reference to parent
    private var router: StrongRouter<AppRoute>?
/// ...
}

When I come to init it, I set the parent.

// MainMenuCoordinator: Init
  convenience init(router: StrongRouter<AppRoute>) {
        self.init(initialRoute: .mainmenu)
    }

But now it won't use any routes that I've defined for the MainMenuCoordinator; instead, it uses AppRoute

Example:

Trying to set the router in MainMenuCoordinator.prepareTransition

override func prepareTransition(for route: MainMenuRoute) -> NavigationTransition {
        print ("route: \(route as Any)")

        switch route {
        case .mainmenu:
            let vc = MainMenuViewController.instantiate(.main)
            vc.router = strongRouter
            return .push(vc)
        // ....
      }
}

The main menu view controller holds a reference to:

class MainMenuViewController: UIViewController, Storyboarded {

    // MARK: - Stored properties
    var router: UnownedRouter<MainMenuRoute>!
}

With these edits, the root view controller is now white; but the logger still complains I cannot push view controllers.

Body:
I am doing smth like this:

class MainCoordinator: NavigationCoordinator<ApplicationRoute> {

    convenience init() {
        var defaultRoute: ApplicationRoute = .showAuthentification
        if ApplicationSettings.shared.isLoggedIn {
            defaultRoute = .showApplicationRoot
        }

        self.init(defaultRoute: defaultRoute)
        self.rootViewController.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    }

    override func prepareTransition(for route: ApplicationRoute) -> NavigationTransition {
        switch route {
            case .showAuthentification:
                return .multiple(.dismissToRoot(animation: .fadeInstant),
                                 .presentFullScreen(AuthentificationCoordinator(router: strongRouter),
                                                    animation: .fadeInstant))

            case .showApplicationRoot:
                return .multiple(.dismissToRoot(animation: .fadeInstant),
                                 .presentFullScreen(TabControllerCoordinator(router: strongRouter),
                                                    animation: .fadeInstant))

        }
    }
}

and in a one child coordinator:

class AuthentificationCoordinator: NavigationCoordinator<AuthentificationRoute> {
    // For my child coordinators I keep a strong reference to the parent, so I can use it later
    private var router: StrongRouter<SMCApplicationRoute>?

    convenience init(router: StrongRouter<SMCApplicationRoute>) {
        self.init(defaultRoute: .initial)
        self.router = router
    }

    override func prepareTransition(for route: AuthentificationRoute) -> NavigationTransition {
        switch route {
        case .initial:
            let initialVC = LandingPageViewController.loadFromXIB(type: LandingPageViewController.self)
            initialVC.router = strongRouter
            return .push(initialVC, animation: .fade)

        case .showLogin:
            let loginVC = LoginViewController.loadFromXIB(type: LoginViewController.self)
            loginVC.router = strongRouter
            return .push(loginVC, animation: .fade)

        case .showHome:
            // Here I trigger the other route from MainCoordinator. If I log in, the AuthentificationCoordinator will get destroyed, with all the child coordinators with root controllers
            return .trigger(SMCApplicationRoute.showApplicationRoot, on: router!)
        }
    }
}

I think there are better solutions, but I found this to be efective. If the code is not self explaining, just let me know ;)


问:
Selecting only non null fields from the filter rows django
I have this query which are getting the required rows which i want but the problem is most fields/columns have null values I just want to get only those fields from these rows which have non null values

```<code>queryset = User.objects.filter(email__exact=email)
</code>```

Here, is my model

```<code>class User(models.Model):
    email = models.CharField(max_length=50, null=True, blank=True)
    password = models.CharField(db_index=True, max_length=40, null=True)
    source = models.CharField(default='unknown', max_length=150, null=True)
    domain = models.CharField(max_length=50, null=True, blank=True)
    before_at = models.CharField(max_length=255, null=True, blank=True)
    username = models.CharField(db_index=True, max_length=150, null=True, blank=True)
    hash = models.CharField(max_length=255, null=True, blank=True)
    ipaddress = models.CharField(max_length=50, null=True, blank=True)
    phonenumber = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        if self.email != None:
            return self.email
        elif self.username != None:
            return self.username
</code>```

答:
You can obtain a list of NULLable fields with:

```<code>nullable_fields = [f.name for f in <b>User._meta.get_fields()</b> if <b>f.null</b>]</code>```

With these fields, we can make a filter:

```<code><b>nonnullq</b> = Q(
    *[f('{field}__isnull', False) for field in nullable_fields],
    _connector=Q.AND
)</code>```

We can use this filter to exclude all records where one if the fields is NULL:

```<code>queryset = User.objects.filter(<b>nonnullq</b>, email=email)</code>```

That being said, it is rather odd that nearly all fields are NULLable. Often only a small amount is NULLable, since it often makes models more complicated.

Body:
I have this query which are getting the required rows which i want but the problem is most fields/columns have null values I just want to get only those fields from these rows which have non null values

queryset = User.objects.filter(email__exact=email)

Here, is my model

class User(models.Model):
    email = models.CharField(max_length=50, null=True, blank=True)
    password = models.CharField(db_index=True, max_length=40, null=True)
    source = models.CharField(default='unknown', max_length=150, null=True)
    domain = models.CharField(max_length=50, null=True, blank=True)
    before_at = models.CharField(max_length=255, null=True, blank=True)
    username = models.CharField(db_index=True, max_length=150, null=True, blank=True)
    hash = models.CharField(max_length=255, null=True, blank=True)
    ipaddress = models.CharField(max_length=50, null=True, blank=True)
    phonenumber = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        if self.email != None:
            return self.email
        elif self.username != None:
            return self.username

Body:
You can obtain a list of NULLable fields with:

nullable_fields = [f.name for f in User._meta.get_fields() if f.null]

With these fields, we can make a filter:

nonnullq = Q(
    *[f('{field}__isnull', False) for field in nullable_fields],
    _connector=Q.AND
)

We can use this filter to exclude all records where one if the fields is NULL:

queryset = User.objects.filter(nonnullq, email=email)

That being said, it is rather odd that nearly all fields are NULLable. Often only a small amount is NULLable, since it often makes models more complicated.


问:
can I use hystrix to call up a failed request again?
I have a feign client that sends one request to another microservice every 60 seconds. On this controller, I use the HystrixCommand annotation with a user configuration (just experimenting). I also have a fallback method in which I go into when the request fails.
However, the expected data is quite sensitive for me, so it makes no sense to send empty data from the fallback method.

Question: How to execute a failed request another 2-3 times at any interval? Does Hystrix have this functionality?

I had the idea to call the request again in the fallback method and save somewhere the number of executed requests, each time comparing them with the limit-variable, but I do not like it.

```<code> @HystrixCommand(
            threadPoolKey = "currencyThreadPool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "30"),
                    @HystrixProperty(name = "maxQueueSize", value = "10")},
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "90"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "15000"),
                    @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "5")}
    )
</code>```

答:
In the end, I used Spring Retry library, which fully satisfied my requirements.</p>

```<code>@Retryable(value = {ConnectException.class, FeignException.class}, maxAttempts = 4,
        backoff = @Backoff(delay = 5000, maxDelay = 80000, multiplier = 4))
</code>```

Body:
I have a feign client that sends one request to another microservice every 60 seconds. On this controller, I use the HystrixCommand annotation with a user configuration (just experimenting). I also have a fallback method in which I go into when the request fails.
However, the expected data is quite sensitive for me, so it makes no sense to send empty data from the fallback method.

Question: How to execute a failed request another 2-3 times at any interval? Does Hystrix have this functionality?

I had the idea to call the request again in the fallback method and save somewhere the number of executed requests, each time comparing them with the limit-variable, but I do not like it.

 @HystrixCommand(
            threadPoolKey = "currencyThreadPool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "30"),
                    @HystrixProperty(name = "maxQueueSize", value = "10")},
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "90"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "15000"),
                    @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "5")}
    )

Body:
In the end, I used Spring Retry library, which fully satisfied my requirements.

@Retryable(value = {ConnectException.class, FeignException.class}, maxAttempts = 4,
        backoff = @Backoff(delay = 5000, maxDelay = 80000, multiplier = 4))


问:
Apollo Java GraphQL Client: generateApolloSources failing
I am exploring graphql and I followed this tutorial https://www.graphql-java.com/tutorials/getting-started-with-spring-boot/ to get a server running. I am now trying to write a Java client for this server using this library: https://github.com/apollographql/apollo-android . My code so far is: https://github.com/alampada/graphql-java-client-tutorial , the readme includes steps to reproduce.

I am not able to have the apollo client library to generate model for my query: https://github.com/alampada/graphql-java-client-tutorial/blob/master/src/main/graphql/com/example/book.graphql, as ./gradlew generateApolloSources fails with:

```<code>Can't query `Book` on type `Query`
  ----------------------------------------------------
  [1]:query BookQuery($id: ID!) {
  [2]:    Book (id: $id) {
  [3]:        id
  ----------------------------------------------------
</code>```

Could someone explain what I am doing wrong?

答:
Replying for reference as I managed to get this to work.
The graphql file should reference the name of the query from the schema rather than book.
Working example updated: https://github.com/alampada/graphql-java-client-tutorial/commit/30e7c0955a59dff4675b7f12c26873fe3dd37201#diff-76111f834f0748466f63240b018a755a

Body:
I am exploring graphql and I followed this tutorial https://www.graphql-java.com/tutorials/getting-started-with-spring-boot/ to get a server running. I am now trying to write a Java client for this server using this library: https://github.com/apollographql/apollo-android . My code so far is: https://github.com/alampada/graphql-java-client-tutorial , the readme includes steps to reproduce.

I am not able to have the apollo client library to generate model for my query: https://github.com/alampada/graphql-java-client-tutorial/blob/master/src/main/graphql/com/example/book.graphql, as ./gradlew generateApolloSources fails with:

Can't query `Book` on type `Query`
  ----------------------------------------------------
  [1]:query BookQuery($id: ID!) {
  [2]:    Book (id: $id) {
  [3]:        id
  ----------------------------------------------------

Could someone explain what I am doing wrong?


问:
Adding and Removing tinyMCE instances within jQuery instances
Odd problem here.

Working with an existing system that uses TinyMCE as it's text editor.

I've created a page which contains a whole lot of movable divs using jquery sortables.  Now TinyMCE doesn't seem to like being moved in the dom so after doing a bit of research it appears I have to remove the tinymce instance from the textbox within the div being moved and add it back in at the end of the drag.  I can do remove the instance fine but however when I go to add it back in, it won't.

I have the most up to date version of TinyMCE, a slightly older version of jQuery (tried updating but no luck).

Can't work this out hence this post :)

```<code> $(function() {
    $("#categoryorder").sortable({
    opacity: 0.6,
    cursor: 'move',
    revert: true,
    forcePlaceholderSize: true,
    scrollSensitivity: 40,
    start: function(e, ui) {
             tinyMCE.execCommand( 'mceRemoveControl', false, 'textarea1' );
    },
    stop: function(e,ui) {
            // won't add back here for some reason
            tinyMCE.execCommand( 'mceAddControl', false, 'textarea1' );
            $(this).sortable( "refresh" );
    }
    });
});
</code>```

Not sure why it won't add back, any ideas?

答:
I know this is an oldish post but incase someone if googling for this issue:

I am not sure what you are trying to achieve with the refresh call to sortable.

but this is what I did to make it work for me

I am using the jquery.tinymce - just to try it out..
I have the tinymce settings elsewhere so I can call different settings depending what I am initializing but the concept is sound - so here are my start and stop methods for sortable

```<code>start : function(event, ui) {
// mce editor needs to be removed and readded when move finsihed
     $("textarea",ui.item).tinymce().remove();
},
stop : function(event, ui) {
     $("textarea",ui.item).tinymce(myconfig.tinymcesettings);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Odd problem here.

Working with an existing system that uses TinyMCE as it's text editor.

I've created a page which contains a whole lot of movable divs using jquery sortables.  Now TinyMCE doesn't seem to like being moved in the dom so after doing a bit of research it appears I have to remove the tinymce instance from the textbox within the div being moved and add it back in at the end of the drag.  I can do remove the instance fine but however when I go to add it back in, it won't.

I have the most up to date version of TinyMCE, a slightly older version of jQuery (tried updating but no luck).

Can't work this out hence this post :)

 $(function() {
    $("#categoryorder").sortable({
    opacity: 0.6,
    cursor: 'move',
    revert: true,
    forcePlaceholderSize: true,
    scrollSensitivity: 40,
    start: function(e, ui) {
             tinyMCE.execCommand( 'mceRemoveControl', false, 'textarea1' );
    },
    stop: function(e,ui) {
            // won't add back here for some reason
            tinyMCE.execCommand( 'mceAddControl', false, 'textarea1' );
            $(this).sortable( "refresh" );
    }
    });
});

Not sure why it won't add back, any ideas?

Body:
I know this is an oldish post but incase someone if googling for this issue:

I am not sure what you are trying to achieve with the refresh call to sortable.

but this is what I did to make it work for me

I am using the jquery.tinymce - just to try it out..
I have the tinymce settings elsewhere so I can call different settings depending what I am initializing but the concept is sound - so here are my start and stop methods for sortable

start : function(event, ui) {
// mce editor needs to be removed and readded when move finsihed
     $("textarea",ui.item).tinymce().remove();
},
stop : function(event, ui) {
     $("textarea",ui.item).tinymce(myconfig.tinymcesettings);
}


问:
Laravel attach on associative key
I have a ManyToMany relationship setup but need to specify a value for the key in my array to attach.

```<code>$data = request()->validate([
           'homework_title' => '', // string
           'homework_description' => '', // string
            'group_id' => '', // array
        ]);

$homework = request()->user()->homeworks()->create([
            'homework_title' => $data['homework_title'],
            'homework_description' => $data['homework_description'],
        ]);

$homework->groups()->attach($data['group_id'][key]);
</code>```

group_id is an array and looks like the following:

```<code>[
  {
    "group_id": 1,
    "group_name": "8x/En2"
  },
  {
    "group_id": 2,
    "group_name": "9x/En3"
  }
]
</code>```

How do I specify to attach only the group_id in array?

答:
Got it to work, with:

Arr::pluck()

First time round I forgot to import the class (stupid me)!

use Illuminate\Support\Arr;

finally looking like the following:

```<code>$homework->groups()->attach(Arr::pluck($data['group_id'], 'group_id'));
</code>```

Title: Laravel attach on associative key

Body:
I have a ManyToMany relationship setup but need to specify a value for the key in my array to attach.

$data = request()->validate([
           'homework_title' => '', // string
           'homework_description' => '', // string
            'group_id' => '', // array
        ]);

$homework = request()->user()->homeworks()->create([
            'homework_title' => $data['homework_title'],
            'homework_description' => $data['homework_description'],
        ]);

$homework->groups()->attach($data['group_id'][key]);

group_id is an array and looks like the following:

[
  {
    "group_id": 1,
    "group_name": "8x/En2"
  },
  {
    "group_id": 2,
    "group_name": "9x/En3"
  }
]

How do I specify to attach only the group_id in array?

Body:
Got it to work, with:

Arr::pluck()

First time round I forgot to import the class (stupid me)!

use Illuminate\Support\Arr;

finally looking like the following:

$homework->groups()->attach(Arr::pluck($data['group_id'], 'group_id'));


问:
Python: coursera assignments - Dictionary chapter
I'm trying to solve the assignments from coursera - Python.

Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

```<code>name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

lst = list()
for line in handle:
    line = line.strip()
    if line.startswith("From"):
        words = line.split()
        email = words[1]
        lst.append(email)

dct = dict()
for email in lst:
    dct[email] = dct.get(email,0)+1

bigcount = None
email_address = None
for key,value in dct.items():
    if bigcount is None or value > bigcount:
        bigcount = value
        email_address = key

print email_address, bigcount
</code>```

My code runs, but the desired output should be: cwen@iupui.edu 5  , but i get somehow "doubled" output: cwen@iupui.edu 10

Did anyone solved this problem? Could you please give me a hint what have i missed? Thank you a lot!

答:
```<code> name = input("Enter file:")
 if len(name) < 1 : name = "mbox-short.txt"
 handle = open(name)
 word=list()
 for line in handle:
     if line.startswith('From'):
        words=line.split()
        word.append(words)

count=dict()
for word in words:
count[word]=count.get(word,0)+1

bigcount = None
bigword= None
for count,word in count.items():
    if count > bigcount:
    bigcount=count
    bigword=word

print(bigcount,bigword)
</code>```

Body:
I'm trying to solve the assignments from coursera - Python.

Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

lst = list()
for line in handle:
    line = line.strip()
    if line.startswith("From"):
        words = line.split()
        email = words[1]
        lst.append(email)

dct = dict()
for email in lst:
    dct[email] = dct.get(email,0)+1

bigcount = None
email_address = None
for key,value in dct.items():
    if bigcount is None or value > bigcount:
        bigcount = value
        email_address = key

print email_address, bigcount

My code runs, but the desired output should be: cwen@iupui.edu 5  , but i get somehow "doubled" output: cwen@iupui.edu 10

Did anyone solved this problem? Could you please give me a hint what have i missed? Thank you a lot!


问:
Python replace lines in a file that match a certain format using regex
I have a file with the following lines:

```<code> [Path('info')]
TInfoResource = class
 protected
 public
  [GET, Path('/build/'), Produces(TMediaType.TEXT_PLAIN)]
  function GetBuild: string;
  [GET, Path('/version/'), Produces(TMediaType.TEXT_PLAIN)]
  function GetVersion: string;
 end;

 [Path('helloworld')]
  THelloWorldResource = class
  protected
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;
</code>```

and I'm trying to write an expression in python that would allow me to find all the lines that contain the "[Path('*')]" pattern and replace the last square bracket with ", RolesAllowed('admin')]". However, I'm having trouble coming up with the correct regular expression to achieve this, this is what I have so far but it isn't working:

```<code>filename = "RAsistance"

#input file
fin = open(filename + ".pas", "rt")
fout = open(filename + "_MOD.pas", "wt")
for line in fin:
    if (re.search(r"^\[Path (*) \]", line)):
        fout.write(line.replace(']', ", RolesAllowed('admin')]"))

fin.close()
fout.close()
</code>```

I'm entirely new to regular expressions, any help is appreciated, thanks!

答:
You need to escape all regex control characters in your pattern, test here:</p>

```<code>^\[Path\s{0,}\(['*]+\)\s{0,}\]
</code>```

Body:
I have a file with the following lines:

 [Path('info')]
TInfoResource = class
 protected
 public
  [GET, Path('/build/'), Produces(TMediaType.TEXT_PLAIN)]
  function GetBuild: string;
  [GET, Path('/version/'), Produces(TMediaType.TEXT_PLAIN)]
  function GetVersion: string;
 end;

 [Path('helloworld')]
  THelloWorldResource = class
  protected
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;

and I'm trying to write an expression in python that would allow me to find all the lines that contain the "[Path('*')]" pattern and replace the last square bracket with ", RolesAllowed('admin')]". However, I'm having trouble coming up with the correct regular expression to achieve this, this is what I have so far but it isn't working:

filename = "RAsistance"

#input file
fin = open(filename + ".pas", "rt")
fout = open(filename + "_MOD.pas", "wt")
for line in fin:
    if (re.search(r"^\[Path (*) \]", line)):
        fout.write(line.replace(']', ", RolesAllowed('admin')]"))

fin.close()
fout.close()

I'm entirely new to regular expressions, any help is appreciated, thanks!

Body:
You need to escape all regex control characters in your pattern, test here:

^\[Path\s{0,}\(['*]+\)\s{0,}\]


问:
Extract row value where the 2 columns are not equal in a data frame in R
Is there a way to extract values in the dataframe when the columns values are not equal

```<code>df
ColA  Colb  ColC
12     12    fs
23     24    fsd
34     34    dsf
21     22    dsf
</code>```

Here 2nd and 4th Row values(ColA and ColB are not equal), So is there a way to extract row values and cell values corresponding to that?

```<code>Row values
2, 4
</code>```

```<code>Cel_value_ColC  # Corresponding values
fsd, dsf
</code>```

答:
An option with tidyverse

```<code>library(dplyr)
df %>%
   filter(ColA - ColB != 0) %>%
   pull(ColC)
</code>```

Body:
Is there a way to extract values in the dataframe when the columns values are not equal

df
ColA  Colb  ColC
12     12    fs
23     24    fsd
34     34    dsf
21     22    dsf

Here 2nd and 4th Row values(ColA and ColB are not equal), So is there a way to extract row values and cell values corresponding to that?

Row values
2, 4

Cel_value_ColC  # Corresponding values
fsd, dsf

Body:
An option with tidyverse

library(dplyr)
df %>%
   filter(ColA - ColB != 0) %>%
   pull(ColC)


问:
Extract Name and Value from XML Node in Oracle SQL
I am trying to extract the Values based on Name via Oracle SQL query from the XML returned by a SOAP web service response, however it's resulting in errors. I could extract AdName, AdCat using this XMLTYPE method, but not the ones that's embedded further inside Results and AdSettings attributes. I must be wrong with the syntax I am using. Any help is appreciated.

SQL Query with XML Response:

```<code>WITH xmltest (id, data_xml) AS (
SELECT 1, XMLTYPE('<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <ResponseHeader xmlns="https://www.google.com/apis/ads/v202005">
      <requestId>123456</requestId>
    </ResponseHeader>
  </soap:Header>
  <soap:Body>
    <getAdsResponse xmlns="https://www.google.com/apis/ads/v202005">
      <getAdsResult>
        <ResultReceived>1</ResultReceived>
        <AdName>Target Comm. Systems</AdName>
        <AdCat>COMMERCIAL</AdCat>
        <SessionID>654321</SessionID>
        <Results>
          <Result><Name>ADId</Name><Value>2372</Value></Result>
          <Result><Name>AdStatus</Name><Value>ACTIVE</Value></Result>
          <Result><Name>targetWindow</Name><Value>TOP</Value></Result>
        </Results>
        <AdSettings>
          <Setting><Name>fontFamily</Name><Value>DEFAULT</Value></Setting>
          <Setting><Name>fontSize</Name><Value>9</Value></Setting>
          <Setting><Name>adSenseEnabled</Name><Value>TRUE</Value></Setting>
          <Setting><Name>adType</Name><Value>TEXT_AND_IMAGE</Value></Setting>
        </AdSettings>
      </getAdsResult>
    </getAdsResponse>
  </soap:Body>
</soap:Envelope>') FROM SYS.DUAL
  )
  SELECT x.Ad_Name,
         x.Ad_Category,
         x.Ad_ID,
         x.Ad_Status,
         x.AdSense_Enabled,
         x.Ad_Type
  FROM   xmltest d,
         XMLTABLE ( XMLNAMESPACES ( 'http://schemas.xmlsoap.org/soap/envelope/'  AS  "soap",
                                    'https://www.google.com/apis/ads/v202005'    AS  "AdsNs2"
                                  ),
                    '/soap:Envelope/soap:Body/AdsNs2:getAdsResponse/AdsNs2:getAdsResult'
                    PASSING d.data_xml
                    COLUMNS Ad_Name          VARCHAR2(50)  PATH  'AdsNs2:AdName',
                            Ad_Category      VARCHAR2(50)  PATH  'AdsNs2:AdCat',
                            Ad_ID            VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="ADId"]/Value',
                            Ad_Status        VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="AdStatus"]/Value',
                            AdSense_Enabled  VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="adSenseEnabled"]/Value',
                            Ad_Type          VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="adType"]/Value'
                  ) x;
</code>```

Error:

```<code>ORA-19112: error raised during evaluation:
XVM-01081: [XPST0081] Invalid prefix
1   declare namespace soap="http://schemas.xmlsoap.org/soap/envelope/";declare
-                                                                                ^

19112. 00000 -  "error raised during evaluation: %s"
*Cause:    The error function was called during evaluation of the XQuery expression.
*Action:   Check the detailed error message for the possible causes.
Error at Line: 39 Column: 10
</code>```

答:
The last four columns XPath expressions were completely off. Here is how to do it correctly.

SQL

```<code>WITH xmltest (id, data_xml) AS (
SELECT 1, XMLTYPE('<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <ResponseHeader xmlns="https://www.google.com/apis/ads/v202005">
      <requestId>123456</requestId>
    </ResponseHeader>
  </soap:Header>
  <soap:Body>
    <getAdsResponse xmlns="https://www.google.com/apis/ads/v202005">
      <getAdsResult>
        <ResultReceived>1</ResultReceived>
        <AdName>Target Comm. Systems</AdName>
        <AdCat>COMMERCIAL</AdCat>
        <SessionID>654321</SessionID>
        <Results>
          <Result><Name>ADId</Name><Value>2372</Value></Result>
          <Result><Name>AdStatus</Name><Value>ACTIVE</Value></Result>
          <Result><Name>targetWindow</Name><Value>TOP</Value></Result>
        </Results>
        <AdSettings>
          <Setting><Name>fontFamily</Name><Value>DEFAULT</Value></Setting>
          <Setting><Name>fontSize</Name><Value>9</Value></Setting>
          <Setting><Name>adSenseEnabled</Name><Value>TRUE</Value></Setting>
          <Setting><Name>adType</Name><Value>TEXT_AND_IMAGE</Value></Setting>
        </AdSettings>
      </getAdsResult>
    </getAdsResponse>
  </soap:Body>
</soap:Envelope>') FROM SYS.DUAL
  )
  SELECT x.Ad_Name,
         x.Ad_Category,
         x.Ad_ID,
         x.Ad_Status,
         x.AdSense_Enabled,
         x.Ad_Type
  FROM   xmltest d,
         XMLTABLE ( XMLNAMESPACES ( 'http://schemas.xmlsoap.org/soap/envelope/'  AS  "soap",
                                    'https://www.google.com/apis/ads/v202005'    AS  "AdsNs2"
                                  ),
                    '/soap:Envelope/soap:Body/AdsNs2:getAdsResponse/AdsNs2:getAdsResult'
                    PASSING d.data_xml
                    COLUMNS Ad_Name          VARCHAR2(50)  PATH  'AdsNs2:AdName',
                            Ad_Category      VARCHAR2(50)  PATH  'AdsNs2:AdCat',
                            Ad_ID            VARCHAR2(50)  PATH  'AdsNs2:Results/AdsNs2:Result[AdsNs2:Name="ADId"]/AdsNs2:Value',
                            Ad_Status        VARCHAR2(50)  PATH  'AdsNs2:Results/AdsNs2:Result[AdsNs2:Name="AdStatus"]/AdsNs2:Value',
                            AdSense_Enabled  VARCHAR2(50)  PATH  'AdsNs2:AdSettings/AdsNs2:Setting[AdsNs2:Name="adSenseEnabled"]/AdsNs2:Value',
                            Ad_Type          VARCHAR2(50)  PATH  'AdsNs2:AdSettings/AdsNs2:Setting[AdsNs2:Name="adType"]/AdsNs2:Value'
                  ) x;
</code>```

Body:
I am trying to extract the Values based on Name via Oracle SQL query from the XML returned by a SOAP web service response, however it's resulting in errors. I could extract AdName, AdCat using this XMLTYPE method, but not the ones that's embedded further inside Results and AdSettings attributes. I must be wrong with the syntax I am using. Any help is appreciated.

SQL Query with XML Response:

WITH xmltest (id, data_xml) AS (
SELECT 1, XMLTYPE('<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <ResponseHeader xmlns="https://www.google.com/apis/ads/v202005">
      <requestId>123456</requestId>
    </ResponseHeader>
  </soap:Header>
  <soap:Body>
    <getAdsResponse xmlns="https://www.google.com/apis/ads/v202005">
      <getAdsResult>
        <ResultReceived>1</ResultReceived>
        <AdName>Target Comm. Systems</AdName>
        <AdCat>COMMERCIAL</AdCat>
        <SessionID>654321</SessionID>
        <Results>
          <Result><Name>ADId</Name><Value>2372</Value></Result>
          <Result><Name>AdStatus</Name><Value>ACTIVE</Value></Result>
          <Result><Name>targetWindow</Name><Value>TOP</Value></Result>
        </Results>
        <AdSettings>
          <Setting><Name>fontFamily</Name><Value>DEFAULT</Value></Setting>
          <Setting><Name>fontSize</Name><Value>9</Value></Setting>
          <Setting><Name>adSenseEnabled</Name><Value>TRUE</Value></Setting>
          <Setting><Name>adType</Name><Value>TEXT_AND_IMAGE</Value></Setting>
        </AdSettings>
      </getAdsResult>
    </getAdsResponse>
  </soap:Body>
</soap:Envelope>') FROM SYS.DUAL
  )
  SELECT x.Ad_Name,
         x.Ad_Category,
         x.Ad_ID,
         x.Ad_Status,
         x.AdSense_Enabled,
         x.Ad_Type
  FROM   xmltest d,
         XMLTABLE ( XMLNAMESPACES ( 'http://schemas.xmlsoap.org/soap/envelope/'  AS  "soap",
                                    'https://www.google.com/apis/ads/v202005'    AS  "AdsNs2"
                                  ),
                    '/soap:Envelope/soap:Body/AdsNs2:getAdsResponse/AdsNs2:getAdsResult'
                    PASSING d.data_xml
                    COLUMNS Ad_Name          VARCHAR2(50)  PATH  'AdsNs2:AdName',
                            Ad_Category      VARCHAR2(50)  PATH  'AdsNs2:AdCat',
                            Ad_ID            VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="ADId"]/Value',
                            Ad_Status        VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="AdStatus"]/Value',
                            AdSense_Enabled  VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="adSenseEnabled"]/Value',
                            Ad_Type          VARCHAR2(50)  PATH  'AdsNs2/Results:Result[Name="adType"]/Value'
                  ) x;

Error:

ORA-19112: error raised during evaluation:
XVM-01081: [XPST0081] Invalid prefix
1   declare namespace soap="http://schemas.xmlsoap.org/soap/envelope/";declare
-                                                                                ^

19112. 00000 -  "error raised during evaluation: %s"
*Cause:    The error function was called during evaluation of the XQuery expression.
*Action:   Check the detailed error message for the possible causes.
Error at Line: 39 Column: 10

Body:
The last four columns XPath expressions were completely off. Here is how to do it correctly.

SQL

WITH xmltest (id, data_xml) AS (
SELECT 1, XMLTYPE('<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <ResponseHeader xmlns="https://www.google.com/apis/ads/v202005">
      <requestId>123456</requestId>
    </ResponseHeader>
  </soap:Header>
  <soap:Body>
    <getAdsResponse xmlns="https://www.google.com/apis/ads/v202005">
      <getAdsResult>
        <ResultReceived>1</ResultReceived>
        <AdName>Target Comm. Systems</AdName>
        <AdCat>COMMERCIAL</AdCat>
        <SessionID>654321</SessionID>
        <Results>
          <Result><Name>ADId</Name><Value>2372</Value></Result>
          <Result><Name>AdStatus</Name><Value>ACTIVE</Value></Result>
          <Result><Name>targetWindow</Name><Value>TOP</Value></Result>
        </Results>
        <AdSettings>
          <Setting><Name>fontFamily</Name><Value>DEFAULT</Value></Setting>
          <Setting><Name>fontSize</Name><Value>9</Value></Setting>
          <Setting><Name>adSenseEnabled</Name><Value>TRUE</Value></Setting>
          <Setting><Name>adType</Name><Value>TEXT_AND_IMAGE</Value></Setting>
        </AdSettings>
      </getAdsResult>
    </getAdsResponse>
  </soap:Body>
</soap:Envelope>') FROM SYS.DUAL
  )
  SELECT x.Ad_Name,
         x.Ad_Category,
         x.Ad_ID,
         x.Ad_Status,
         x.AdSense_Enabled,
         x.Ad_Type
  FROM   xmltest d,
         XMLTABLE ( XMLNAMESPACES ( 'http://schemas.xmlsoap.org/soap/envelope/'  AS  "soap",
                                    'https://www.google.com/apis/ads/v202005'    AS  "AdsNs2"
                                  ),
                    '/soap:Envelope/soap:Body/AdsNs2:getAdsResponse/AdsNs2:getAdsResult'
                    PASSING d.data_xml
                    COLUMNS Ad_Name          VARCHAR2(50)  PATH  'AdsNs2:AdName',
                            Ad_Category      VARCHAR2(50)  PATH  'AdsNs2:AdCat',
                            Ad_ID            VARCHAR2(50)  PATH  'AdsNs2:Results/AdsNs2:Result[AdsNs2:Name="ADId"]/AdsNs2:Value',
                            Ad_Status        VARCHAR2(50)  PATH  'AdsNs2:Results/AdsNs2:Result[AdsNs2:Name="AdStatus"]/AdsNs2:Value',
                            AdSense_Enabled  VARCHAR2(50)  PATH  'AdsNs2:AdSettings/AdsNs2:Setting[AdsNs2:Name="adSenseEnabled"]/AdsNs2:Value',
                            Ad_Type          VARCHAR2(50)  PATH  'AdsNs2:AdSettings/AdsNs2:Setting[AdsNs2:Name="adType"]/AdsNs2:Value'
                  ) x;