问:
Could not find com.google.firebase:firebase-analytics-ktx:. Required by: project :app
I followed the steps in registering my mobile application in firestore but when I try running the code I get the following error. I have downloaded the google services.json from firestore while registering my app and added it to android/app level of my project. Also I have added 'com.google.firebase:firebase-analytics-ktx' in my android/app/build gradle file

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
   > Could not find com.google.firebase:firebase-analytics-ktx:.
     Required by:
         project :app

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

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

BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

My project level build gradle is as below

```<code>buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.4'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

My app level build gradle is as below

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.ashniz.firestore_time_compare"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics-ktx'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Does anyone know how to fix this issue? Thank you

答:
All you need that update flutter sdk by running that command in terminal:

```<code>flutter upgrade
</code>```

After completing the update, build your new project and link it to firebase but make sure that in 'PROJECT_PATH/android/app/build.gradle', minSdkVersion is 19 or higher.

```<code>applicationId "com.example.flutter_application_1"
    minSdkVersion 19 // here
    targetSdkVersion flutter.targetSdkVersion
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
</code>```

Body:
I followed the steps in registering my mobile application in firestore but when I try running the code I get the following error. I have downloaded the google services.json from firestore while registering my app and added it to android/app level of my project. Also I have added 'com.google.firebase:firebase-analytics-ktx' in my android/app/build gradle file

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
   > Could not find com.google.firebase:firebase-analytics-ktx:.
     Required by:
         project :app

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

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

BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1

My project level build gradle is as below

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.4'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My app level build gradle is as below

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.ashniz.firestore_time_compare"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics-ktx'
}

apply plugin: 'com.google.gms.google-services'

Does anyone know how to fix this issue? Thank you

Body:
All you need that update flutter sdk by running that command in terminal:

flutter upgrade

After completing the update, build your new project and link it to firebase but make sure that in 'PROJECT_PATH/android/app/build.gradle', minSdkVersion is 19 or higher.

applicationId "com.example.flutter_application_1"
    minSdkVersion 19 // here
    targetSdkVersion flutter.targetSdkVersion
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName


来源: stackexchange

问:
Android. Repository with global lifecycle
I have a repository where a chain of network requests is calling. The repository is accessed from the interactor. And interactor is accessed from  viewModel. The view model is attached to activity A. If I go to activity B, which has its own viewModel, then the request chain in the repository of activity A does not complete its execution.

Is it possible to make a repository whose life cycle will be equal to the life cycle of the application. I need all requests to complete even if I go to a new activity.

Please, help me.

答:
This is covered in the Coroutines guide on developer.android.com

```<code>class ArticlesRepository(
    private val articlesDataSource: ArticlesDataSource,
    private val externalScope: CoroutineScope,
    private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
    // As we want to complete bookmarking the article even if the user moves
    // away from the screen, the work is done creating a new coroutine
    // from an external scope
    suspend fun bookmarkArticle(article: Article) {
        externalScope.launch(defaultDispatcher) {
            articlesDataSource.bookmarkArticle(article)
        }
            .join() // Wait for the coroutine to complete
    }
}
</code>```

Here externalScope is defined like this (for a scope with application lifetime):

```<code>class MyApplication : Application() {
  // No need to cancel this scope as it'll be torn down with the process
  val applicationScope = CoroutineScope(SupervisorJob() + otherConfig)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is covered in the Coroutines guide on developer.android.com

class ArticlesRepository(
    private val articlesDataSource: ArticlesDataSource,
    private val externalScope: CoroutineScope,
    private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
    // As we want to complete bookmarking the article even if the user moves
    // away from the screen, the work is done creating a new coroutine
    // from an external scope
    suspend fun bookmarkArticle(article: Article) {
        externalScope.launch(defaultDispatcher) {
            articlesDataSource.bookmarkArticle(article)
        }
            .join() // Wait for the coroutine to complete
    }
}

Here externalScope is defined like this (for a scope with application lifetime):

class MyApplication : Application() {
  // No need to cancel this scope as it'll be torn down with the process
  val applicationScope = CoroutineScope(SupervisorJob() + otherConfig)
}


问:
Laravel 8 Attribute [controller] does not exist
In my route I want to create a group.

Route::controller(ProductController::class)->group(function () {
    dd('Hello World');
});
```

And get the following error message: Attribute [controller] does not exist..

Although it is in the Laravel 8 documentation https://laravel.com/docs/8.x/routing#route-group-controllers I assume that the function does not exist in Laravel 8. Probably an mistake in the documentation!?!?

Note: In Laravel 9 it would work.

答:
In the early versions of Laravel 8, there is no Route Group Controller they introduce it in laravel version 8.80
please check your laravel version to see if it's the 8.80 version or higher
and if it's higher

As of Documentation

```<code>Route::controller(OrderController::class)->group(function () {
    Route::get('/orders/{id}', 'show');
    Route::post('/orders', 'store');
});
</code>```

you didn't mention any routes inside your group like

```<code>Route::controller(OrderController::class)->group(function () {
    Route::get('/orders', function(){
     dd("hello world!")
     });
});
</code>```

https://www.youtube.com/watch?v=M9TkLVrVfWs

https://laravel-news.com/laravel-8-80-0

Body:
In my route I want to create a group.

Route::controller(ProductController::class)->group(function () {
    dd('Hello World');
});

And get the following error message: Attribute [controller] does not exist..

Although it is in the Laravel 8 documentation https://laravel.com/docs/8.x/routing#route-group-controllers I assume that the function does not exist in Laravel 8. Probably an mistake in the documentation!?!?

Note: In Laravel 9 it would work.

Body:
In the early versions of Laravel 8, there is no Route Group Controller they introduce it in laravel version 8.80
please check your laravel version to see if it's the 8.80 version or higher
and if it's higher

As of Documentation

Route::controller(OrderController::class)->group(function () {
    Route::get('/orders/{id}', 'show');
    Route::post('/orders', 'store');
});

you didn't mention any routes inside your group like

Route::controller(OrderController::class)->group(function () {
    Route::get('/orders', function(){
     dd("hello world!")
     });
});

https://www.youtube.com/watch?v=M9TkLVrVfWs

https://laravel-news.com/laravel-8-80-0


问:
Most efficient way to check cells and change neighbors matching a condition in a dataframe
I'm using a pandas dataframe to store a dynamic 2D game map for a rougelike style game map editor. The player can draw and erase rooms. I need to draw walls around these changing rooms.

I have this:

```<code>0  1  2  3  4  5  6
0  .  .  .  x  .  .
1  .  .  x  x  .  .
2  .  x  x  x  .  .
3  .  .  .  .  .  .
4  .  .  .  .  .  .
</code>```

And need this:

```<code>0  1  2  3  4  5  6
0  .  #  #  x  #  .
1  #  #  x  x  #  .
2  #  x  x  x  #  .
3  #  #  #  #  #  .
4  .  .  .  .  .  .
</code>```

What is the most efficient way to do this?

So far I followed the approach outlined here, but this leaves me with some nested if and for before and after the lambda. As I have to check first if a cell is currently dug out. Then check all eight neighbors if they are dug out or not before changing the matching cells. This really takes a tool on the frame rate. I can't be the first to struggle with something like this, but got stuck at finding a solution.

I was hoping to find a way by applying mask or a similar binary comparison. Still, I have no idea how to efficiently do the neighbor checks without falling back into nested loops.

答:
What you want to do is called a binary dilation. You can do this on the underlying numpy array with scipy.ndimage.morphology.binary_dilation:

```<code>from scipy.ndimage.morphology import binary_dilation
import numpy as np

a = df.eq('x').to_numpy()
# [[False False  True  True  True False]
#  [False  True  True  True  True False]
#  [ True  True  True  True  True False]
#  [False  True  True  True False False]
#  [False False False False False False]]

df = pd.DataFrame(np.where(binary_dilation(a), 'x', df))
</code>```

output:

```<code>   0  1  2  3  4  5
0  .  .  x  x  x  .
1  .  x  x  x  x  .
2  x  x  x  x  x  .
3  .  x  x  x  .  .
4  .  .  .  .  .  .
</code>```

Now to get a different symbol, you can use a more complex mask (binary_dilation(a)^a) with a XOR operation (^):

```<code>a = df.eq('x').to_numpy()
df = pd.DataFrame(np.where(binary_dilation(a)^a, '#', df))
</code>```

output:

```<code>   0  1  2  3  4  5
0  .  .  #  x  #  .
1  .  #  x  x  #  .
2  #  x  x  x  #  .
3  .  #  #  #  .  .
4  .  .  .  .  .  .
</code>```

all neighbors

Use a different structuring element (here a 3x3 matrix of 1s):

```<code>from scipy.ndimage.morphology import binary_dilation

a = df.eq('x').to_numpy()
kernel = np.ones((3,3))

df = pd.DataFrame(np.where(binary_dilation(a, kernel)^a, '#', df))
</code>```

output:

```<code>   0  1  2  3  4  5
0  .  #  #  x  #  .
1  #  #  x  x  #  .
2  #  x  x  x  #  .
3  #  #  #  #  #  .
4  .  .  .  .  .  .
</code>```

other kernels

You can easily adapt the code to have any combination of neighbors

example: top left

```<code>kernel = np.array([[1, 1, 0],
                   [1, 1, 0],
                   [0, 0, 0]])

   0  1  2  3  4  5
0  .  #  #  x  .  .
1  #  #  x  x  .  .
2  #  x  x  x  .  .
3  .  .  .  .  .  .
4  .  .  .  .  .  .
</code>```

Body:
I'm using a pandas dataframe to store a dynamic 2D game map for a rougelike style game map editor. The player can draw and erase rooms. I need to draw walls around these changing rooms.

I have this:

0  1  2  3  4  5  6
0  .  .  .  x  .  .
1  .  .  x  x  .  .
2  .  x  x  x  .  .
3  .  .  .  .  .  .
4  .  .  .  .  .  .

And need this:

0  1  2  3  4  5  6
0  .  #  #  x  #  .
1  #  #  x  x  #  .
2  #  x  x  x  #  .
3  #  #  #  #  #  .
4  .  .  .  .  .  .

What is the most efficient way to do this?

So far I followed the approach outlined here, but this leaves me with some nested if and for before and after the lambda. As I have to check first if a cell is currently dug out. Then check all eight neighbors if they are dug out or not before changing the matching cells. This really takes a tool on the frame rate. I can't be the first to struggle with something like this, but got stuck at finding a solution.

I was hoping to find a way by applying mask or a similar binary comparison. Still, I have no idea how to efficiently do the neighbor checks without falling back into nested loops.

Body:
What you want to do is called a binary dilation. You can do this on the underlying numpy array with scipy.ndimage.morphology.binary_dilation:

from scipy.ndimage.morphology import binary_dilation
import numpy as np

a = df.eq('x').to_numpy()
# [[False False  True  True  True False]
#  [False  True  True  True  True False]
#  [ True  True  True  True  True False]
#  [False  True  True  True False False]
#  [False False False False False False]]

df = pd.DataFrame(np.where(binary_dilation(a), 'x', df))

output:

   0  1  2  3  4  5
0  .  .  x  x  x  .
1  .  x  x  x  x  .
2  x  x  x  x  x  .
3  .  x  x  x  .  .
4  .  .  .  .  .  .

Now to get a different symbol, you can use a more complex mask (binary_dilation(a)^a) with a XOR operation (^):

a = df.eq('x').to_numpy()
df = pd.DataFrame(np.where(binary_dilation(a)^a, '#', df))

output:

   0  1  2  3  4  5
0  .  .  #  x  #  .
1  .  #  x  x  #  .
2  #  x  x  x  #  .
3  .  #  #  #  .  .
4  .  .  .  .  .  .

all neighbors

Use a different structuring element (here a 3x3 matrix of 1s):

from scipy.ndimage.morphology import binary_dilation

a = df.eq('x').to_numpy()
kernel = np.ones((3,3))

df = pd.DataFrame(np.where(binary_dilation(a, kernel)^a, '#', df))

output:

   0  1  2  3  4  5
0  .  #  #  x  #  .
1  #  #  x  x  #  .
2  #  x  x  x  #  .
3  #  #  #  #  #  .
4  .  .  .  .  .  .

other kernels

You can easily adapt the code to have any combination of neighbors

example: top left

kernel = np.array([[1, 1, 0],
                   [1, 1, 0],
                   [0, 0, 0]])

   0  1  2  3  4  5
0  .  #  #  x  .  .
1  #  #  x  x  .  .
2  #  x  x  x  .  .
3  .  .  .  .  .  .
4  .  .  .  .  .  .


问:
Getting many errors and warnings just after creating a dotnet wpf project from the terminal
I was going to create my first wpf project and I ran the command dotnet new wpf -o gui and the folder was created but when I opened some of the files I started getting many errors. Here is the list-:

App.xaml.cs-

The type or namespace name 'Application' could not be found (are you missing a using directive or an assembly reference?) [c#]

AssemblyInfo.cs-

The type or namespace name 'ThemeInfoAttribute' could not be found (are you missing a using directive or an assembly reference?) [c#]

The type or namespace name 'ThemeInfo' could not be found (are you missing a using directive or an assembly reference?) [c#]

The name 'ResourceDictionaryLocation' does not exist in the current context [c#]

The name 'ResourceDictionaryLocation' does not exist in the current context [c#]

MainWindow.xaml.cs-

The type or namespace name 'Controls' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [c#]

The type or namespace name 'Data' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [c#]

The type or namespace name 'Documents' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [c#]

The type or namespace name 'Media' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [c#]

The type or namespace name 'Media' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [c#]

The type or namespace name 'Navigation' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [c#]

The type or namespace name 'Shapes' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [c#]

The type or namespace name 'Window' could not be found (are you missing a using directive or an assembly reference?) [c#]

The name 'InitializeComponent' does not exist in the current context [c#]

When I build and run the program it works fine. Please tell me how to fix these errors.

Here is the code in App.Xaml.cs-

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace gui
{
    ///
    /// Interaction logic for App.xaml
    ///
    public partial class App : Application
    {
    }
}
```

答: Sometimes Visual Studio is going crazy. Try to turn off and on this program and see if you still have this errors. Also copy and paste the code from the App.xaml.cs so we can see what's there.</p>


问:
displays as undefined if person dosen't chat discord js v12
Image of users displaying as undefined
I wan't to display usernames instead of pinging user in the leaderboard embed?
At this point i have no idea what to do i asked people to help and couldn't figure it out. Image it says undefined until member chats.

Leaberboard command file

```<code>         let UserJSON = JSON.parse(Fs.readFileSync("./DataBase/users.json"));
        var Sorted = Object.entries(UserJSON).sort((a, b) => b[1].money- a[1].money);
        if (Sorted.length > 10) Sorted = Sorted.slice(0, 10);

        var LBString = "";
        Sorted.forEach(user => {
            LBString += `${client.users.cache.find(u => u.id == user[0])} - ${user[1].money}\n`;
        });
        var LBEmbed = new Discord.MessageEmbed()
            .setColor('#FFFFFF')
            .setTitle("**Coins Leaderboard**")
            .setDescription(LBString);
        message.channel.send(LBEmbed);
        client.channels.cache.get('941016208940077086').send(`${message.author.username} has used $coinslb`)

//users.json file
{"599675959888707594":{"money":492,"lastbeg":1644580691540,"lastwork":1644580757380},"617797297924866093":{"money":0,"lastbeg":0,"lastwork":0}}
</code>```

I want the leaderboard to display usernames not @ them in the embed

答:
After user[0]), put .username to get only the username, like this:

LBString += `${client.users.cache.find(u => u.id == user[0]).username} - ${user[1].money}\n`;
```
<p>Also, it shows <code>undefined</code> when they haven't chatted before because they aren't in your database. You could get the guild (server) you're in and fetch the member by ID, instead of from cache:</p>
<pre class="lang-js prettyprint-override"><code>guild.members.fetch('user_id_here').username;
</code>```

Body:
Image of users displaying as undefined
I wan't to display usernames instead of pinging user in the leaderboard embed?
At this point i have no idea what to do i asked people to help and couldn't figure it out. Image it says undefined until member chats.

Leaberboard command file

         let UserJSON = JSON.parse(Fs.readFileSync("./DataBase/users.json"));
        var Sorted = Object.entries(UserJSON).sort((a, b) => b[1].money- a[1].money);
        if (Sorted.length > 10) Sorted = Sorted.slice(0, 10);

        var LBString = "";
        Sorted.forEach(user => {
            LBString += `${client.users.cache.find(u => u.id == user[0])} - ${user[1].money}\n`;
        });
        var LBEmbed = new Discord.MessageEmbed()
            .setColor('#FFFFFF')
            .setTitle("**Coins Leaderboard**")
            .setDescription(LBString);
        message.channel.send(LBEmbed);
        client.channels.cache.get('941016208940077086').send(`${message.author.username} has used $coinslb`)

//users.json file
{"599675959888707594":{"money":492,"lastbeg":1644580691540,"lastwork":1644580757380},"617797297924866093":{"money":0,"lastbeg":0,"lastwork":0}}

I want the leaderboard to display usernames not @ them in the embed

Body:
After user[0]), put .username to get only the username, like this:

LBString += `${client.users.cache.find(u => u.id == user[0]).username} - ${user[1].money}\n`;

Also, it shows undefined when they haven't chatted before because they aren't in your database. You could get the guild (server) you're in and fetch the member by ID, instead of from cache:

guild.members.fetch('user_id_here').username;


问:
find xpath element using a variable
im looking to find an element in a schema based on the value of a variable (that changes each time i iterate).  the catch is the element could be anywhere inside the schema.

for instance:

```<code><...
  <foo>
    <bar>
       <bar1>BB</bar1>
       <bar2>CC</bar2>
    </bar>
    <rab>
       <rab1>DD</rab1>
    </rab>
  </foo>
/...>
</code>```

$attribute = bar1
(then the next iteration, $attribute may equal rab1)

how would i write an expression that could find me: .../foo/bar/$attribute

the closest thing i can find is ...//*[name()=$attribute] but it doesn't work. is there any other way?

Thanks for your help!

答:
Although the question leaves out a lot of details that may be important, you could try changing name() to local-name():

```<code>...//*[local-name()='bar1']
</code>```

and see if that fixes the problem. The return value of name() includes any prefix the element name has, which could cause it not to match the value of $attribute. (@Kirill was hinting at this.)

If that doesn't solve the problem, provide more context: What is the full XPath expression? How is it being used in XSLT? How do you know it "doesn't work"? (Give expected results and actual results.)

ContentLicense: CC BY-SA 3.0

Title: find xpath element using a variable

Body:
im looking to find an element in a schema based on the value of a variable (that changes each time i iterate).  the catch is the element could be anywhere inside the schema.

for instance:

<...
  <foo>
    <bar>
       <bar1>BB</bar1>
       <bar2>CC</bar2>
    </bar>
    <rab>
       <rab1>DD</rab1>
    </rab>
  </foo>
/...>

$attribute = bar1
(then the next iteration, $attribute may equal rab1)

how would i write an expression that could find me: .../foo/bar/$attribute

the closest thing i can find is ...//*[name()=$attribute] but it doesn't work. is there any other way?

Thanks for your help!

Body:
Although the question leaves out a lot of details that may be important, you could try changing name() to local-name():

...//*[local-name()='bar1']

and see if that fixes the problem. The return value of name() includes any prefix the element name has, which could cause it not to match the value of $attribute. (@Kirill was hinting at this.)

If that doesn't solve the problem, provide more context: What is the full XPath expression? How is it being used in XSLT? How do you know it "doesn't work"? (Give expected results and actual results.)


问:
Android Studio 4.2 Kotlin Plugin Issue
Cannot build a new project using Android Studio 4.2 because of the following error:

```<code>A problem occurred configuring root project 'My Application'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0-release-764.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.0-release-764/kotlin-gradle-plugin-1.5.0-release-764.pom
       - https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.0-release-764/kotlin-gradle-plugin-1.5.0-release-764.pom
     Required by:
         project :

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html
</code>```

When I changed the Kotlin plugin version from ext.kotlin_version = "1.5.0-release-764" to ext.kotlin_version = "1.5.0" app builds successfully but the following warning appears:

```<code>Kotlin version that is used for building with Gradle (1.5.0) differs from the one bundled into the IDE plugin (1.5.0-release-764)
</code>```

答:
if you work on flutter project ,you just need to update flutter sdk run that command in terminal:

```<code>flutter upgrade
</code>```

After updating , new flutter version  will fix that errors automatically.

Title: Android Studio 4.2 Kotlin Plugin Issue

Body:
Cannot build a new project using Android Studio 4.2 because of the following error:

A problem occurred configuring root project 'My Application'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0-release-764.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.0-release-764/kotlin-gradle-plugin-1.5.0-release-764.pom
       - https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.0-release-764/kotlin-gradle-plugin-1.5.0-release-764.pom
     Required by:
         project :

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

When I changed the Kotlin plugin version from ext.kotlin_version = "1.5.0-release-764" to ext.kotlin_version = "1.5.0" app builds successfully but the following warning appears:

Kotlin version that is used for building with Gradle (1.5.0) differs from the one bundled into the IDE plugin (1.5.0-release-764)

Body:
if you work on flutter project ,you just need to update flutter sdk run that command in terminal:

flutter upgrade

After updating , new flutter version  will fix that errors automatically.


问:
Lazy mode of recursive function
I'm going to find a solution to this problem:

Splitting given list to sublist with given sub-list length and skip length, for example:

groupEvery 3 1 [1..6] = [[1,2,3], [2,3,4], [3,4,5], [4,5,6]]
groupEvery 3 2 "abcdefghij" = [ "abc", "cde", "efg", "ghi", "ij"]
```
<p>The <code>groupEvery n p l</code> args details are:</p>
<ul>
<li>n is length of sub-list: Int</li>
<li>f is length of skip: Int</li>
<li>xs is input list: [a]</li>
</ul>
<p>Here is my solution:</p>
<pre class="lang-haskell prettyprint-override"><code>groupEvery :: Int -> Int -> [a] -> [[a]] -> [[a]]
groupEvery n p xs acc
    | length xs <= n = acc ++ [xs]
    | otherwise = groupEvery n p dropped (acc++[segment])
        where
            dropped = drop p xs
            segment = take n xs
</code>```

But this solution is not lazy, for example take 3 Lib2.groupEvery 3 1 [1..] [] never finished.
My question is about

Better solutions for the groupEvery function ?

How we can write recursive lazy function that accumulate some data ? In other words is there any structure for this kind of recursive functions that accumulate results and are lazy ?

答:
The main problem is that you use an accumulator and only return the list when you walked over the entire input list. Furthermore length l will  walk through the entire list. You don't need to calculate the length. This is also inefficient: if the list is long it will each time make a linear run.

You can pattern match on the list and for an empty list return an empty list and for a non-empty list yield the take n xs and recurse with drop p xs.

```<code>groupEvery :: Int -> Int -> [a] -> [[a]]
groupEvery _ _ [] = []
groupEvery n p xs = take n xs : groupEvery n p (drop p xs)
</code>```

This thus produces:

```<code>ghci> take 3 (groupEvery 3 1 [1..])
[[1,2,3],[2,3,4],[3,4,5]]
</code>```

You can further improve the function by combining take n and drop p such that you only walk over the min n p parts of the list once. I leave that as an exercise.

Title: Lazy mode of recursive function

Body:
I'm going to find a solution to this problem:

Splitting given list to sublist with given sub-list length and skip length, for example:

groupEvery 3 1 [1..6] = [[1,2,3], [2,3,4], [3,4,5], [4,5,6]]
groupEvery 3 2 "abcdefghij" = [ "abc", "cde", "efg", "ghi", "ij"]

The groupEvery n p l args details are:

n is length of sub-list: Int

f is length of skip: Int

xs is input list: [a]

Here is my solution:

groupEvery :: Int -> Int -> [a] -> [[a]] -> [[a]]
groupEvery n p xs acc
    | length xs <= n = acc ++ [xs]
    | otherwise = groupEvery n p dropped (acc++[segment])
        where
            dropped = drop p xs
            segment = take n xs

But this solution is not lazy, for example take 3 Lib2.groupEvery 3 1 [1..] [] never finished.
My question is about

Better solutions for the groupEvery function ?

How we can write recursive lazy function that accumulate some data ? In other words is there any structure for this kind of recursive functions that accumulate results and are lazy ?

Body:
The main problem is that you use an accumulator and only return the list when you walked over the entire input list. Furthermore length l will  walk through the entire list. You don't need to calculate the length. This is also inefficient: if the list is long it will each time make a linear run.

You can pattern match on the list and for an empty list return an empty list and for a non-empty list yield the take n xs and recurse with drop p xs.

groupEvery :: Int -> Int -> [a] -> [[a]]
groupEvery _ _ [] = []
groupEvery n p xs = take n xs : groupEvery n p (drop p xs)

This thus produces:

ghci> take 3 (groupEvery 3 1 [1..])
[[1,2,3],[2,3,4],[3,4,5]]

You can further improve the function by combining take n and drop p such that you only walk over the min n p parts of the list once. I leave that as an exercise.


问:
The argument type 'Iterable<dynamic>' can't be assigned to the parameter type 'List<DropdownMenuItem<String>>?'

DropdownButton<String>(
              value: value,
              items: locationItems.map( DropdownMenuItem<String>(
                child: Text( widget.locationName ),
                value: "${widget.locationName}",
              )
              ),

```

答:
Map returns iteratable. Try to convert it to list.</p>
```<code>DropdownButton<String>(
              value: value,
              items: locationItems.map( DropdownMenuItem<String>(
                child: Text( widget.locationName ),
                value: "${widget.locationName}",
              )
              ).toList<DropdownMenuItem<String>>(),

</code>```

Body:
Map returns iteratable. Try to convert it to list.

DropdownButton<String>(
              value: value,
              items: locationItems.map( DropdownMenuItem<String>(
                child: Text( widget.locationName ),
                value: "${widget.locationName}",
              )
              ).toList<DropdownMenuItem<String>>(),


问:
Error in the Log cat Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
I have been using three button for this but for the good ui I chose to use 3 check boxes and a single button. Before the change everything was working fine but after the changes I did the button started throwing null pointer exception. I checked the ID of other buttons I used in the project and also the layout in which the button is present and the layout to which the java file is pointing is same. Still not able to resolve this error. Can anyone please tell me where I am doing wrong.

The XML code which points the BabyDetails activity below.

```<code><CheckBox
        android:id="@+id/years03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/age_group"
        android:layout_marginStart="100dp"
        android:layout_marginTop="20dp"
        android:fontFamily="@font/poppinsbold"
        android:text="0-3 years"
        android:textColor="@color/black"
        android:textSize="18sp" />
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:layout_marginStart="100dp"
        android:layout_below="@+id/age_group"
        android:text="3-6 years"
        android:fontFamily="@font/poppinsbold"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:id="@+id/years36"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/age_group"
        android:layout_marginStart="100dp"
        android:layout_marginTop="100dp"
        android:text="6-9 years"
        android:fontFamily="@font/poppinsbold"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:id="@+id/years69"/>

    <Button
        android:id="@+id/gotohome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/years69"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/round_button"
        android:backgroundTint="#4C0027"
        android:fontFamily="@font/poppinsbold"
        android:text="  Next  "
        android:textSize="22sp" />
</code>```

This is the class where the Button's action takes place.

```<code>public class BabyDetails extends AppCompatActivity {
CheckBox cb1,cb2,cb3;
Button gotohome;
private Baby baby;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_baby_details);
    cb1 = findViewById(R.id.years03);
    cb2 = findViewById(R.id.years36);
    cb3 = findViewById(R.id.years69);
    gotohome = findViewById(R.id.gotohome);

    gotohome.setOnClickListener(v -> {
        try {

            if(cb1.isChecked()){
                baby.setBaby_name(et_baby.getText().toString());
                baby.setBirthdate(et_date.getText().toString());
                baby.setGender(radioButton.getText().toString());
                baby.setAge("0-3 years");
                Long id = dbaseBaby.addBaby(baby);
                dbaseBaby.addBaby(baby);

                Intent intent = new Intent(BabyDetails.this, Home.class);
                intent.putExtra("added_id",id);
                startActivity(intent);
                finish();
            }

            else if(cb2.isChecked()){
                baby.setBaby_name(et_baby.getText().toString());
                baby.setBirthdate(et_date.getText().toString());
                baby.setGender(radioButton.getText().toString());
                baby.setAge("3-6 years");
                Long id = dbaseBaby.addBaby(baby);
                dbaseBaby.addBaby(baby);

                Intent intent = new Intent(BabyDetails.this, Home2.class);
                intent.putExtra("added_id",id);
                startActivity(intent);
                finish();
            }
            else if(cb3.isChecked()){
                baby.setBaby_name(et_baby.getText().toString());
                baby.setBirthdate(et_date.getText().toString());
                baby.setGender(radioButton.getText().toString());
                baby.setAge("6-9 years");
                Long id = dbaseBaby.addBaby(baby);
                dbaseBaby.addBaby(baby);

                Intent intent = new Intent(BabyDetails.this, Home3.class);
                intent.putExtra("added_id",id);
                startActivity(intent);
                finish();
            }
            Toast.makeText(BabyDetails.this, "Login Successful", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    });

</code>```

The error in the Log cat:

```<code>   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.kidcave.pediacare.BabyDetails.onCreate(BabyDetails.java:50)
</code>```

答:
Just a small change was required to resolve the issue. I had defined the button above the initobject function where my database was defined but after changing it works perfectly</p>
```<code>    initview();
    initObject();
    cb1 = findViewById(R.id.years03);
    cb2 = findViewById(R.id.years36);
    cb3 = findViewById(R.id.years69);
    gotohome = findViewById(R.id.next03);
</code>```

Body:
I have been using three button for this but for the good ui I chose to use 3 check boxes and a single button. Before the change everything was working fine but after the changes I did the button started throwing null pointer exception. I checked the ID of other buttons I used in the project and also the layout in which the button is present and the layout to which the java file is pointing is same. Still not able to resolve this error. Can anyone please tell me where I am doing wrong.

The XML code which points the BabyDetails activity below.

<CheckBox
        android:id="@+id/years03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/age_group"
        android:layout_marginStart="100dp"
        android:layout_marginTop="20dp"
        android:fontFamily="@font/poppinsbold"
        android:text="0-3 years"
        android:textColor="@color/black"
        android:textSize="18sp" />
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:layout_marginStart="100dp"
        android:layout_below="@+id/age_group"
        android:text="3-6 years"
        android:fontFamily="@font/poppinsbold"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:id="@+id/years36"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/age_group"
        android:layout_marginStart="100dp"
        android:layout_marginTop="100dp"
        android:text="6-9 years"
        android:fontFamily="@font/poppinsbold"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:id="@+id/years69"/>

    <Button
        android:id="@+id/gotohome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/years69"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/round_button"
        android:backgroundTint="#4C0027"
        android:fontFamily="@font/poppinsbold"
        android:text="  Next  "
        android:textSize="22sp" />

This is the class where the Button's action takes place.

public class BabyDetails extends AppCompatActivity {
CheckBox cb1,cb2,cb3;
Button gotohome;
private Baby baby;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_baby_details);
    cb1 = findViewById(R.id.years03);
    cb2 = findViewById(R.id.years36);
    cb3 = findViewById(R.id.years69);
    gotohome = findViewById(R.id.gotohome);

    gotohome.setOnClickListener(v -> {
        try {

            if(cb1.isChecked()){
                baby.setBaby_name(et_baby.getText().toString());
                baby.setBirthdate(et_date.getText().toString());
                baby.setGender(radioButton.getText().toString());
                baby.setAge("0-3 years");
                Long id = dbaseBaby.addBaby(baby);
                dbaseBaby.addBaby(baby);

                Intent intent = new Intent(BabyDetails.this, Home.class);
                intent.putExtra("added_id",id);
                startActivity(intent);
                finish();
            }

            else if(cb2.isChecked()){
                baby.setBaby_name(et_baby.getText().toString());
                baby.setBirthdate(et_date.getText().toString());
                baby.setGender(radioButton.getText().toString());
                baby.setAge("3-6 years");
                Long id = dbaseBaby.addBaby(baby);
                dbaseBaby.addBaby(baby);

                Intent intent = new Intent(BabyDetails.this, Home2.class);
                intent.putExtra("added_id",id);
                startActivity(intent);
                finish();
            }
            else if(cb3.isChecked()){
                baby.setBaby_name(et_baby.getText().toString());
                baby.setBirthdate(et_date.getText().toString());
                baby.setGender(radioButton.getText().toString());
                baby.setAge("6-9 years");
                Long id = dbaseBaby.addBaby(baby);
                dbaseBaby.addBaby(baby);

                Intent intent = new Intent(BabyDetails.this, Home3.class);
                intent.putExtra("added_id",id);
                startActivity(intent);
                finish();
            }
            Toast.makeText(BabyDetails.this, "Login Successful", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    });

The error in the Log cat:

   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.kidcave.pediacare.BabyDetails.onCreate(BabyDetails.java:50)

Body:
Just a small change was required to resolve the issue. I had defined the button above the initobject function where my database was defined but after changing it works perfectly

    initview();
    initObject();
    cb1 = findViewById(R.id.years03);
    cb2 = findViewById(R.id.years36);
    cb3 = findViewById(R.id.years69);
    gotohome = findViewById(R.id.next03);


问:
Xcode : failed to get the task for process
This is for an existing app that compiled and distributed multiple times. Since updating to Xcode 5 I have this error popping.

I have my developers profile selected in the Code Signing for debug.

Deleted the Derived Data a few times.

Quit a few times

Downloaded and tried to re-add my Developers certificates.

Reset my computer! And checked updates

Tried using black magic!

The Scheme > Build Configuration is set to Debug

The odd circumstances I am compiling to compile to iOS 6.1 so I can run on my iPhone 3GS - the base is SDK iOS 7? Could this be an issue? I just need to test it before finding a newer phone to before change it to iOS 7.

答:
This link works for me

Choose the problematic scheme

Edit Scheme

Choose Run

Uncheck “Debug executable”

Clean Derived Data: ⌘ Cmd + ↑ Shift + K

Run the app again: ⌘ Cmd + R


问:
How to fix 'The project you were looking for could not be found' when using git clone
I am trying to clone a project from gitlab to my local machine. I have been granted rights as a developer, and use the command 'git clone

None of the protocols work (ssh and https neither work)

The error message I am getting:

```<code>remote: The project you were looking for could not be found.
fatal: repository 'https://gitlab.com/KZA_Connected/skilltree.git/' not found
</code>```

Any help would be highly appreciated.

答:
Put username before the url like this:

```<code>git clone https://username@repo.abc.com/projectname.git
</code>```

To add git to an existing folder accordingly:

```<code>git remote add origin https://username@repo.abc.com/projectname.git
</code>```

Body:
I am trying to clone a project from gitlab to my local machine. I have been granted rights as a developer, and use the command 'git clone

None of the protocols work (ssh and https neither work)

The error message I am getting:

remote: The project you were looking for could not be found.
fatal: repository 'https://gitlab.com/KZA_Connected/skilltree.git/' not found

Any help would be highly appreciated.

Body:
Put username before the url like this:

git clone https://username@repo.abc.com/projectname.git

To add git to an existing folder accordingly:

git remote add origin https://username@repo.abc.com/projectname.git


问:
How to join multiple distinct rows in one column
I have 3 tables

Restaurants table:

restaurant_id
restaurant_name

1
Burger King

2
Coffee shop

Foods table:

food_id
food_title
category_id
restaurant_id

1
Burger with cheese
1
1

2
Beef Burger
2
1

3
Beef Burger with cheese
2
1

4
Iced Coffee
3
2

5
Dark Coffee
3
2

5
Green Tea
4
2

Categories table:

category_id
category_title

1
Normal Burger

2
Beef Burger

3
Coffee

4
Tea

The output I'm looking for:

restaurant_id
restaurant_name
categories_list

1
Burger King
[{category_id: 1, category_title: 'Normal Burger'}, {category_id: 2, category_title: 'Beef Burger'}]

2
Coffee shop
[{category_id: 3, category_title: 'Coffee'}, {category_id: 4, category_title: 'Tea'}]

答:
Try:

```<code>    select restaurant_id,restaurant_name,concat('[',group_concat(my_col),']') as tot_result
from ( select r.restaurant_id,r.restaurant_name,concat('{category_id: ', c.category_id," category_title: '",c.category_title ,"'}") as my_col
       from Restaurants r
       inner join Foods f on r.restaurant_id=f.restaurant_id
       inner join Categories c on c.category_id=f.category_id
       group by r.restaurant_id,r.restaurant_name,my_col
     ) as t1
group by restaurant_id,restaurant_name;
</code>```

Result:

```<code>restaurant_id   restaurant_name   tot_result
    1            Burger King    [{category_id: 1 category_title: 'Normal Burger'},{category_id: 2 category_title: 'Beef Burger'}]
    2            Coffee shop    [{category_id: 3 category_title: 'Coffee'},{category_id: 4 category_title: 'Tea'}]
</code>```

Demo

Body:
Try:

    select restaurant_id,restaurant_name,concat('[',group_concat(my_col),']') as tot_result
from ( select r.restaurant_id,r.restaurant_name,concat('{category_id: ', c.category_id," category_title: '",c.category_title ,"'}") as my_col
       from Restaurants r
       inner join Foods f on r.restaurant_id=f.restaurant_id
       inner join Categories c on c.category_id=f.category_id
       group by r.restaurant_id,r.restaurant_name,my_col
     ) as t1
group by restaurant_id,restaurant_name;

Result:

restaurant_id   restaurant_name   tot_result
    1            Burger King    [{category_id: 1 category_title: 'Normal Burger'},{category_id: 2 category_title: 'Beef Burger'}]
    2            Coffee shop    [{category_id: 3 category_title: 'Coffee'},{category_id: 4 category_title: 'Tea'}]

Demo


问:
Cypress sees undefined when reffering to an aliased text value
My test results in adding a row to the table. In afterEach hook I wanted to add a method to delete the newest row after the test ran so I wrote this piece of code:

```<code>deleteTheNewestRequest() {
    cy.get('table#return-request-list').find('tr').eq(1).then( firstRow => {
        cy.wrap(firstRow).find('td').eq(0).invoke('text').as('rowId')
        cy.wrap(firstRow).find('a[title="Delete"]').click()
        cy.get('button.btn-delete-return-request').click()
        cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)
    })
}
</code>```

With 'then' I'm saving a table element to later use to find and operate on the elements inside it. I wanted to first save the value of the newest row in the table that was added after the test ran successfully, then delete and as the last step make sure that the row with the ID that was deleted is actually gone from the table. The problem is that cypress test runner assertions marks it green because it sees that value of  is not equal to 'undefined' and not, let's say 3794.

答:
When you delete the row, it is removed from the DOM but the test still has a pointer to it (the firstRow variable), preventing the garbage collector from removing it from memory.

So  cy.wrap(firstRow) is still pointing to the complete row, and it still has the same rowId.

You want to test what the user sees, that firstRow is no longer in the DOM.

//cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)  // not this
cy.wrap(firstRow).should(firstRow => {
  expect(Cypress.dom.isAttached(firstRow)).to.eq(false)
})
```
<p>Or test that no rows in the DOM have the rowId</p>
<pre class="lang-js prettyprint-override"><code>cy.get('@rowId').then(rowId => {
  cy.contains('tr', rowId).should('not.exist')
})
</code>```

Body:
My test results in adding a row to the table. In afterEach hook I wanted to add a method to delete the newest row after the test ran so I wrote this piece of code:

deleteTheNewestRequest() {
    cy.get('table#return-request-list').find('tr').eq(1).then( firstRow => {
        cy.wrap(firstRow).find('td').eq(0).invoke('text').as('rowId')
        cy.wrap(firstRow).find('a[title="Delete"]').click()
        cy.get('button.btn-delete-return-request').click()
        cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)
    })
}

With 'then' I'm saving a table element to later use to find and operate on the elements inside it. I wanted to first save the value of the newest row in the table that was added after the test ran successfully, then delete and as the last step make sure that the row with the ID that was deleted is actually gone from the table. The problem is that cypress test runner assertions marks it green because it sees that value of  is not equal to 'undefined' and not, let's say 3794.

Body:
When you delete the row, it is removed from the DOM but the test still has a pointer to it (the firstRow variable), preventing the garbage collector from removing it from memory.

So  cy.wrap(firstRow) is still pointing to the complete row, and it still has the same rowId.

You want to test what the user sees, that firstRow is no longer in the DOM.

//cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)  // not this
cy.wrap(firstRow).should(firstRow => {
  expect(Cypress.dom.isAttached(firstRow)).to.eq(false)
})

Or test that no rows in the DOM have the rowId

cy.get('@rowId').then(rowId => {
  cy.contains('tr', rowId).should('not.exist')
})


问:
Cannot generate .abi and .bin files when Smartcontract contains the Openzeppelin import
I started using web3j and I want to generate smart contract wrapper. According to documentation, it can be done this way:

```<code>web3j generate solidity -b /path/to/<smart-contract>.bin -a /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name
</code>```

And this works very good. You need .bin and .abi files for it.
It's easy to generate as well with this command:

```<code>solcjs <contract>.sol --abi --bin
</code>```

On contracts where I don't import Openzeppelin, this works great. But on contracts where I do import Openzeppelin, I get an error when calling the solcjs command:

```<code>ParserError: Source "@openzeppelin/contracts/token/ERC721/ERC721.sol" not found: File not found inside the base path or any of the include paths.
 --> MyNFT.sol:5:1:
  |
5 | import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

ParserError: Source "@openzeppelin/contracts/utils/Counters.sol" not found: File not found inside the base path or any of the include paths.
 --> MyNFT.sol:6:1:
  |
6 | import "@openzeppelin/contracts/utils/Counters.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

ParserError: Source "@openzeppelin/contracts/access/Ownable.sol" not found: File not found inside the base path or any of the include paths.
 --> MyNFT.sol:7:1:
  |
7 | import "@openzeppelin/contracts/access/Ownable.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

Syntax how I import this library in smart contract in Solidity:

```<code>import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
</code>```

I use pragma solidity >=0.7.3;

Smartcontract is valid, I compiled it with hardhat with no problem.

I imported openzeppelin version - @openzeppelin/contracts@3.1.0-solc-0.7

Where those files should be to be able generate .abi and .bin files? Thank you for help.

答:
I had the same error, and finally found the solution nowhere else, but the GitHub page of the Solidity compiler itself! See this.

To compile a contract that imports other contracts via relative paths:

solcjs --bin --include-path node_modules/ --base-path . MainContract.sol

Use the --base-path and --include-path options to describe the layout of your project. --base-path represents the root of your own source tree while --include-path allows you to specify extra locations containing external code (e.g. libraries installed with a package manager).

Note: ensure that all the files you specify on the command line are located inside the base path or one of the include paths. The compiler refers to files from outside of these directories using absolute paths. Having absolute paths in contract metadata will result in your bytecode being reproducible only when it's placed in these exact absolute locations.

Assuming that all your packages (including OpenZeppelin) are nicely organized within a single node_modules directory (probably a local one that you created for your project), just replace node_modules/ with the path to this node-modules directory. And similarly, replace . with the path to the directory which contains the contract you are compiling.

The only issue with compiling the contract this way, is that it generates ABI files for all contracts, including the ones that you have imported to the main contract (and the ones they import, and so on). I don't know if there's any command line option which specifies which ABI files to produce (for example, to produce only the ABI file for MainContract.sol).

PS: You can also specify the output directory for your .abi and .bin output files using the -o option. This turns out to be very helpful specially when a large number of output files are being produced.

Body:
I started using web3j and I want to generate smart contract wrapper. According to documentation, it can be done this way:

web3j generate solidity -b /path/to/<smart-contract>.bin -a /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name

And this works very good. You need .bin and .abi files for it.
It's easy to generate as well with this command:

solcjs <contract>.sol --abi --bin

On contracts where I don't import Openzeppelin, this works great. But on contracts where I do import Openzeppelin, I get an error when calling the solcjs command:

ParserError: Source "@openzeppelin/contracts/token/ERC721/ERC721.sol" not found: File not found inside the base path or any of the include paths.
 --> MyNFT.sol:5:1:
  |
5 | import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

ParserError: Source "@openzeppelin/contracts/utils/Counters.sol" not found: File not found inside the base path or any of the include paths.
 --> MyNFT.sol:6:1:
  |
6 | import "@openzeppelin/contracts/utils/Counters.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

ParserError: Source "@openzeppelin/contracts/access/Ownable.sol" not found: File not found inside the base path or any of the include paths.
 --> MyNFT.sol:7:1:
  |
7 | import "@openzeppelin/contracts/access/Ownable.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Syntax how I import this library in smart contract in Solidity:

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

I use pragma solidity >=0.7.3;

Smartcontract is valid, I compiled it with hardhat with no problem.

I imported openzeppelin version - @openzeppelin/contracts@3.1.0-solc-0.7

Where those files should be to be able generate .abi and .bin files? Thank you for help.


问:
How to write a unit test for a React.js project?
I am doing a web-based e-commerce site. Now I need to perform unit testing. Are there any tools required for unit testing?</p>

答:
There are a couple of testing frameworks and libraries for this.

The ones I use are Jest and React Testing Library

There is a curve for the setup but if you are using create-react-app it's already done.

As for the question 'how'. It's dependent of the code because some components just render props and the testing itself is just checking that the props are rendered a certain way.

Some other components have data fetching, hooks and dependencies that need mocking. Until you learn the quirks of both libraries I would advise testing simpler components first. I leave one example

```<code>========== index.js ============
import React from 'react'

export default function MyComponent(){
 return <div>test</div>
}

=========== index.test.js =============
import React from 'react'
import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
import MyComponent from '.'

test("should render 'test'", () => {
  render(<MyComponent />)
  expect(screen.queryByText("test")).toBeInTheDocument()
})
</code>```

Body:
There are a couple of testing frameworks and libraries for this.

The ones I use are Jest and React Testing Library

There is a curve for the setup but if you are using create-react-app it's already done.

As for the question 'how'. It's dependent of the code because some components just render props and the testing itself is just checking that the props are rendered a certain way.

Some other components have data fetching, hooks and dependencies that need mocking. Until you learn the quirks of both libraries I would advise testing simpler components first. I leave one example

========== index.js ============
import React from 'react'

export default function MyComponent(){
 return <div>test</div>
}

=========== index.test.js =============
import React from 'react'
import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
import MyComponent from '.'

test("should render 'test'", () => {
  render(<MyComponent />)
  expect(screen.queryByText("test")).toBeInTheDocument()
})


问:
What is the practical use of the identity function in R?
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

```<code>identity <- function (x){x}
</code>```

Why would such a trivial function ever be useful?  Why would it be included in base R?

答:
For whatever it's worth, it is located in funprog.R (the functional programming stuff) in the source of the base package, and it was added as a "convenience function" in 2008: I can imagine (but can't give an immediate example!) that there would be some contexts in the functional programming approach (i.e. using Filter, Reduce, Map etc.) where it would be convenient to have an identity function ...

```<code>r45063 | hornik | 2008-04-03 12:40:59 -0400 (Thu, 03 Apr 2008) | 2 lines

Add higher-order functions Find() and Position(), and convenience
function identity().
</code>```

Body:
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

identity <- function (x){x}

Why would such a trivial function ever be useful?  Why would it be included in base R?

Body:
For whatever it's worth, it is located in funprog.R (the functional programming stuff) in the source of the base package, and it was added as a "convenience function" in 2008: I can imagine (but can't give an immediate example!) that there would be some contexts in the functional programming approach (i.e. using Filter, Reduce, Map etc.) where it would be convenient to have an identity function ...

r45063 | hornik | 2008-04-03 12:40:59 -0400 (Thu, 03 Apr 2008) | 2 lines

Add higher-order functions Find() and Position(), and convenience
function identity().


问:
How to scale a SwiftUI Image including its overlay?
Given this view with an image that has an overlay:

struct TestView: View {
    var body: some View {
        Image("image")
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130) // I want to freely position the overlay image
            }
    }
}
```
<p>The size of the images shouldn’t matter. I my example they are 150×150 pixels (“image”) and 20×20 pixels (logo).</p>
<img src="https://i.stack.imgur.com/a6jeu.png" width="200" />
<p>How can I scale this up to its bounds (like superviews frame), <strong>including</strong> the overlay?</p>
<h2>Some must-have conditions:</h2>
<ul>
<li><p>I need to <strong>freely position</strong> the overlay image, so I can not use the <code>alignment</code> parameter of <code>overlay</code> in conjunction with a padding on the logo.</p>
</li>
<li><p>I also need to <strong>position</strong> the overlay image <strong>absolutely</strong>, not relatively. So I can’t use a <code>GeometryReader</code> (or <code>alignment</code>).</p>
</li>
<li><p>I need the view to be <strong>reusable</strong> in different scenarios (different devices, different view hierarchies). That means I <strong>don’t know the scale factor</strong>, so I can’t use <code>scaleEffect</code>.</p>
</li>
</ul>
<h2>I tried:</h2>
<h3>A) <code>.aspectRatio(contentMode: .fit)</code></h3>
<pre class="lang-swift prettyprint-override"><code>struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .aspectRatio(contentMode: .fit)
    }
}
</code>```

B) .scaledToFit()

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .scaledToFit()
    }
}
```
<h3>C) Making logo resizable</h3>
<pre class="lang-swift prettyprint-override"><code>struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .resizable()
                    .position(x: 20, y: 130)
            }
            .scaledToFit() // or .aspectRatio(contentMode: .fit)
        }
}
</code>```

A and B looking like this:

C looking like this:

Both of which gave me a relative position of the logo that was different from the original (see linked screenshot). The relative size differs as well (it is now too small).

Wrapping in a stack and scale this stack instead also didn’t help.

[UPDATE] Accepted answer

Apparently not having a real view hierarchy in SwiftUI vs UIKit comes at a price. Scaling a hierarchy shouldn’t be that complicated imho. Instead I still would expect .scaledToFit (if added at the end) to scale everything before it (see A), B), and C)).

Adapted accepted answer (minus contentSize and alignment: .topLeading):

struct ContentView: View {
    var body: some View {
        Image("image")
            .resizable()
            .scaledToFit()
            .overlay {
                GeometryReader { geometry in
                    let imageSize = CGSize(width: 150, height: 150)
                    let logoSize = CGSize(width: 20, height: 20)
                    let logoPosition = CGPoint(x: 20, y: 130)
                    Image("logo")
                        .resizable()
                        .position(
                            x: logoPosition.x / imageSize.width * geometry.size.width,
                            y: logoPosition.y / imageSize.height * geometry.size.height
                        )
                        .frame(
                            width: logoSize.width / imageSize.width * geometry.size.width,
                            height: logoSize.height / imageSize.height * geometry.size.height
                        )
                }
            }
    }
}
```

答:
Then like this with GeometryReader:</p>
```<code>struct ContentView: View {

    let imageSize = CGSize(width: 150, height: 150) // Size of orig. image
    let logoPos = CGSize(width: 10, height: 120) // Position of Logo in relation to orig. image
    let logoSize = CGSize(width: 20, height: 20) // Size of logo in relation to orig. image

    @State private var contentSize = CGSize.zero

    var body: some View {

        Image("dog")
            .resizable()
            .scaledToFit()

            .overlay(
                GeometryReader { geo in
                    Color.clear.onAppear {
                        contentSize = geo.size
                    }
                }
            )
            .overlay(
                Image(systemName: "circle.hexagongrid.circle.fill")
                    .resizable()
                    .foregroundColor(.pink)
                    .offset(x: logoPos.width / imageSize.width * contentSize.width,
                            y: logoPos.height / imageSize.height * contentSize.height)
                    .frame(width: logoSize.width / imageSize.width * contentSize.width,
                           height: logoSize.height / imageSize.height * contentSize.height)
                , alignment: .topLeading)
    }
}
</code>```

Body:
Given this view with an image that has an overlay:

struct TestView: View {
    var body: some View {
        Image("image")
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130) // I want to freely position the overlay image
            }
    }
}

The size of the images shouldn’t matter. I my example they are 150×150 pixels (“image”) and 20×20 pixels (logo).

How can I scale this up to its bounds (like superviews frame), including the overlay?

Some must-have conditions:

I need to freely position the overlay image, so I can not use the alignment parameter of overlay in conjunction with a padding on the logo.

I also need to position the overlay image absolutely, not relatively. So I can’t use a GeometryReader (or alignment).

I need the view to be reusable in different scenarios (different devices, different view hierarchies). That means I don’t know the scale factor, so I can’t use scaleEffect.

I tried:

A) .aspectRatio(contentMode: .fit)

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .aspectRatio(contentMode: .fit)
    }
}

B) .scaledToFit()

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .scaledToFit()
    }
}

C) Making logo resizable

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .resizable()
                    .position(x: 20, y: 130)
            }
            .scaledToFit() // or .aspectRatio(contentMode: .fit)
        }
}

A and B looking like this:

C looking like this:

Both of which gave me a relative position of the logo that was different from the original (see linked screenshot). The relative size differs as well (it is now too small).

Wrapping in a stack and scale this stack instead also didn’t help.

[UPDATE] Accepted answer

Apparently not having a real view hierarchy in SwiftUI vs UIKit comes at a price. Scaling a hierarchy shouldn’t be that complicated imho. Instead I still would expect .scaledToFit (if added at the end) to scale everything before it (see A), B), and C)).

Adapted accepted answer (minus contentSize and alignment: .topLeading):

struct ContentView: View {
    var body: some View {
        Image("image")
            .resizable()
            .scaledToFit()
            .overlay {
                GeometryReader { geometry in
                    let imageSize = CGSize(width: 150, height: 150)
                    let logoSize = CGSize(width: 20, height: 20)
                    let logoPosition = CGPoint(x: 20, y: 130)
                    Image("logo")
                        .resizable()
                        .position(
                            x: logoPosition.x / imageSize.width * geometry.size.width,
                            y: logoPosition.y / imageSize.height * geometry.size.height
                        )
                        .frame(
                            width: logoSize.width / imageSize.width * geometry.size.width,
                            height: logoSize.height / imageSize.height * geometry.size.height
                        )
                }
            }
    }
}

Body:
Then like this with GeometryReader:

struct ContentView: View {

    let imageSize = CGSize(width: 150, height: 150) // Size of orig. image
    let logoPos = CGSize(width: 10, height: 120) // Position of Logo in relation to orig. image
    let logoSize = CGSize(width: 20, height: 20) // Size of logo in relation to orig. image

    @State private var contentSize = CGSize.zero

    var body: some View {

        Image("dog")
            .resizable()
            .scaledToFit()

            .overlay(
                GeometryReader { geo in
                    Color.clear.onAppear {
                        contentSize = geo.size
                    }
                }
            )
            .overlay(
                Image(systemName: "circle.hexagongrid.circle.fill")
                    .resizable()
                    .foregroundColor(.pink)
                    .offset(x: logoPos.width / imageSize.width * contentSize.width,
                            y: logoPos.height / imageSize.height * contentSize.height)
                    .frame(width: logoSize.width / imageSize.width * contentSize.width,
                           height: logoSize.height / imageSize.height * contentSize.height)
                , alignment: .topLeading)
    }
}


问:
JAXP with Xerces with ignores xsi:schemaLocation attribute?
I've tried creating a SAXParser, but any xsi:schemaLocation attributes in the instance document are ignored.  Does Xerces not support this feature when using JAXP?

```<code>import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
...

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);      // schema already created beforehand
spf.setNamespaceAware(true);

SAXParser sp = spf.newSAXParser();

XMLReader parser = sp.getXMLReader();
parser.setEntityResolver( new DefaultResolver());    // the entity resolver never gets invoked
parser.setErrorHandler(new SAXErrorHandler());
parser.setContentHandler(new TestHandler());
parser.parse(new InputSource(new FileInputStream(dataPath.toFile())));
</code>```

So everything works in terms of parsing and validating the document, except when there are xsi:schemaLocation attributes, these are completely getting ignored.

If I use Xerces directly, it will invoke its entity resolver.

答:
This is correct behavior as per JAXP specification.

To use xsi:schemaLocaton or xsi:noNamespceSchemaLocation hints during validation, the method newSchema should be used instead of newSchema(schema).

Body:
I've tried creating a SAXParser, but any xsi:schemaLocation attributes in the instance document are ignored.  Does Xerces not support this feature when using JAXP?

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
...

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);      // schema already created beforehand
spf.setNamespaceAware(true);

SAXParser sp = spf.newSAXParser();

XMLReader parser = sp.getXMLReader();
parser.setEntityResolver( new DefaultResolver());    // the entity resolver never gets invoked
parser.setErrorHandler(new SAXErrorHandler());
parser.setContentHandler(new TestHandler());
parser.parse(new InputSource(new FileInputStream(dataPath.toFile())));

So everything works in terms of parsing and validating the document, except when there are xsi:schemaLocation attributes, these are completely getting ignored.

If I use Xerces directly, it will invoke its entity resolver.


问:
Local scroll effect to anchor animation not working
On my wordpress site my smooth scroll to anchor script is not working like expected. It fires the "alert" and scrolls to the page but without any animation. </p>

```<code>$(document).ready(function($){

/*------------------------------------*/
/* SMOOTH SCROLL */
/*------------------------------------*/
$('a[href^="#"]').on('click',function (e) {
    alert("Step 1");
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});
</code>```

答:
I added this code to end of the functions.php file on my wordpress site and it works great for me with anchor links.</p>
```<code>function add_javascript() {
    ?>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("a").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){
        window.location.hash = hash;
      });
    }
  });
});
</script>
    <?php
}
add_action('wp_head', 'add_javascript');
</code>```

Body:
On my wordpress site my smooth scroll to anchor script is not working like expected. It fires the "alert" and scrolls to the page but without any animation.

$(document).ready(function($){

/*------------------------------------*/
/* SMOOTH SCROLL */
/*------------------------------------*/
$('a[href^="#"]').on('click',function (e) {
    alert("Step 1");
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});

Body:
I added this code to end of the functions.php file on my wordpress site and it works great for me with anchor links.

function add_javascript() {
    ?>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("a").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){
        window.location.hash = hash;
      });
    }
  });
});
</script>
    <?php
}
add_action('wp_head', 'add_javascript');


问:
reacting to message just created
I want to make the bot react to it's own message. I am making a !vote command and it can make a message saying "Cast your vote: " already. I want to make a reaction to that new message, like an example, where it reacts with a checkmark and a red x for people to click on. How can I do this?</p>

答:
Here you go!:

client.on("messageCreate", msg => {
  if (msg.content === `!vote`) {
    msg.channel.send(`Cast your vote:`).then(msg => {
      msg.react("✅");
      msg.react("❎");
    })
  }
});
```

Title: reacting to message just created


问:
I want to Consume a URL given by twitter to obtain the JSON file?
How does one consume web services that return JSON data in the response?

I am trying to build an app around twitter's API (for ex: http://search.twitter.com/search.json?q=shivkumarganesh)

I have a Twitter URL  . Now this when queried returns a JSON file. Can you help me to identify that how can I consume this in order to retrieve the results. I want to build an application around it. Please let me koow. I am using Netbeans 7 as my IDE so if there is a tutorial for such a thing in Netbeans and that too in Java then please let me know.

答:
You have 2 choices here: 1. Consume the twitter API on your server 2.  Consume the API in the client

The fastest to roll out would be number 2 since you'll just fire an ajax request to the API and consume the JSON response.

Consuming it on your server(presumably a j2ee application) will require a JSON Serializer/Deserialzer. There are several available(see json.org) but I personally prefer flexjson. google-gson is also good.


问:
Convert nested list to nested dictionary without duplicates and NAN
I'm pretty new to python and would like to ask for your help or idea in converting nested list to dictionary.

Here is a sample data:

```<code>    l3 = [['A', 'A-1', 'A-1-1'],
          ['A', 'A-1', 'A-1-2'],
          ['A', 'B-1', 'B-1-1'],
          ['A', 'B-2', nan]]
</code>```

the expected output is like this:

```<code>    output = {
        'prod': 'A',
        'item': [
                    {
                    'prod': 'A-1',
                    'item': [
                                {
                                    'prod': 'A-1-1'
                                    'item': []
                                },
                                {
                                    'prod': 'A-1-2'
                                    'item': []
                                }
                            ]
                     },
                    {
                    'prod': 'B-1',
                    'item': [
                                {
                                    'prod': 'B-1-1'
                                    'item': []
                                }
                            ]
                    },
                    {
                    'prod': 'B-2',
                    'item': []
                    }
                ]
        }
</code>```

I've tried following this link but I am having difficulty to implement it.
Python: Combine several nested lists into a dictionary

Is there a way to do this? Thank you in advance for helping me.

答:
This isn't exactly a 'nested dictionary', in the same sense as the linked question: in their version, looking up a key sequence of length k will take O(k) time on average, since they're using the mapping and lookup functionality of dictionaries. The size of the data structure doesn't asymptotically affect performance.

In your data structure, looking up the a key of length k will take O(k*L)  time, where L is the maximum number of dictionaries on the same level. This is equivalent (performance-wise) to using only nested lists. As you get more data, performance will worsen (albeit not dramatically).

If you really want to keep your current structure, this code will give matching output to yours:

def parse_nested_list(nested_list):
    # First element is always A
    base_dict = {'prod': 'A', 'item': []}

    for sub_list in nested_list:
        current_dict_list = base_dict['item']

        # Skip first element
        for element in sub_list[1:]:
            # Break on NaN
            if is_nan(element):
                break

            # Search for existing dictionary with 'prod' value match
            for sub_dict in current_dict_list:
                if sub_dict.get('prod', None) == element:
                    current_dict_list = sub_dict['item']
                    break
            else:  # None were found: create new dict
                current_dict_list.append({'prod': element, 'item': []})
                current_dict_list = current_dict_list[-1]['item']

    return base_dict
```
<p>However, if you have a choice, using a similar approach to the linked thread is probably closer to what you're looking for, and the code is simpler.</p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>def parse_nested_list_better(nested_list):
    base_dict = {}

    for sub_list in nested_list:
        current_dict = base_dict
        for element in sub_list:
            # Break on NaN
            if is_nan(element):
                break
            if element not in current_dict:
                current_dict[element] = {}

            current_dict = current_dict[element]

    return base_dict
</code>```

This will give you the following output:

```<code>output = {'A':
              {'A-1':
                     {'A-1-1': {},
                      'A-1-2': {}
                      },

               'B-1':
                     {'B-1-1': {}
                      },

               'B-2': {}

              }
          }
</code>```

Body:
I'm pretty new to python and would like to ask for your help or idea in converting nested list to dictionary.

Here is a sample data:

    l3 = [['A', 'A-1', 'A-1-1'],
          ['A', 'A-1', 'A-1-2'],
          ['A', 'B-1', 'B-1-1'],
          ['A', 'B-2', nan]]

the expected output is like this:

    output = {
        'prod': 'A',
        'item': [
                    {
                    'prod': 'A-1',
                    'item': [
                                {
                                    'prod': 'A-1-1'
                                    'item': []
                                },
                                {
                                    'prod': 'A-1-2'
                                    'item': []
                                }
                            ]
                     },
                    {
                    'prod': 'B-1',
                    'item': [
                                {
                                    'prod': 'B-1-1'
                                    'item': []
                                }
                            ]
                    },
                    {
                    'prod': 'B-2',
                    'item': []
                    }
                ]
        }

I've tried following this link but I am having difficulty to implement it.
Python: Combine several nested lists into a dictionary

Is there a way to do this? Thank you in advance for helping me.

Body:
This isn't exactly a 'nested dictionary', in the same sense as the linked question: in their version, looking up a key sequence of length k will take O(k) time on average, since they're using the mapping and lookup functionality of dictionaries. The size of the data structure doesn't asymptotically affect performance.

In your data structure, looking up the a key of length k will take O(k*L)  time, where L is the maximum number of dictionaries on the same level. This is equivalent (performance-wise) to using only nested lists. As you get more data, performance will worsen (albeit not dramatically).

If you really want to keep your current structure, this code will give matching output to yours:

def parse_nested_list(nested_list):
    # First element is always A
    base_dict = {'prod': 'A', 'item': []}

    for sub_list in nested_list:
        current_dict_list = base_dict['item']

        # Skip first element
        for element in sub_list[1:]:
            # Break on NaN
            if is_nan(element):
                break

            # Search for existing dictionary with 'prod' value match
            for sub_dict in current_dict_list:
                if sub_dict.get('prod', None) == element:
                    current_dict_list = sub_dict['item']
                    break
            else:  # None were found: create new dict
                current_dict_list.append({'prod': element, 'item': []})
                current_dict_list = current_dict_list[-1]['item']

    return base_dict

However, if you have a choice, using a similar approach to the linked thread is probably closer to what you're looking for, and the code is simpler.

For example:

def parse_nested_list_better(nested_list):
    base_dict = {}

    for sub_list in nested_list:
        current_dict = base_dict
        for element in sub_list:
            # Break on NaN
            if is_nan(element):
                break
            if element not in current_dict:
                current_dict[element] = {}

            current_dict = current_dict[element]

    return base_dict

This will give you the following output:

output = {'A':
              {'A-1':
                     {'A-1-1': {},
                      'A-1-2': {}
                      },

               'B-1':
                     {'B-1-1': {}
                      },

               'B-2': {}

              }
          }


问:
prefetch by related_name in children foreign key django
i'm trying to prefetch related from parent model to chidren throught the related name, However the queryset in the template still hits the DB in PostgreSQL, my modelB modelC and ModelD all point towards modelA and when I overwrite the generic class based view queryset function it still doesnt affect the size of the query?? any clues ?</p>
```<code>*MODEL
class ModelA(models.Model):
    title = models.Charfield(max_lenght=200, null=True, Blank=True)

class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name="model_a_related")

*VIEW
class ModelAView(DetailView):
    model = ModelA

    def get_queryset(self):
        return super().get_queryset().prefetch_related('model_a_related')
</code>```

答:
.prefetch_related(…) [Django-doc] does not fetches the ModelBs in the same query, but in a second query where it fetches all the related ModelBs for the selected (filtered) ModelAs in bulk, this in contract to fetching it per ModelA object which would be the usual behavior.

For a DetailView [Django-doc], it will thus not make any improvement. In a DetailView you render a single item, and fetching the related ModelBs will, regardless whether it is done through .prefetch_related(…) or by accessing object.model_a_related.all() make one extra query.

Body:
i'm trying to prefetch related from parent model to chidren throught the related name, However the queryset in the template still hits the DB in PostgreSQL, my modelB modelC and ModelD all point towards modelA and when I overwrite the generic class based view queryset function it still doesnt affect the size of the query?? any clues ?

*MODEL
class ModelA(models.Model):
    title = models.Charfield(max_lenght=200, null=True, Blank=True)

class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name="model_a_related")

*VIEW
class ModelAView(DetailView):
    model = ModelA

    def get_queryset(self):
        return super().get_queryset().prefetch_related('model_a_related')


问:
Suggestions about multiplayer game development on iOS and Android?
I'm working on a simple game to experience the multiplayer game development on mobile plaforms especially on Android and iOS. I'm now planning network/multiplayer side of the game and need some advice.

Firstly i think about Google App Engine as the server side of the game. But i learned that app engine cannot connect directly to clients. So updates of the users cannot be send to others directly with this method. Then i started to think about serving the game on one of the gamers of the current session. But of course some of the features will be on the server. You think it is a good idea?

Second, I'm looking for a protocol to communicate iOS and Android. YAML and JSON are the ones i looked so far.

Any other suggestions about multiplayer game development would be appreciated. Thanks...

答: I too evaluated OpenFeint and Scoreloop. I'm particularly impressed with Open Feint's rich feature set. RIM acquired ScoreLoop in June so I'm not sure how long they'd support non-BlackBerry platforms. I found that both these SDKs do not provide multiplayer support. If multiplayer social game development is what you are talking about, Skiller seems to be a good option.</p>

ContentLicense: CC BY-SA 2.5


问:
React Native 0.64 Command PhaseScriptExecution failed with a nonzero exit code
I'm installing a new project with a bunch of modules with React Native 0.64. I can do a pod install without troubles, but when I want to make my app running (with react-native run-ios or with XCode) this error occured on XCode :

```<code>/Users/thomas/Desktop/Dev/Mobile/appname/node_modules/react-native/scripts/generate-specs.sh: line 27: readlink: command not found
/Users/thomas/Desktop/Dev/Mobile/appname/node_modules/react-native/scripts/generate-specs.sh: line 27: dirname: command not found
/Users/thomas/Desktop/Dev/Mobile/appname/node_modules/react-native/scripts/generate-specs.sh: line 27: cd: : No such file or directory
Command PhaseScriptExecution failed with a nonzero exit code
</code>```

This one on react-native run-ios :

```<code>The following build commands failed:
    PhaseScriptExecution [CP-User]\ Generate\ Specs /Users/thomas/Library/Developer/Xcode/DerivedData/appname-aqbmfgqjkshyqmaprdvggqaeqjrp/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/**FBReactNativeSpec**.build/Script-A319AA7F2B7AAE771AE63D66A0049241.sh
</code>```

Note that I don't have a 'scripts' folder in my node_modules/react-native (I just have assets, normalize-color and polyfills folders). I've tried to remove node-modules and reinstall it.

My specs are :

iOS Big Sur v. 11.2.3

XCode v.12.3

React Native v.0.64

CocoaPods v. 1.10.1

Node v. 12.14.1

Any help ? Thanks.

答:
The above answer is correct but in that case, you are editing the inside the node modules. So rather than just enter this command in your terminal</p>
```<code>export PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin
</code>```

Body:
I'm installing a new project with a bunch of modules with React Native 0.64. I can do a pod install without troubles, but when I want to make my app running (with react-native run-ios or with XCode) this error occured on XCode :

/Users/thomas/Desktop/Dev/Mobile/appname/node_modules/react-native/scripts/generate-specs.sh: line 27: readlink: command not found
/Users/thomas/Desktop/Dev/Mobile/appname/node_modules/react-native/scripts/generate-specs.sh: line 27: dirname: command not found
/Users/thomas/Desktop/Dev/Mobile/appname/node_modules/react-native/scripts/generate-specs.sh: line 27: cd: : No such file or directory
Command PhaseScriptExecution failed with a nonzero exit code

This one on react-native run-ios :

The following build commands failed:
    PhaseScriptExecution [CP-User]\ Generate\ Specs /Users/thomas/Library/Developer/Xcode/DerivedData/appname-aqbmfgqjkshyqmaprdvggqaeqjrp/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/**FBReactNativeSpec**.build/Script-A319AA7F2B7AAE771AE63D66A0049241.sh

Note that I don't have a 'scripts' folder in my node_modules/react-native (I just have assets, normalize-color and polyfills folders). I've tried to remove node-modules and reinstall it.

My specs are :

iOS Big Sur v. 11.2.3

XCode v.12.3

React Native v.0.64

CocoaPods v. 1.10.1

Node v. 12.14.1

Any help ? Thanks.

Body:
The above answer is correct but in that case, you are editing the inside the node modules. So rather than just enter this command in your terminal

export PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin


问:
Check if second string is rotation of another string
I'm trying to write a function that takes in two string parameters and check if the second parameter is a rotated version of the first string.

So the following would be the results:

checkRotationStrings('waterbottle', 'lewaterbott'); // true
checkRotationStrings('waterbottle', 'bottlewater'); // true
checkRotationStrings('waterbottle', 'erbottlewat'); // true
checkRotationStrings('waterbottle', 'lewaterbottx'); // false

I wrote the following code, but there are some edge cases that I can't seem to figure out:

function checkRotationStrings(string, rotatedString) {
  let result;
  let rotationCheck
  let stringArr = string.split('');
  let rotatedStringArr = rotatedString.split('')

  for (let i = 0; i < string.length - 1; i++) {
    if (rotatedString[0] === stringArr[i]) {
       result = stringArr.slice(i);
       rotationCheck = stringArr.slice(0, i).concat(result).join('');
    }
  }
  console.log(rotationCheck)
  if (rotationCheck === string){
    return true;
  } else {
    return false;
  }
}
```

Any help would be appreciated.

答:
I might be late for this, but here is my solution and it include all edge cases.

function checkRotation(str1,str2){
  const char0 = str1[0];
  let ind = str2.indexOf(char0);
  while(ind>-1){
    const start = str2.substring(0,ind);
    const end = str2.substring(ind,str2.length);
    if(end+start === str1){
      return true;
    }
    ind = str2.indexOf(char0,ind+1)
  }
  return false
}
console.log(checkRotation("assads","adsass"))```

Body:
I'm trying to write a function that takes in two string parameters and check if the second parameter is a rotated version of the first string.

So the following would be the results:

checkRotationStrings('waterbottle', 'lewaterbott'); // true
checkRotationStrings('waterbottle', 'bottlewater'); // true
checkRotationStrings('waterbottle', 'erbottlewat'); // true
checkRotationStrings('waterbottle', 'lewaterbottx'); // false

I wrote the following code, but there are some edge cases that I can't seem to figure out:

function checkRotationStrings(string, rotatedString) {
  let result;
  let rotationCheck
  let stringArr = string.split('');
  let rotatedStringArr = rotatedString.split('')

  for (let i = 0; i < string.length - 1; i++) {
    if (rotatedString[0] === stringArr[i]) {
       result = stringArr.slice(i);
       rotationCheck = stringArr.slice(0, i).concat(result).join('');
    }
  }
  console.log(rotationCheck)
  if (rotationCheck === string){
    return true;
  } else {
    return false;
  }
}

Any help would be appreciated.