问:
Integration test in custom folder: Execution failed for task ':integrationTest'. No tests found for given includes
Apologies if that post repeats many other, I've seen them all and tried all the suggested recipes, and yet the problem stays.

I have a SpringBoot project with Grails build, with the following structure:

```<code>mybike-rest
    src
        integration
            java
                com.bike
                    BorrowMyBikeApplicationTest
            resources
        main
            java
            ...
        test
            java
            ...
</code>```

My build.gradle is as follows:

```<code>plugins {
    id 'org.springframework.boot' version '2.4.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'idea'
}

group = 'java.bike'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '8'

sourceSets {
    main {
        java.srcDirs('./src/main/java')
        resources.srcDirs('./src/main/resources')
    }
    test {
        java.srcDirs('./src/test/java')
        resources.srcDirs('./src/test/resources')
    }
    integrationTest {
        java.srcDirs('./src/integration/java')
        resources.srcDirs('./src/integration/resources')
        compileClasspath += main.output + test.output
        runtimeClasspath += main.output + test.output
    }
}

configurations{
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntime.extendsFrom testRuntime
}

task integrationTest(type: Test) {
    description = 'Runs the integration tests.'
    group = 'verification'
    outputs.upToDateWhen { false }
    testLogging { events "passed", "skipped", "failed" } // This is not needed, but I like to see which tests have run
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath
}

repositories {
    mavenCentral()
}

test {
    useJUnitPlatform()
}

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.projectlombok:lombok'
    compile 'org.flywaydb:flyway-core'
    runtimeOnly 'org.postgresql:postgresql'
    runtimeOnly 'com.h2database:h2'
    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile 'org.junit.jupiter:junit-jupiter'
    testCompile 'org.springframework.data:spring-data-commons'
    testCompile 'org.assertj:assertj-core'

    integrationTestCompile sourceSets.main.output
    integrationTestCompile sourceSets.test.output
    integrationTestCompile configurations.compile
    integrationTestCompile configurations.testCompile
    integrationTestRuntime configurations.runtime
    integrationTestRuntime configurations.testRuntime
    integrationTestAnnotationProcessor configurations.testAnnotationProcessor

    annotationProcessor 'org.projectlombok:lombok'
    testAnnotationProcessor 'org.projectlombok:lombok'
}
</code>```

IntelliJ recognises my test correctly:

However, when I run the test in iJ, I get the following output:

```<code>> Task :cleanIntegrationTest
> Task :compileJava UP-TO-DATE
> Task :processResources UP-TO-DATE
> Task :classes UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :processTestResources UP-TO-DATE
> Task :testClasses UP-TO-DATE
> Task :compileIntegrationTestJava UP-TO-DATE
> Task :processIntegrationTestResources
> Task :integrationTestClasses
> Task :integrationTest FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':integrationTest'.
> No tests found for given includes: [com.bike.BorrowMyBikeApplicationTest](filter.includeTestsMatching)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.8.3/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 1s
8 actionable tasks: 3 executed, 5 up-to-date
</code>```

When I run in command line as gradlew clean iT -i, I see the following output:

```<code>...
> Task :compileIntegrationTestJava
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/java', not found
Excluding []
Excluding []
Caching disabled for task ':compileIntegrationTestJava' because:
  Build cache is disabled
Task ':compileIntegrationTestJava' is not up-to-date because:
  Output property 'destinationDirectory' file /home/nmilyaev/Work/Intellij/mybike-rest/build/classes/java/integrationTest has been removed.
  Output property 'destinationDirectory' file /home/nmilyaev/Work/Intellij/mybike-rest/build/classes/java/integrationTest/com has been removed.
  Output property 'destinationDirectory' file /home/nmilyaev/Work/Intellij/mybike-rest/build/classes/java/integrationTest/com/bike has been removed.
The input changes require a full rebuild for incremental task ':compileIntegrationTestJava'.
Full recompilation is required because no incremental change information is available. This is usually caused by clean builds or changing compiler arguments.
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/java', not found
Compiling with JDK Java compiler API.
Created classpath snapshot for incremental compilation in 0.006 secs. 1 duplicate classes found in classpath (see all with --debug).
:compileIntegrationTestJava (Thread[Daemon worker Thread 10,5,main]) completed. Took 0.643 secs.
:processIntegrationTestResources (Thread[Execution worker for ':' Thread 3,5,main]) started.

> Task :processIntegrationTestResources
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/resources', not found
Caching disabled for task ':processIntegrationTestResources' because:
  Build cache is disabled
Task ':processIntegrationTestResources' is not up-to-date because:
  Output property 'destinationDir' file /home/nmilyaev/Work/Intellij/mybike-rest/build/resources/integrationTest has been removed.
  Output property 'destinationDir' file /home/nmilyaev/Work/Intellij/mybike-rest/build/resources/integrationTest/application.properties has been removed.
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/resources', not found
:processIntegrationTestResources (Thread[Execution worker for ':' Thread 3,5,main]) completed. Took 0.019 secs.
:integrationTestClasses (Thread[Execution worker for ':' Thread 3,5,main]) started.

> Task :integrationTestClasses
Skipping task ':integrationTestClasses' as it has no actions.
:integrationTestClasses (Thread[Execution worker for ':' Thread 3,5,main]) completed. Took 0.0 secs.
:integrationTest (Thread[Execution worker for ':' Thread 3,5,main]) started.

> Task :integrationTest
Excluding []
Caching disabled for task ':integrationTest' because:
  Build cache is disabled
Task ':integrationTest' is not up-to-date because:
  Task.upToDateWhen is false.
Finished generating test XML results (0.0 secs) into: /home/nmilyaev/Work/Intellij/mybike-rest/build/test-results/integrationTest
Generating HTML test report...
Finished generating test html results (0.003 secs) into: /home/nmilyaev/Work/Intellij/mybike-rest/build/reports/tests/integrationTest
:integrationTest (Thread[Execution worker for ':' Thread 3,5,main]) completed. Took 0.149 secs.

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

BUILD SUCCESSFUL in 4s
</code>```

Honestly, I tried everything there under the moon, but something is amiss. Could anyone please help me spot what am I missing?

答:
Thanks for the answer, @nestor-milyaev. I have a similar structure to your project and this is my scenario:

Gradle 7.3

Using the discussion you linked to.

Using JUnit 5 and excluding vintage.

```<code>tasks.withType(Test) {
    useJUnitPlatform {
        excludeEngines 'junit-vintage'
    }
    testLogging {
        events "FAILED", "SKIPPED"
    }
}
</code>```

Now ITs are running as well as UTs.

Body:
Apologies if that post repeats many other, I've seen them all and tried all the suggested recipes, and yet the problem stays.

I have a SpringBoot project with Grails build, with the following structure:

mybike-rest
    src
        integration
            java
                com.bike
                    BorrowMyBikeApplicationTest
            resources
        main
            java
            ...
        test
            java
            ...

My build.gradle is as follows:

plugins {
    id 'org.springframework.boot' version '2.4.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'idea'
}

group = 'java.bike'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '8'

sourceSets {
    main {
        java.srcDirs('./src/main/java')
        resources.srcDirs('./src/main/resources')
    }
    test {
        java.srcDirs('./src/test/java')
        resources.srcDirs('./src/test/resources')
    }
    integrationTest {
        java.srcDirs('./src/integration/java')
        resources.srcDirs('./src/integration/resources')
        compileClasspath += main.output + test.output
        runtimeClasspath += main.output + test.output
    }
}

configurations{
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntime.extendsFrom testRuntime
}

task integrationTest(type: Test) {
    description = 'Runs the integration tests.'
    group = 'verification'
    outputs.upToDateWhen { false }
    testLogging { events "passed", "skipped", "failed" } // This is not needed, but I like to see which tests have run
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath
}

repositories {
    mavenCentral()
}

test {
    useJUnitPlatform()
}

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.projectlombok:lombok'
    compile 'org.flywaydb:flyway-core'
    runtimeOnly 'org.postgresql:postgresql'
    runtimeOnly 'com.h2database:h2'
    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile 'org.junit.jupiter:junit-jupiter'
    testCompile 'org.springframework.data:spring-data-commons'
    testCompile 'org.assertj:assertj-core'

    integrationTestCompile sourceSets.main.output
    integrationTestCompile sourceSets.test.output
    integrationTestCompile configurations.compile
    integrationTestCompile configurations.testCompile
    integrationTestRuntime configurations.runtime
    integrationTestRuntime configurations.testRuntime
    integrationTestAnnotationProcessor configurations.testAnnotationProcessor

    annotationProcessor 'org.projectlombok:lombok'
    testAnnotationProcessor 'org.projectlombok:lombok'
}

IntelliJ recognises my test correctly:

However, when I run the test in iJ, I get the following output:

> Task :cleanIntegrationTest
> Task :compileJava UP-TO-DATE
> Task :processResources UP-TO-DATE
> Task :classes UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :processTestResources UP-TO-DATE
> Task :testClasses UP-TO-DATE
> Task :compileIntegrationTestJava UP-TO-DATE
> Task :processIntegrationTestResources
> Task :integrationTestClasses
> Task :integrationTest FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':integrationTest'.
> No tests found for given includes: [com.bike.BorrowMyBikeApplicationTest](filter.includeTestsMatching)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.8.3/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 1s
8 actionable tasks: 3 executed, 5 up-to-date

When I run in command line as gradlew clean iT -i, I see the following output:

...
> Task :compileIntegrationTestJava
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/java', not found
Excluding []
Excluding []
Caching disabled for task ':compileIntegrationTestJava' because:
  Build cache is disabled
Task ':compileIntegrationTestJava' is not up-to-date because:
  Output property 'destinationDirectory' file /home/nmilyaev/Work/Intellij/mybike-rest/build/classes/java/integrationTest has been removed.
  Output property 'destinationDirectory' file /home/nmilyaev/Work/Intellij/mybike-rest/build/classes/java/integrationTest/com has been removed.
  Output property 'destinationDirectory' file /home/nmilyaev/Work/Intellij/mybike-rest/build/classes/java/integrationTest/com/bike has been removed.
The input changes require a full rebuild for incremental task ':compileIntegrationTestJava'.
Full recompilation is required because no incremental change information is available. This is usually caused by clean builds or changing compiler arguments.
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/java', not found
Compiling with JDK Java compiler API.
Created classpath snapshot for incremental compilation in 0.006 secs. 1 duplicate classes found in classpath (see all with --debug).
:compileIntegrationTestJava (Thread[Daemon worker Thread 10,5,main]) completed. Took 0.643 secs.
:processIntegrationTestResources (Thread[Execution worker for ':' Thread 3,5,main]) started.

> Task :processIntegrationTestResources
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/resources', not found
Caching disabled for task ':processIntegrationTestResources' because:
  Build cache is disabled
Task ':processIntegrationTestResources' is not up-to-date because:
  Output property 'destinationDir' file /home/nmilyaev/Work/Intellij/mybike-rest/build/resources/integrationTest has been removed.
  Output property 'destinationDir' file /home/nmilyaev/Work/Intellij/mybike-rest/build/resources/integrationTest/application.properties has been removed.
file or directory '/home/nmilyaev/Work/Intellij/mybike-rest/src/integrationTest/resources', not found
:processIntegrationTestResources (Thread[Execution worker for ':' Thread 3,5,main]) completed. Took 0.019 secs.
:integrationTestClasses (Thread[Execution worker for ':' Thread 3,5,main]) started.

> Task :integrationTestClasses
Skipping task ':integrationTestClasses' as it has no actions.
:integrationTestClasses (Thread[Execution worker for ':' Thread 3,5,main]) completed. Took 0.0 secs.
:integrationTest (Thread[Execution worker for ':' Thread 3,5,main]) started.

> Task :integrationTest
Excluding []
Caching disabled for task ':integrationTest' because:
  Build cache is disabled
Task ':integrationTest' is not up-to-date because:
  Task.upToDateWhen is false.
Finished generating test XML results (0.0 secs) into: /home/nmilyaev/Work/Intellij/mybike-rest/build/test-results/integrationTest
Generating HTML test report...
Finished generating test html results (0.003 secs) into: /home/nmilyaev/Work/Intellij/mybike-rest/build/reports/tests/integrationTest
:integrationTest (Thread[Execution worker for ':' Thread 3,5,main]) completed. Took 0.149 secs.

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

BUILD SUCCESSFUL in 4s

Honestly, I tried everything there under the moon, but something is amiss. Could anyone please help me spot what am I missing?

Body:
Thanks for the answer, @nestor-milyaev. I have a similar structure to your project and this is my scenario:

Gradle 7.3

Using the discussion you linked to.

Using JUnit 5 and excluding vintage.

tasks.withType(Test) {
    useJUnitPlatform {
        excludeEngines 'junit-vintage'
    }
    testLogging {
        events "FAILED", "SKIPPED"
    }
}

Now ITs are running as well as UTs.


来源: stackexchange

问:
How to apply an attribute to all classes who inherit monobehaviour in a project/ an assembly?
I'm asking this because I want to eliminate the "Failed to insert item" warnings in a Unity project, which is caused by amount of scripts exceeding a certain value. Here is a solution provided by unity,  which suggests applying [AddComponentMenu("")]attribute to all monobehaviours accordingly.

Since I'm working on a project with lots of scripts, it seems very difficult to apply this attribute manually. I need to:

Finding all classes under \Assets\Scripts (or in Assembly-CSharp) who inherit monobehaviour or any of its child class

Applying [AddComponentMenu("PATH")] attibute to the classes found above and put the realtive path of the script in the "PATH"

I don't know how to implement these and have been failing to find a solution by myself.

Some additional features would be wonderful (not necessary):

If there is existing [AddComponentMenu("")] in the script, do not override the original one.

Automatically applying [AddComponentMenu("")] to the scripts to be created.

Looking forward to all kinds of help. Thanks a lot!

答:
There are probably many ways to do this outside of Unity. However, I will assume you want to do it all in Unity itself just for the simpleness of things.

Remark: There are for sure edge-cases left but I hope this is a good starting point

Finding all classes under \Assets\Scripts (or in Assembly-CSharp) who inherit monobehaviour or any of its child class

This first point would be quite simple - kind of. The Assets don't allow to find script types themselves but you can get all script assets by searching for t:MonoScript in the search bar in the Assets view.

The same can be done also via script using AssetDatabase.FindAssets like e.g.

```<code>var scriptGUIDs = AssetDataBase.FindAssets($"t:{nameof(MonoScript)}",  new[] {"Assets/Scripts"});
</code>```

From there you will need to load the script asset and check its type using e.g.

```<code>foreach (var scriptGUID  in scriptGUIDs)
{
    // e.g. Assets/Scripts/MyComponent.cs
    var scriptAssetPath = AssetDatabase.GUIDToAssetPath(scriptGUID);

    // first get the actual asset
    var scriptAsset = AssetDatabase.LoadAssetAtPath<MonoScript>(scriptAssetPath);
    // get the system type
    var scriptType = scriptAsset.GetClass();
    // Now first of all check if this is actually something derived from MonoBehaviour -> if not skip
    if(!scriptType.IsSubclassOf(typeof(MonoBehaviour))) continue;

    .....
}
</code>```

Applying [AddComponentMenu("PATH")] attribute to the classes found above and put the realtive path of the script in the "PATH"

This is of course way more tricky since it requires to find the according code line (right above the class implementation) and add text into the file.

So this requires multiple steps

Check if this type already has the attribute -> skip, which also solves

If there is existing [AddComponentMenu("")] in the script, do not override the original one.

Load the raw text content

find the line of code which contains public class TYPENAME :

Insert your attribute line before that line

Write all lines back to the file

After all done refresh the data base to cause a reload/recompilation

This could look somewhat like e.g.

```<code>// Find all assets of type "MonoScript" in the folder Assets/Scripts
// or remove /Scripts if you really want to go for all in the Assets
var scriptGUIDs = AssetDatabase.FindAssets($"t:{nameof(MonoScript)}",  new[] {"Assets/Scripts"});

foreach (var scriptGUID  in scriptGUIDs)
{
    // e.g. Assets/Scripts/MyComponent.cs
    var scriptAssetPath = AssetDatabase.GUIDToAssetPath(scriptGUID);

    // first get the actual asset
    var scriptAsset = AssetDatabase.LoadAssetAtPath<MonoScript>(scriptAssetPath);
    // get the system type
    var scriptType = scriptAsset.GetClass();
    // Now first of all check if this is actually something derived from MonoBehaviour -> if not skip
    if(!scriptType.IsSubclassOf(typeof(MonoBehaviour))) continue;
    // check if this class already has the attribute -> if so skip
    if(scriptType.IsDefined(typeof(AddComponentMenu), true)) continue;

    // otherwise load in the lines as a list so we can insert our new line
    var lines = File.ReadAllLines(scriptAssetPath).ToList();
    // find the one defining the class
    var indexOfClassLine = lines.FindIndex(l => l.Contains($" class {scriptType.Name} : "));

    // e.g. Assets/Scripts/MyComponent
    // => you might want to e.g. also remove the "Assets" part ;)
    var relativePathWithoutExtension = scriptAssetPath.Substring(0, scriptAssetPath.Length - 3);

    // insert the new attribute one line right above that line
    lines.Insert(indexOfClassLine, $"[AddComponentMenu(\"{relativePathWithoutExtension}\")]");

    File.WriteAllLines(scriptAssetPath, lines);
}

AssetDatabase.Refresh();
</code>```

And finally

Automatically applying [AddComponentMenu("")] to the scripts to be created.

Somewhere in you project you need an implementation of AssetModificationProcessor which will basically do the same thing as before, just this time it is slightly easier since we don't need to check the type since all c# scrips created via the menu are MonoBehaviour by default

```<code>public class ScriptKeywordProcessor : UnityEditor.AssetModificationProcessor
{
    public static void OnWillCreateAsset(string path)
    {
        // ignore meta files
        var tempPath = path.Replace(".meta", "");
        var index = tempPath.LastIndexOf(".");
        if (index < 0) return;

        // ignore if not a .cs script
        var file = tempPath.Substring(index);
        if (file != ".cs") return;

        // otherwise load in the lines as a list so we can insert our new line
        var lines = File.ReadAllLines(path).ToList();
        // find the one defining the class
        var indexOfClassLine = lines.FindIndex(l => l.Contains($" class {Path.GetFileNameWithoutExtension(path)} : "));

        // e.g. Assets/Scripts/MyComponent
        // => you might want to e.g. also remove the "Assets" part ;)
        var relativePathWithoutExtension = path.Substring(0, path.Length - 3);

        // insert the new attribute one line right above that line
        lines.Insert(indexOfClassLine, $"[AddComponentMenu(\"{relativePathWithoutExtension}\")]");

        File.WriteAllLines(path, lines);

        AssetDatabase.Refresh();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are probably many ways to do this outside of Unity. However, I will assume you want to do it all in Unity itself just for the simpleness of things.

Remark: There are for sure edge-cases left but I hope this is a good starting point

Finding all classes under \Assets\Scripts (or in Assembly-CSharp) who inherit monobehaviour or any of its child class

This first point would be quite simple - kind of. The Assets don't allow to find script types themselves but you can get all script assets by searching for t:MonoScript in the search bar in the Assets view.

The same can be done also via script using AssetDatabase.FindAssets like e.g.

var scriptGUIDs = AssetDataBase.FindAssets($"t:{nameof(MonoScript)}",  new[] {"Assets/Scripts"});

From there you will need to load the script asset and check its type using e.g.

foreach (var scriptGUID  in scriptGUIDs)
{
    // e.g. Assets/Scripts/MyComponent.cs
    var scriptAssetPath = AssetDatabase.GUIDToAssetPath(scriptGUID);

    // first get the actual asset
    var scriptAsset = AssetDatabase.LoadAssetAtPath<MonoScript>(scriptAssetPath);
    // get the system type
    var scriptType = scriptAsset.GetClass();
    // Now first of all check if this is actually something derived from MonoBehaviour -> if not skip
    if(!scriptType.IsSubclassOf(typeof(MonoBehaviour))) continue;

    .....
}

Applying [AddComponentMenu("PATH")] attribute to the classes found above and put the realtive path of the script in the "PATH"

This is of course way more tricky since it requires to find the according code line (right above the class implementation) and add text into the file.

So this requires multiple steps

Check if this type already has the attribute -> skip, which also solves

If there is existing [AddComponentMenu("")] in the script, do not override the original one.

Load the raw text content

find the line of code which contains public class TYPENAME :

Insert your attribute line before that line

Write all lines back to the file

After all done refresh the data base to cause a reload/recompilation

This could look somewhat like e.g.

// Find all assets of type "MonoScript" in the folder Assets/Scripts
// or remove /Scripts if you really want to go for all in the Assets
var scriptGUIDs = AssetDatabase.FindAssets($"t:{nameof(MonoScript)}",  new[] {"Assets/Scripts"});

foreach (var scriptGUID  in scriptGUIDs)
{
    // e.g. Assets/Scripts/MyComponent.cs
    var scriptAssetPath = AssetDatabase.GUIDToAssetPath(scriptGUID);

    // first get the actual asset
    var scriptAsset = AssetDatabase.LoadAssetAtPath<MonoScript>(scriptAssetPath);
    // get the system type
    var scriptType = scriptAsset.GetClass();
    // Now first of all check if this is actually something derived from MonoBehaviour -> if not skip
    if(!scriptType.IsSubclassOf(typeof(MonoBehaviour))) continue;
    // check if this class already has the attribute -> if so skip
    if(scriptType.IsDefined(typeof(AddComponentMenu), true)) continue;

    // otherwise load in the lines as a list so we can insert our new line
    var lines = File.ReadAllLines(scriptAssetPath).ToList();
    // find the one defining the class
    var indexOfClassLine = lines.FindIndex(l => l.Contains($" class {scriptType.Name} : "));

    // e.g. Assets/Scripts/MyComponent
    // => you might want to e.g. also remove the "Assets" part ;)
    var relativePathWithoutExtension = scriptAssetPath.Substring(0, scriptAssetPath.Length - 3);

    // insert the new attribute one line right above that line
    lines.Insert(indexOfClassLine, $"[AddComponentMenu(\"{relativePathWithoutExtension}\")]");

    File.WriteAllLines(scriptAssetPath, lines);
}

AssetDatabase.Refresh();

And finally

Automatically applying [AddComponentMenu("")] to the scripts to be created.

Somewhere in you project you need an implementation of AssetModificationProcessor which will basically do the same thing as before, just this time it is slightly easier since we don't need to check the type since all c# scrips created via the menu are MonoBehaviour by default

public class ScriptKeywordProcessor : UnityEditor.AssetModificationProcessor
{
    public static void OnWillCreateAsset(string path)
    {
        // ignore meta files
        var tempPath = path.Replace(".meta", "");
        var index = tempPath.LastIndexOf(".");
        if (index < 0) return;

        // ignore if not a .cs script
        var file = tempPath.Substring(index);
        if (file != ".cs") return;

        // otherwise load in the lines as a list so we can insert our new line
        var lines = File.ReadAllLines(path).ToList();
        // find the one defining the class
        var indexOfClassLine = lines.FindIndex(l => l.Contains($" class {Path.GetFileNameWithoutExtension(path)} : "));

        // e.g. Assets/Scripts/MyComponent
        // => you might want to e.g. also remove the "Assets" part ;)
        var relativePathWithoutExtension = path.Substring(0, path.Length - 3);

        // insert the new attribute one line right above that line
        lines.Insert(indexOfClassLine, $"[AddComponentMenu(\"{relativePathWithoutExtension}\")]");

        File.WriteAllLines(path, lines);

        AssetDatabase.Refresh();
    }
}


问:
How to Include associated entities
I want to create test case for below method "GetByEmail".

```<code> public User GetByEmail(string email, bool includeUserRoles = false, bool includeUserType = false)
 {
    Expression<Func<User>> whereClause = u => u.Email == email;

    return GetQuery(whereClause, includeUserRoles, includeUserType) .FirstOrDefault();
 }

 private IQueryable<User> GetQuery(Expression<Func<User>> whereClause,
                                   bool includeUserRoles = false, bool includeUserType = false)
 {
   IQueryable<User> query = base.GetQuery(whereClause);

   if (includeUserRoles)
     query = query.Include(u => u.UserRoles);

   if (includeUserType)
     query = query.Include(u => u.UserType);

   return query;
 }

 protected IQueryable<T> GetQuery<T>(Expression<Func<T>> predicate) where T : EntityBase
 {
    return predicate != null ?
             CreateObjectSet<T>().Where(predicate) :
             CreateObjectSet<T>();
 }

 protected IObjectSet<T> CreateObjectSet<T>() where T : EntityBase
 {
   return _context.CreateObjectSet<T>();
 }

 public static IQueryable<T> Include<T>(this IQueryable<T> source, Expression<Func<T>> property)
 {
   var objectQuery = source as ObjectQuery<T>;

   if (objectQuery != null)
   {
      var propertyPath = GetPropertyPath(property);
      return objectQuery.Include(propertyPath);
   }

   return source;
 }
</code>```

Below is my test case method -

```<code>[Fact]
private void GetByEmail_PassedEmailAddress_RelatedUser()
{
  //Created fake context
  var fakeContext = Isolate.Fake.Instance<Entities>();

  //Created fake Repository and passed fakeContext to it
  var fakeRepository = Isolate.Fake.Instance<Repository>(Members.CallOriginal,   ConstructorWillBe.Called, fakeContext);

  //Created fake in memory collection of User
  var fakeUsers = GetUsers();

  Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>())
         .WillReturnCollectionValuesOf(fakeUsers);

  var User = Isolate.Invoke.Method(fakeRepository, "GetByEmail", "abc@xyz.com", true, true);

  Assert.True(User != null);
}
</code>```

In the above test case method I successfully get the user with passed email but not able to include other entities of associated user.

Kindly let me know, how can I include other entities with associated User.

答:
Include is leaky abstraction - it works only with EF and linq-to-entities and cannot be successfully used with linq-to-objects. You know that your unit test needs populated relations so your GetUsers method must prepare that data. That is a point of mocking / faking - you don't think about internal implementation of mocked method. You simply return what should be returned.

Btw. what is the point of your test? It looks like you are trying to test a mock - that is wrong. Mock provides correct data and you only need it to test another feature dependent on mocked component.

ContentLicense: CC BY-SA 3.0

Title: How to Include associated entities

Body:
I want to create test case for below method "GetByEmail".

 public User GetByEmail(string email, bool includeUserRoles = false, bool includeUserType = false)
 {
    Expression<Func<User>> whereClause = u => u.Email == email;

    return GetQuery(whereClause, includeUserRoles, includeUserType) .FirstOrDefault();
 }

 private IQueryable<User> GetQuery(Expression<Func<User>> whereClause,
                                   bool includeUserRoles = false, bool includeUserType = false)
 {
   IQueryable<User> query = base.GetQuery(whereClause);

   if (includeUserRoles)
     query = query.Include(u => u.UserRoles);

   if (includeUserType)
     query = query.Include(u => u.UserType);

   return query;
 }

 protected IQueryable<T> GetQuery<T>(Expression<Func<T>> predicate) where T : EntityBase
 {
    return predicate != null ?
             CreateObjectSet<T>().Where(predicate) :
             CreateObjectSet<T>();
 }

 protected IObjectSet<T> CreateObjectSet<T>() where T : EntityBase
 {
   return _context.CreateObjectSet<T>();
 }

 public static IQueryable<T> Include<T>(this IQueryable<T> source, Expression<Func<T>> property)
 {
   var objectQuery = source as ObjectQuery<T>;

   if (objectQuery != null)
   {
      var propertyPath = GetPropertyPath(property);
      return objectQuery.Include(propertyPath);
   }

   return source;
 }

Below is my test case method -

[Fact]
private void GetByEmail_PassedEmailAddress_RelatedUser()
{
  //Created fake context
  var fakeContext = Isolate.Fake.Instance<Entities>();

  //Created fake Repository and passed fakeContext to it
  var fakeRepository = Isolate.Fake.Instance<Repository>(Members.CallOriginal,   ConstructorWillBe.Called, fakeContext);

  //Created fake in memory collection of User
  var fakeUsers = GetUsers();

  Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>())
         .WillReturnCollectionValuesOf(fakeUsers);

  var User = Isolate.Invoke.Method(fakeRepository, "GetByEmail", "abc@xyz.com", true, true);

  Assert.True(User != null);
}

In the above test case method I successfully get the user with passed email but not able to include other entities of associated user.

Kindly let me know, how can I include other entities with associated User.


问:
Sorting values in dataframe
I'm given the following dataset:

```<code>df.head()
    Bacteria    Penicilin   Streptomycin    Neomycin
0   Aerobacter aerogenes    870.000 1.00    1.600
1   Brucella abortus    1.000   2.00    0.020
2   Brucella anthracis  0.001   0.01    0.007
3   Diplococcus pneumoniae  0.005   11.00   10.000
4   Escherichia coli    100.000 0.40    0.100
</code>```

I need it to be sorted by bacteria column, so I am trying to use the following command:

```<code>df.sort_values(by=df['Bacteria'])
</code>```

I am still getting the error. What's wrong with sorting command?

答:
First parameter of sort_values is expected to be a str | list of str by pandas docs.

So you should arrange it like df.sort_values(by='Bacteria')

Title: Sorting values in dataframe

Body:
I'm given the following dataset:

df.head()
    Bacteria    Penicilin   Streptomycin    Neomycin
0   Aerobacter aerogenes    870.000 1.00    1.600
1   Brucella abortus    1.000   2.00    0.020
2   Brucella anthracis  0.001   0.01    0.007
3   Diplococcus pneumoniae  0.005   11.00   10.000
4   Escherichia coli    100.000 0.40    0.100

I need it to be sorted by bacteria column, so I am trying to use the following command:

df.sort_values(by=df['Bacteria'])

I am still getting the error. What's wrong with sorting command?


问:
MVVM ListView not updating despite Itemsource modification | XAMARIN FORMS, ANDROID
I would like to create an android Bluetooth scanner. But I can't manage to display anything using a listview. I've tried debugging it for an extended amount of time without success. It seems like the problem doesn't come from the Bluetooth segments. But rather comes from a refreshing/binding issue.

I'm debugging on a physical Android device, the permissions stuff should be ok since the devices list is updating but the linked list view isn't.

It might be worth mentioning that I've started from the visual studio 2019 Xamarin flyout template. Which, uses an app shell to navigate between the pages. I feel like the problem could also come from this since the app shell might mess with the view models links.

P.S: I am relatively new to MVVM.

Any help would be appreciated !!

I have the following code :

ItemPage (.XAML)

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="clavier.Views.ItemsPage"
                 Title="Devices"
                 x:Name="BrowseItemsPage">

        <ContentPage.Content>
            <StackLayout>
                <Button Text="Search" Command="{Binding SearchDeviceCommand}"/>
                <ListView x:Name="DevicesList"
                          ItemsSource="{Binding list, Mode=OneWay}"
                          IsPullToRefreshEnabled="True"
                          CachingStrategy="RecycleElement">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout>
                                    <Label Text="{Binding NativeDevice.Name}"></Label>
                                    <Label Text="{Binding NativeDevice.Address}" ></Label>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <Button Text="End"/>
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>

</code>```

ItemPage code (.XAML.CS)

```<code>namespace clavier.Views
    {
        public partial class ItemsPage : ContentPage
        {
            public ItemsPage()
            {
                BindingContext = new ItemsViewModel();
                InitializeComponent();
            }
        }
    }
</code>```

ViewModel (.CS)

```<code>    ```
    namespace clavier.ViewModels
    {
        public class ItemsViewModel : BaseViewModel
        {
            public IAdapter adapter;
            public IBluetoothLE bluetoothBLE;
            public IDevice SelectedDevice { get; set; }
            public string Title { get; set; }
            public ObservableCollection<IDevice> list { get; set; }
            public Command SearchDeviceCommand { get; }

            public ItemsViewModel()
            {
                bluetoothBLE = CrossBluetoothLE.Current;
                adapter = CrossBluetoothLE.Current.Adapter;
                SearchDeviceCommand = new Command(SearchDevice);
                list = new ObservableCollection<IDevice>();
            }

            public async void SearchDevice()
            {
                if (bluetoothBLE.State == BluetoothState.Off)
                {
                    await Shell.Current.DisplayAlert("Attention", "le bluetooth n'est pas activé.", "OK");
                }
                else
                {
                    list.Clear();
                    adapter.ScanTimeout = 10000;
                    adapter.ScanMode = ScanMode.Balanced;
                    adapter.DeviceDiscovered += (obj, a) =>
                    {
                        if (!list.Contains(a.Device))
                        {
                            list.Add(a.Device);
                        }
                    };
                    await adapter.StartScanningForDevicesAsync();
                }
            }

            public async void DevicesList_OnItemSelected()
            {
                var resullt = await Shell.Current.DisplayAlert("Alerte", "Vous êtes sur le point de vous connecter à cet appareil. Etes vosu sur de vouloir vous connecter ?","Se connecter", "Annuler");

                if (!resullt)
                {
                    return;
                }
                await adapter.StopScanningForDevicesAsync();

                try
                {
                    await adapter.ConnectToDeviceAsync(SelectedDevice);
                    await Shell.Current.DisplayAlert("Connection ...", "Status : " + SelectedDevice.State, "Ok");
                }
                catch (DeviceConnectionException ex)
                {
                    await Shell.Current.DisplayAlert("Erreur !", ex.Message, "Ok");
                }
            }
        }
    }
```
</code>```

My app shell (.XAML)

```<code>```
<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:clavier.Views"
       Title="clavier"
       x:Class="clavier.AppShell">

    <Shell.Resources>
        <ResourceDictionary>

        </ResourceDictionary>
    </Shell.Resources>

    <FlyoutItem Title="Clavier bluetooth" Icon="icon_about.png">
        <ShellContent Route="AboutPage" ContentTemplate="{DataTemplate local:AboutPage}" />
    </FlyoutItem>
    <FlyoutItem Title="Information" Icon="icon_feed.png">
        <ShellContent Route="ItemsPage" ContentTemplate="{DataTemplate local:ItemsPage}" />
    </FlyoutItem>

    <MenuItem Text="Logout" StyleClass="MenuItemLayoutStyle" Clicked="OnMenuItemClicked">
    </MenuItem>

    <TabBar>
        <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate local:LoginPage}" />
    </TabBar>
</Shell>
```
</code>```

During debugging, I've checked the XAML linker errors but I don't have anything. I've also tried step-by-step debugging and the list is correctly updating with the devices.

I've also tried to add the INotifyProprietyChanged as it was suggested in other answers but nothing changed. (I might have incorrectly used it)

Note: I'm using the plugin BLE nuget, and I've followed the instructions from the Git and from tutorials I've found on the web (this one, and this one).

答:
Thanks for your help @ColeX and @Jason! I've figured out what was happening. I don't know how could I've not thought about this earlier.

It appears that the default text color for my ListView was white which explains why I could not see anything.

I don't know why by default the text and the background colors were the same but yeah that was the problem...

Body:
I would like to create an android Bluetooth scanner. But I can't manage to display anything using a listview. I've tried debugging it for an extended amount of time without success. It seems like the problem doesn't come from the Bluetooth segments. But rather comes from a refreshing/binding issue.

I'm debugging on a physical Android device, the permissions stuff should be ok since the devices list is updating but the linked list view isn't.

It might be worth mentioning that I've started from the visual studio 2019 Xamarin flyout template. Which, uses an app shell to navigate between the pages. I feel like the problem could also come from this since the app shell might mess with the view models links.

P.S: I am relatively new to MVVM.

Any help would be appreciated !!

I have the following code :

ItemPage (.XAML)

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="clavier.Views.ItemsPage"
                 Title="Devices"
                 x:Name="BrowseItemsPage">

        <ContentPage.Content>
            <StackLayout>
                <Button Text="Search" Command="{Binding SearchDeviceCommand}"/>
                <ListView x:Name="DevicesList"
                          ItemsSource="{Binding list, Mode=OneWay}"
                          IsPullToRefreshEnabled="True"
                          CachingStrategy="RecycleElement">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout>

                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <Button Text="End"/>
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>

ItemPage code (.XAML.CS)

namespace clavier.Views
    {
        public partial class ItemsPage : ContentPage
        {
            public ItemsPage()
            {
                BindingContext = new ItemsViewModel();
                InitializeComponent();
            }
        }
    }

ViewModel (.CS)

    ```
    namespace clavier.ViewModels
    {
        public class ItemsViewModel : BaseViewModel
        {
            public IAdapter adapter;
            public IBluetoothLE bluetoothBLE;
            public IDevice SelectedDevice { get; set; }
            public string Title { get; set; }
            public ObservableCollection<IDevice> list { get; set; }
            public Command SearchDeviceCommand { get; }

            public ItemsViewModel()
            {
                bluetoothBLE = CrossBluetoothLE.Current;
                adapter = CrossBluetoothLE.Current.Adapter;
                SearchDeviceCommand = new Command(SearchDevice);
                list = new ObservableCollection<IDevice>();
            }

            public async void SearchDevice()
            {
                if (bluetoothBLE.State == BluetoothState.Off)
                {
                    await Shell.Current.DisplayAlert("Attention", "le bluetooth n'est pas activé.", "OK");
                }
                else
                {
                    list.Clear();
                    adapter.ScanTimeout = 10000;
                    adapter.ScanMode = ScanMode.Balanced;
                    adapter.DeviceDiscovered += (obj, a) =>
                    {
                        if (!list.Contains(a.Device))
                        {
                            list.Add(a.Device);
                        }
                    };
                    await adapter.StartScanningForDevicesAsync();
                }
            }

            public async void DevicesList_OnItemSelected()
            {
                var resullt = await Shell.Current.DisplayAlert("Alerte", "Vous êtes sur le point de vous connecter à cet appareil. Etes vosu sur de vouloir vous connecter ?","Se connecter", "Annuler");

                if (!resullt)
                {
                    return;
                }
                await adapter.StopScanningForDevicesAsync();

                try
                {
                    await adapter.ConnectToDeviceAsync(SelectedDevice);
                    await Shell.Current.DisplayAlert("Connection ...", "Status : " + SelectedDevice.State, "Ok");
                }
                catch (DeviceConnectionException ex)
                {
                    await Shell.Current.DisplayAlert("Erreur !", ex.Message, "Ok");
                }
            }
        }
    }
```

My app shell (.XAML)

```
<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:clavier.Views"
       Title="clavier"
       x:Class="clavier.AppShell">

    <Shell.Resources>
        <ResourceDictionary>
            <Style x:Key="BaseStyle" TargetType="Element">
                <Setter Property="Shell.BackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.ForegroundColor" Value="White" />
                <Setter Property="Shell.TitleColor" Value="White" />
                <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
                <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
                <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.TabBarForegroundColor" Value="White"/>
                <Setter Property="Shell.TabBarUnselectedColor" Value="#95FFFFFF"/>
                <Setter Property="Shell.TabBarTitleColor" Value="White"/>
            </Style>
            <Style TargetType="TabBar" BasedOn="{StaticResource BaseStyle}" />
            <Style TargetType="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />

            <Style Class="FlyoutItemLabelStyle" TargetType="Label">
                <Setter Property="TextColor" Value="White"></Setter>
            </Style>
            <Style Class="FlyoutItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                <Setter Property="VisualStateManager.VisualStateGroups">
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor" Value="{x:OnPlatform UWP=Transparent, iOS=White}" />
                                    <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState x:Name="Selected">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateGroupList>
                </Setter>
            </Style>

            <Style Class="MenuItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                <Setter Property="VisualStateManager.VisualStateGroups">
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateGroupList>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Shell.Resources>

    <FlyoutItem Title="Clavier bluetooth" Icon="icon_about.png">
        <ShellContent Route="AboutPage" ContentTemplate="{DataTemplate local:AboutPage}" />
    </FlyoutItem>
    <FlyoutItem Title="Information" Icon="icon_feed.png">
        <ShellContent Route="ItemsPage" ContentTemplate="{DataTemplate local:ItemsPage}" />
    </FlyoutItem>

    <MenuItem Text="Logout" StyleClass="MenuItemLayoutStyle" Clicked="OnMenuItemClicked">
    </MenuItem>

    <TabBar>
        <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate local:LoginPage}" />
    </TabBar>
</Shell>
```

During debugging, I've checked the XAML linker errors but I don't have anything. I've also tried step-by-step debugging and the list is correctly updating with the devices.

I've also tried to add the INotifyProprietyChanged as it was suggested in other answers but nothing changed. (I might have incorrectly used it)

Note: I'm using the plugin BLE nuget, and I've followed the instructions from the Git and from tutorials I've found on the web (this one, and this one).


问:
I am not able to install PyAutoGui
https://i.stack.imgur.com/IMG04.png

```<code>C:\Windows\System32>pip install pyautogui
Fatal error in launcher: Unable to create process
using '"C:\Python310\python.exe"  "C:\Python310\Scripts\pip.exe"
install pyautogui': The system cannot find the file specified.
</code>```

I've tried installing PyAutoGui for a while now, but this error keeps appearing.

I have tried reinstalling Python, but that didn't work.

The version of Python I am using is 3.10.2.

I am using Windows 11 Home Insider Preview Single Language.

答:
Best way to work with python is to create virutal environment for an application and then you can install any module with pip install <module_name>
Please follow this link
https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/</p>

Title: I am not able to install PyAutoGui

Body:
https://i.stack.imgur.com/IMG04.png

C:\Windows\System32>pip install pyautogui
Fatal error in launcher: Unable to create process
using '"C:\Python310\python.exe"  "C:\Python310\Scripts\pip.exe"
install pyautogui': The system cannot find the file specified.

I've tried installing PyAutoGui for a while now, but this error keeps appearing.

I have tried reinstalling Python, but that didn't work.

The version of Python I am using is 3.10.2.

I am using Windows 11 Home Insider Preview Single Language.


问:
How to print a X with two letters inside a square
I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again.

P p p p p p Q
p P p p p Q q
p p P p Q q q
p p p Q q q q
p p Q q Q q q
p Q q q q Q q
Q q q q q q Q
```
```int main()
{
    int loopLimit = 7;
    int upperCharacter = 0;

    do {
        int loopCounter = 0;

        do {
            if (loopCounter == upperCharacter) std::cout << "P ";
            else std::cout << "p ";
            loopCounter = loopCounter + 1;
        } while (loopCounter < loopLimit);

        upperCharacter = upperCharacter + 1;
        loopLimit = loopLimit - 1;
        std::cout << "\n";
    } while (loopLimit > 0);
}
```
<p>My code currently outputs:</p>
<pre class="lang-none prettyprint-override"><code>P p p p p p p
p P p p p p
p p P p p
p p p P
p p p
p p
p
</code>```

答:
A pen and a paper solved this question.

Here's the solution:

```<code>for (int satirSayaci = 1; satirSayaci < 8; satirSayaci++) {
        for (int karakterSayaci = 1; karakterSayaci < 8; karakterSayaci++)
        {
            if (karakterSayaci >= 8 - satirSayaci) {
                if (karakterSayaci == 8 - satirSayaci || karakterSayaci == satirSayaci) std::cout << "X ";
                else std::cout << "x ";
            } else {
                if (karakterSayaci == satirSayaci) std::cout << "P ";
                else std::cout << "p ";
            }
        }

        // Yeni bir satir yazdir
        std::cout << std::endl;
    }
</code>```

Body:
I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again.

P p p p p p Q
p P p p p Q q
p p P p Q q q
p p p Q q q q
p p Q q Q q q
p Q q q q Q q
Q q q q q q Q

int main()
{
    int loopLimit = 7;
    int upperCharacter = 0;

    do {
        int loopCounter = 0;

        do {
            if (loopCounter == upperCharacter) std::cout << "P ";
            else std::cout << "p ";
            loopCounter = loopCounter + 1;
        } while (loopCounter < loopLimit);

        upperCharacter = upperCharacter + 1;
        loopLimit = loopLimit - 1;
        std::cout << "\n";
    } while (loopLimit > 0);
}

My code currently outputs:

P p p p p p p
p P p p p p
p p P p p
p p p P
p p p
p p
p

Body:
A pen and a paper solved this question.

Here's the solution:

for (int satirSayaci = 1; satirSayaci < 8; satirSayaci++) {
        for (int karakterSayaci = 1; karakterSayaci < 8; karakterSayaci++)
        {
            if (karakterSayaci >= 8 - satirSayaci) {
                if (karakterSayaci == 8 - satirSayaci || karakterSayaci == satirSayaci) std::cout << "X ";
                else std::cout << "x ";
            } else {
                if (karakterSayaci == satirSayaci) std::cout << "P ";
                else std::cout << "p ";
            }
        }

        // Yeni bir satir yazdir
        std::cout << std::endl;
    }


问:
regarding distorted back button on iOS app using UINavigationController
I am using UINavigationController in my app. In most of the iPhones I tested its fine. However, on an iPhone4 the back button is sometimes (not always) distorted.

Can anyone kindly tell me if theres something I have missed or if there is something I should do?

Thanks.

答: This may be a long shot, but check your logs to see if you're get any errors related to core animation and/or bad transforms. I've seen something like this before.</p>


问:
Prevent killing some pods when scaling down possible?
I need to scale a set of pods that run queue-based workers. Jobs for workers can run for a long time (hours) and should not get interrupted. The number of pods is based on the length of the worker queue. Scaling would be either using the horizontal autoscaler using custom metrics, or a simple controller that changes the number of replicas.

Problem with either solution is that, when scaling down, there is no control over which pod(s) get terminated. At any given time, most workers are likely working on short running jobs, idle, or (more rare) processing a long running job. I'd like to avoid killing the long running job workers, idle or short running job workers can be terminated without issue.

What would be a way to do this with low complexity? One thing I can think of is to do this based on CPU usage of the pods. Not ideal, but it could be good enough. Another method could be that workers somehow expose a priority indicating whether they are the preferred pod to be deleted. This priority could change every time a worker picks up a new job though.

Eventually all jobs will be short running and this problem will go away, but that is a longer term goal for now.

答:
I think running this type of workload using a Deployment or similar, and using a HorizontalPodAutoscaler for scaling, is the wrong way to go. One way you could go about this is to:

Define a controller (this could perhaps be a Deployment) whose task is to periodically create a Kubernetes Job object.

The spec of the Job should contain a value for .spec.parallelism equal to the maximum number of concurrent executions you will accept.

The Pods spawned by the Job then run your processing logic. They should each pull a message from the queue, process it, and then delete it from the queue (in the case of success).

The Job must exit with the correct status (success or failure). This ensures that the Job recognises when the processing has completed, and so will not spin up additional Pods.

Using this method, .spec.parallelism controls the autoscaling based on how much work there is to be done, and scale-down is an automatic benefit of using a Job.


问:
Using User Managed Identity in Azure function Service Bus triggers not working
I have a function that uses Service bus trigger and wanted to use "User Managed Identity". I couldn't get this working even after following all the config settings.
Below is the config I am using :

The Function trigger looks like:

```<code>public static async Task Run([ServiceBusTrigger("myqueue", Connection = "ServiceBusUsrIdty")] ServiceBusReceivedMessage[] servBusRcvMsg, ILogger log)
</code>```

In the App settings:

```<code>ServiceBusUsrIdty__fullyQualifiedNamespace = <service bus namespace>.servicebus.windows.net
ServiceBusUsrIdty__clientId = <client id of the user managed identity>
ServiceBusUsrIdty__credential = "managedidentity"
</code>```

With the above setting, I couldn't get it working and I then added the below as well but no luck
AzureWebJobsServiceBusUsrIdty = "Endpoint=sb://.servicebus.windows.net/;Authentication=ManagedIdentity"

I am using the package : Azure.Messaging.ServiceBus v7.5.1
The User managed identity is added in the Function App settings and it was granted "Contributor" access in the service bus

What else am I missing to get this working ? The documentation from Microsoft doesn't sufficient details though.

答:
There is slight syntax mistake in the Service Bus connection stored in the 'AzureWebJobsServiceBusUsrIdty'.

It means the connection string must have a space between "Managed" and "Identity", i.e.

```<code>Endpoint=sb://myendpoint.servicebus.windows.net/;Authentication=Managed Identity
</code>```

Include the space for the Authentication value as shown above and run the function.

Refer here for more information

Body:
I have a function that uses Service bus trigger and wanted to use "User Managed Identity". I couldn't get this working even after following all the config settings.
Below is the config I am using :

The Function trigger looks like:

public static async Task Run([ServiceBusTrigger("myqueue", Connection = "ServiceBusUsrIdty")] ServiceBusReceivedMessage[] servBusRcvMsg, ILogger log)

In the App settings:

ServiceBusUsrIdty__fullyQualifiedNamespace = <service bus namespace>.servicebus.windows.net
ServiceBusUsrIdty__clientId = <client id of the user managed identity>
ServiceBusUsrIdty__credential = "managedidentity"

With the above setting, I couldn't get it working and I then added the below as well but no luck
AzureWebJobsServiceBusUsrIdty = "Endpoint=sb://.servicebus.windows.net/;Authentication=ManagedIdentity"

I am using the package : Azure.Messaging.ServiceBus v7.5.1
The User managed identity is added in the Function App settings and it was granted "Contributor" access in the service bus

What else am I missing to get this working ? The documentation from Microsoft doesn't sufficient details though.

Body:
There is slight syntax mistake in the Service Bus connection stored in the 'AzureWebJobsServiceBusUsrIdty'.

It means the connection string must have a space between "Managed" and "Identity", i.e.

Endpoint=sb://myendpoint.servicebus.windows.net/;Authentication=Managed Identity

Include the space for the Authentication value as shown above and run the function.

Refer here for more information


问:
Why I can't pass string literals to const char* const& in this specialized function template
Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal?

Here's the thing. There are two excercises about template specialization in C++ Primer:

Exercise 16.63: Define a function template to count the number of
occurrences of a given value in a vector. Test your program by passing it a
vector of doubles, a vector of ints, and a vector of strings.

Exercise 16.64: Write a specialized version of the template from the
previous exercise to handle vector<const char*> and a program that
uses this specialization.

The code below is my answer, the compile error appears when I pass the string literal to this specialized count function.

```<code>// Count the number of occurrences of a given value in a vector
template <typename T>
std::size_t count(const std::vector<T>& vec, const T& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (v == value)
            ++i;
    }
    return i;
}

// A specialized version where T = const char*
template <>
std::size_t count(const std::vector<const char*>& vec, const char* const& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (!strcmp(v, value))
            ++i;
    }
    return i;
}

int main()
{
    std::vector<const char*> sVec{ "cpp", "primer", "cpp", "fifth", "edition", "Cpp", "cpp" };

    // Error message: no instance of function template "count" matches the argument list,
    // argument types are: (std::vector<const char *, std::allocator<const char *>>, const char [4])
    std::cout << count(sVec, "cpp") << std::endl;

    return 0;
}
</code>```

Besides, it's perfectly ok to pass a string literal to const char* const& in a nontemplate function, which makes me confused.

```<code>void test(const char* const& str)
{
    std::cout << str << std::endl;
}

int main()
{
    test("cpp"); // Prints "cpp" as expected
    return 0;
}
</code>```

答:
An array and a pointer are different types.

It is because of default conversions, that you can pass an array as a pointer parameter.

A template is just that, a "template" for a function.

There is no concrete function to match the parameters that have been specified. So the compiler tries to generate a function from the parameters and can't make a match, so it fails.

But when you specify the template parameter, the compiler knows exactly which function you want, generates it, then tries to call the function using standard rules for calling functions, which allow it to make the conversion.

When you have a template function definition, the requirements for function arguments are stricter.

In this case it will try to match the array and generate the function from the template and Fail. So no function will be available to call.

You can specialize:

```<code>// A specialized version where T = const char[ArraySize]
template<std::size_t ArraySize>
std::size_t count(const std::vector<const char*>& vec, const char (&value)[ArraySize])
{
    return count<const char*>(vec, value);
}
</code>```

-- Edit

Or specifically defining a template parameter function, which defines a concrete function to call.

Body:
Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal?

Here's the thing. There are two excercises about template specialization in C++ Primer:

Exercise 16.63: Define a function template to count the number of
occurrences of a given value in a vector. Test your program by passing it a
vector of doubles, a vector of ints, and a vector of strings.

Exercise 16.64: Write a specialized version of the template from the
previous exercise to handle vector<const char*> and a program that
uses this specialization.

The code below is my answer, the compile error appears when I pass the string literal to this specialized count function.

// Count the number of occurrences of a given value in a vector
template <typename T>
std::size_t count(const std::vector<T>& vec, const T& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (v == value)
            ++i;
    }
    return i;
}

// A specialized version where T = const char*
template <>
std::size_t count(const std::vector<const char*>& vec, const char* const& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (!strcmp(v, value))
            ++i;
    }
    return i;
}

int main()
{
    std::vector<const char*> sVec{ "cpp", "primer", "cpp", "fifth", "edition", "Cpp", "cpp" };

    // Error message: no instance of function template "count" matches the argument list,
    // argument types are: (std::vector<const char *, std::allocator<const char *>>, const char [4])
    std::cout << count(sVec, "cpp") << std::endl;

    return 0;
}

Besides, it's perfectly ok to pass a string literal to const char* const& in a nontemplate function, which makes me confused.

void test(const char* const& str)
{
    std::cout << str << std::endl;
}

int main()
{
    test("cpp"); // Prints "cpp" as expected
    return 0;
}

Body:
An array and a pointer are different types.

It is because of default conversions, that you can pass an array as a pointer parameter.

A template is just that, a "template" for a function.

There is no concrete function to match the parameters that have been specified. So the compiler tries to generate a function from the parameters and can't make a match, so it fails.

But when you specify the template parameter, the compiler knows exactly which function you want, generates it, then tries to call the function using standard rules for calling functions, which allow it to make the conversion.

When you have a template function definition, the requirements for function arguments are stricter.

In this case it will try to match the array and generate the function from the template and Fail. So no function will be available to call.

You can specialize:

// A specialized version where T = const char[ArraySize]
template<std::size_t ArraySize>
std::size_t count(const std::vector<const char*>& vec, const char (&value)[ArraySize])
{
    return count<const char*>(vec, value);
}

-- Edit

Or specifically defining a template parameter function, which defines a concrete function to call.


问:
Add form with validation using php and html to website
Update:  I'm using NicePage to create the website, and something in it is breaking the scriptgenerator.net code.  I'm getting this error in the browser.

```<code>Uncaught TypeError: $(...).validate is not a function
</code>```

Most of my experience in coding has been in COBOL, and I'm not that familiar with php and css.

I need to create a customer form on a website.  In order to do this I used the HTML-PHP-jQuery simple contact form v2 found on https://www.scriptgenerator.net

Here are the issues I'm having:

I can imbed the form.php into my webpage, but I haven't been able to
get the field labels to be left vertical justified as shown in the
generator's picture.

Also, the validation doesn't seem to do anything but reload the
page, no error messages or anything.

I'm not stuck using scriptgenerator.net, but would really appreciate any and all help.  I will also add a recaptcha to the page, but want to get the contact form working first.

The form generator shows this for a preview, which pretty much what I need.

Following the instructions, I downloaded the generator code and the js required.

Here is the form.php as copied from the generator.

```<code><title>Contact Form</title>
    <style type="text/css">
        #contact_wrapper {
            width:100%; /* you can change the form width by just changing this line */
            font-family:Arial, Helvetica, sans-serif;
            font-size:90%;
            margin-bottom:20px;
        }
        #contact_wrapper legend {
            display: inherit;
            border:none;
            width:auto;
            font-size:120%;
            font-weight:bold;
        }

        #contact_wrapper .genField {
            display: block;
            width: 100%;
            height: 34px;
            padding: 6px 20px;

            line-height: 1.42857143;
            color: #222;
            background-color: #fff;
            background-image: none;
            border: 1px solid #ccc;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
            box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
            -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
            -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
            transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
            -webkit-box-sizing:border-box;
            -moz-box-sizing:border-box;
            box-sizing:border-box;
        }
        #contact_wrapper .genField.auto { width:auto; }
        #contact_wrapper textarea.genField { min-height:200px; }

        #contact_wrapper .button {
            display: inline-block;
            padding: 6px 12px;
            margin-bottom: 0;
            font-size: 14px;
            font-weight: 400;
            line-height: 1.42857143;
            text-align: center;
            white-space: nowrap;
            vertical-align: middle;
            -ms-touch-action: manipulation;
            touch-action: manipulation;
            cursor: pointer;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            background-image: none;
            border: 1px solid transparent;
            border-radius: 4px;
            color: #fff;
        }
        #contact_wrapper .f_left { float:left; }
        #contact_wrapper .f_radio{ font-weight:normal; display:block; }

        #contact_wrapper .submit{ background-color: #337ab7; border-color: #2e6da4; padding:6px 30px; margin-left:10px; }
        #contact_wrapper .reset { background-color: #d9534f; border-color: #d43f3a; }

        #contact_wrapper .submit:hover{ background-color: #286090; }
        #contact_wrapper .reset:hover   { background-color: #C9302C; }

        #contact_wrapper input.error, #contact_wrapper textarea.error { border: 1px dashed #F41724; }

        #contact_wrapper label {
            display: block;
            width:auto;
            line-height: 1.8;
            vertical-align: top;
            cursor: pointer;
            color: #222;
            margin-top:12px;
        }
        #contact_wrapper label.error {font-size:80%; color:#F41724; margin-top:2px; float: right; }

        #contact_wrapper .buttons, #contact_wrapper .captcha { margin-top:15px; }

        #contact_wrapper .captcha label.f_left { margin:7px 10px inherit inherit;}

        #contact_wrapper #results p {
            padding: 20px;
            color: #FFFFFF;
            font-weight: bold;
            border-radius: 5px;
        }

        #contact_wrapper #results p.sending_success { background-color: #337AB7; }
        #contact_wrapper #results p.sending_error   { background-color: #D9534F; }

        .clearfix:after {
           content: ".";
           visibility: hidden;
           display: block;
           height: 0;
           clear: both;
        }
    </style>

</head>
<body>

<div id="contact_wrapper">

    <fieldset id="form_wrapper">
        <legend>Contact Form</legend>
        <form name="contactme" id="contactme" action="" method="post">
                        <label for="fname">First Name *</label>
            <input type="text" name="fname" id="fname" class="genField" />
                        <label for="email">Email *</label>
            <input type="text" name="email" id="email" class="genField" />

            <label for="subject">Subject *</label>
            <input type="text" name="subject" id="subject" class="genField" />

            <label for="message">Message *</label>
            <textarea name="message" id="message" class="genField"></textarea>

            <div class="clearfix"></div>
            <div class="buttons">
                <input type="reset" class="button reset" name="reset" value="X" />
                <input type="submit" class="button submit" name="submit" value="Submit Form" />

                <span style="float:right; margin-top:8px;">
                    <a href="http://scriptgenerator.net/html-php-jquery-simple-contact-form-v2/" title="Valid Contact Form">
                        <img    src="http://www.scriptgenerator.net/generator/html-php-contact-form-mailer-generator_files/validform.jpg"
                                alt="Valid Contact Form" width="20" height="20" />
                    </a>
                </span>
            </div>
        </form>

    </fieldset>

    <!-- We will output the results from process.php here -->
    <div id="results" style="display:none;"></div>

</div>

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var msj = "Please enter valid data"; // you can insert here a customized error message
        $('#contactme').validate({
            debug: false,
            rules: {
                // You can set rools to validatate fields here
                fname: { required: true, minlength:2 },
                email: { required: true, email: true },
                subject: { required: true, minlength:2 },
                message: { required: true, minlength:2 },

            },
            messages: {
                // You can also set a custom message for each field
                fname: "Please enter a valid Name",
                email: "Please enter a valid email address",
                subject: msj,
                message: msj,

            },
            submitHandler: function(form) {
                $("#form_wrapper").hide();
                // do adicional stuff of form validation
                $.post("process.php", $("#contactme").serialize(), function(data) {
                    $("#results").html(data).show(1000);
                });
            }
        });
    });
</script>
</code>```

and the process.php

```<code><?php
// Wait a second to simulate a some latency
usleep(500000);

function m($m, $t=NULL){
    return "<p class='".($t=="s"?"sending_success":"sending_error")."'>".$m."</p>";
}

global $email_send_to, $email_recived_from, $success_msj, $error_msj;

// edit email where contact form is sent
$email_send_to = "";
// edit your domain
$email_recived_from = "";

// edit message for a successfully sent contact form
$success_msj = "Your message has been sent. Thank you for your feedback. We will contact you shortly if needed";
// edit error message
$error_msj = "Ups, There has been an error while sending. Please try again in a few minutes or panic appropriately!";
// edit subject here. If user enters no subject, we will use this one
$standard_subject = "Someone contacted you on ".$email_recived_from;

//------------------------------------------------------------------------------------------------//
function secure($post) {
    if (is_array($post)):
        foreach($post as $item=>$value):
            $post[$item] = term( $value ); //This helps not to break code if single or doble cuotes are sent to process
            $post[$item] = trim( $value ); // Strip whitespace (or other characters) from the beginning and end of a string
        endforeach;
    else:
        $post = term( $post ); //This helps not to break code if single or doble cuotes are sent to process
        $post = trim( $post ); // Strip whitespace (or other characters) from the beginning and end of a string
    endif;
    $post = mynl2br($post);

    // insert here aditional security functions

    return $post;
}
//------------------------------------------------------------------------------------------------//
// if someone sends you cods or scripts via contact form, this will prevent it from being interpreted
function mynl2br($post) {
   return strtr($post, array("\t"=>"    ", "<"=>"<", ">"=>">", "\r\n" => "<br />", "\r" => "<br />", "\n" => "<br />"));
}

//------------------------------------------------------------------------------------------------//
function term($post){
//  DO NOT INDENT THIS. adicional spaces are interpreted. This helps not to break code if single or doble cuotes are sent to process
$post = <<<term
$post
term;
return $post;
}
//------------------------------------------------------------------------------------------------//

// Pull out data from contact form
$fname = (isset($_POST['fname'])?secure($_POST['fname']):'');
$email = (isset($_POST['email'])?secure($_POST['email']):'');
$subject = (isset($_POST['subject'])?secure($_POST['subject']):'');
$message = (isset($_POST['message'])?secure($_POST['message']):'');

//------------------------------------------------------------------------------------------------//
$email_recived_from  = str_replace ("http://", "", $email_recived_from );
$email_recived_from  = str_replace ("www.", "", $email_recived_from );

$from = $email_recived_from." <contact@".$email_recived_from.">";

$mail_subject = (empty($subject)?$standard_subject:$subject);
//------------------------------------------------------------------------------------------------//

//------------------------------------------------------------------------------------------------//
// setting HTML email function
function sendHTMLemail($body,$from, $to, $subject) {

    global $success_msj, $error_msj;
    $boundary = uniqid("HTMLEMAIL");

    $headers  = "From: $from\r\n";
    $headers .= "MIME-Version: 1.0\r\n";

    $headers .= "Content-Type: multipart/alternative;".
                "boundary = $boundary\r\n\r\n";
    $headers .= "This is a MIME encoded message.\r\n\r\n";

    $headers .= "--$boundary\r\n".
                "Content-Type: text/html; charset=utf-8\r\n".
                "Content-Transfer-Encoding: base64\r\n\r\n";

    $headers .= chunk_split(base64_encode($body));

    return ( mail($to,$subject,"",$headers,"-f".$from) ? m($success_msj,"s") : m($error_msj) );
}
//------------------------------------------------------------------------------------------------//

ob_start();?>
<html>
<head>
    <!--
        Lots of email clients strip all head information like CSS style classes.
        That is why we included all style directly into the body using span tags.
        Table was used for the layout to increase outlook compatibility and other old email clients.
    -->
</head>
<body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0" bgcolor="#8ED4F4" >

<table width="100%"  cellspacing="0" bgcolor="#8ED4F4" >
    <tr>
        <td valign="top" align="center">

            <table width="80%" style=" width:80%;min-width:326px;margin-top:10px;" cellpadding="20" cellspacing="0" bgcolor="#FFFFFF">
                <tr>
                    <td style="background-color:#337AB7; text-align:center; padding:10px;" align="center">
                        <span style="color:#fff;font-family:arial; font-size:140%;">A new person <span style="color:#FF9366">contacted</span> you:</span>
                    </td>

                </tr>

                <tr>

                    <td bgcolor="#FFFFFF">

                        <p>
                            <span style="font-size:12px;font-weight:normal;color:#666;font-family:arial;line-height:150%;">
                                                                <br /><strong>First Name:</strong> <?=$fname?>
                                <br /><strong>Email:</strong> <?=$email?>
                                <br /><strong>Subject:</strong> <?=$subject?>
                                <br /><strong>Message:</strong> <?=$message?>

                            </span>
                        </p>
                    </td>
                </tr>
                <tr>
                    <td style="background-color:#337AB7; text-align:center;" align="center" valign="top" colspan="2">
                        <span style="font-size:11px;color:#fff;line-height:200%;font-family:arial;text-decoration:none;">Contact service provided by <br />
                            <a style="color:#fff; font-weight:bold; font-size:110%; text-decoration:none;" href="http://scriptgenerator.net" title="scriptgenerator.net">
                                <span style="color:#FF9366">Script</span>Generator
                            </a>
                        </span>
                    </td>
                </tr>
            </table>

        </td>
    </tr>
</table>
</body>
</html>
<? $HTML = ob_get_clean();

// display succes or error message depending is email has been sent or not
echo sendHTMLemail($HTML,$from,$email_send_to,$mail_subject);
?>
</code>```

There are 2 js files, jquery-1.4.2-mini.js and jquery.validate.min.js, which I can provide if necessary, but can also be downloaded from the form generator website.

Here's what it looks like when I imbed it.

答: There is php class named php-form-validator at https://github.com/Umamad/php-form-validator that can make your job easier.

Body:
Update:  I'm using NicePage to create the website, and something in it is breaking the scriptgenerator.net code.  I'm getting this error in the browser.

Uncaught TypeError: $(...).validate is not a function

Most of my experience in coding has been in COBOL, and I'm not that familiar with php and css.

I need to create a customer form on a website.  In order to do this I used the HTML-PHP-jQuery simple contact form v2 found on https://www.scriptgenerator.net

Here are the issues I'm having:

I can imbed the form.php into my webpage, but I haven't been able to
get the field labels to be left vertical justified as shown in the
generator's picture.

Also, the validation doesn't seem to do anything but reload the
page, no error messages or anything.

I'm not stuck using scriptgenerator.net, but would really appreciate any and all help.  I will also add a recaptcha to the page, but want to get the contact form working first.

The form generator shows this for a preview, which pretty much what I need.

Following the instructions, I downloaded the generator code and the js required.

Here is the form.php as copied from the generator.

<title>Contact Form</title>

    <fieldset id="form_wrapper">
        <legend>Contact Form</legend>
        <form name="contactme" id="contactme" action="" method="post">
                        First Name *
            <input type="text" name="fname" id="fname" class="genField" />
                        Email *
            <input type="text" name="email" id="email" class="genField" />

            Subject *
            <input type="text" name="subject" id="subject" class="genField" />

            Message *
            <textarea name="message" id="message" class="genField"></textarea>

                <input type="reset" class="button reset" name="reset" value="X" />
                <input type="submit" class="button submit" name="submit" value="Submit Form" />

        </form>

    </fieldset>

and the process.php

<?php
// Wait a second to simulate a some latency
usleep(500000);

function m($m, $t=NULL){
    return "
".$m."
";
}

global $email_send_to, $email_recived_from, $success_msj, $error_msj;

// edit email where contact form is sent
$email_send_to = "";
// edit your domain
$email_recived_from = "";

// edit message for a successfully sent contact form
$success_msj = "Your message has been sent. Thank you for your feedback. We will contact you shortly if needed";
// edit error message
$error_msj = "Ups, There has been an error while sending. Please try again in a few minutes or panic appropriately!";
// edit subject here. If user enters no subject, we will use this one
$standard_subject = "Someone contacted you on ".$email_recived_from;

//------------------------------------------------------------------------------------------------//
function secure($post) {
    if (is_array($post)):
        foreach($post as $item=>$value):
            $post[$item] = term( $value ); //This helps not to break code if single or doble cuotes are sent to process
            $post[$item] = trim( $value ); // Strip whitespace (or other characters) from the beginning and end of a string
        endforeach;
    else:
        $post = term( $post ); //This helps not to break code if single or doble cuotes are sent to process
        $post = trim( $post ); // Strip whitespace (or other characters) from the beginning and end of a string
    endif;
    $post = mynl2br($post);

    // insert here aditional security functions

    return $post;
}
//------------------------------------------------------------------------------------------------//
// if someone sends you cods or scripts via contact form, this will prevent it from being interpreted
function mynl2br($post) {
   return strtr($post, array("\t"=>"    ", "<"=>"<", ">"=>">", "\r\n" => "
", "\r" => "
", "\n" => "
"));
}

//------------------------------------------------------------------------------------------------//
function term($post){
//  DO NOT INDENT THIS. adicional spaces are interpreted. This helps not to break code if single or doble cuotes are sent to process
$post = <<<term
$post
term;
return $post;
}
//------------------------------------------------------------------------------------------------//

// Pull out data from contact form
$fname = (isset($_POST['fname'])?secure($_POST['fname']):'');
$email = (isset($_POST['email'])?secure($_POST['email']):'');
$subject = (isset($_POST['subject'])?secure($_POST['subject']):'');
$message = (isset($_POST['message'])?secure($_POST['message']):'');

//------------------------------------------------------------------------------------------------//
$email_recived_from  = str_replace ("http://", "", $email_recived_from );
$email_recived_from  = str_replace ("www.", "", $email_recived_from );

$from = $email_recived_from." <contact@".$email_recived_from.">";

$mail_subject = (empty($subject)?$standard_subject:$subject);
//------------------------------------------------------------------------------------------------//

//------------------------------------------------------------------------------------------------//
// setting HTML email function
function sendHTMLemail($body,$from, $to, $subject) {

    global $success_msj, $error_msj;
    $boundary = uniqid("HTMLEMAIL");

    $headers  = "From: $from\r\n";
    $headers .= "MIME-Version: 1.0\r\n";

    $headers .= "Content-Type: multipart/alternative;".
                "boundary = $boundary\r\n\r\n";
    $headers .= "This is a MIME encoded message.\r\n\r\n";

    $headers .= "--$boundary\r\n".
                "Content-Type: text/html; charset=utf-8\r\n".
                "Content-Transfer-Encoding: base64\r\n\r\n";

    $headers .= chunk_split(base64_encode($body));

    return ( mail($to,$subject,"",$headers,"-f".$from) ? m($success_msj,"s") : m($error_msj) );
}
//------------------------------------------------------------------------------------------------//

ob_start();?>

                        A new person contacted you:

First Name: <?=$fname?>

Email: <?=$email?>

Subject: <?=$subject?>

Message: <?=$message?>

                        Contact service provided by

                                ScriptGenerator

<? $HTML = ob_get_clean();

// display succes or error message depending is email has been sent or not
echo sendHTMLemail($HTML,$from,$email_send_to,$mail_subject);
?>

There are 2 js files, jquery-1.4.2-mini.js and jquery.validate.min.js, which I can provide if necessary, but can also be downloaded from the form generator website.

Here's what it looks like when I imbed it.


问:
Access PHP Logfile
is there  any "sexy" solution to access the php error_log from remote? Like implemented in Zend Server CE?

Or how to you handle it, if there is no SSH Access for the server users?

To clarify: it is our own server running on winXP :-)

答: If you use any hosting provider it's possible that error_log to be accessible via control panel.</p>

Title: Access PHP Logfile


问:
Compare values in two dataframes
I have two dataframes. When values in data1['col1'] match with values in data2['col1'], I want to apply a string change in data1['col2']. I don't have any error, but the change is not applying.

Sample of the input :

```<code>data1 = {"col1": ["001", "002", "004"], "col2" : ["SL", "SL", "SL"]}
df1 = pd.DataFrame(data1)
data2  = {"col1": ["009", "004", "025"]}
df2 = pd.DataFrame(data2)

print(df1)
print(df2)

col1 col2
0  001   SL
1  002   SL
2  004   SL

col1
0  009
1  004
2  025

for idx, val in df1["col1"].iteritems():
    for idx2, val2 in df2["col1"].iteritems():
        if val == val2:
            df1["col2"][idx] = "SL MATCH"
</code>```

Output expected :

```<code>print(df1)

col1      col2
0  001        SL
1  002        SL
2  004  SL MATCH
</code>```

答:
Use Series.isin for check values by another column:

```<code>df1.loc[df1['col1'].isin(df2['col1']), "col2"] = "SL MATCH"
print (df1)
  col1      col2
0  001        SL
1  002        SL
2  004  SL MATCH
</code>```

Or:

```<code>df1["col2"] = np.where(df1['col1'].isin(df2['col1']), "SL MATCH", df1["col2"])
</code>```

Title: Compare values in two dataframes

Body:
I have two dataframes. When values in data1['col1'] match with values in data2['col1'], I want to apply a string change in data1['col2']. I don't have any error, but the change is not applying.

Sample of the input :

data1 = {"col1": ["001", "002", "004"], "col2" : ["SL", "SL", "SL"]}
df1 = pd.DataFrame(data1)
data2  = {"col1": ["009", "004", "025"]}
df2 = pd.DataFrame(data2)

print(df1)
print(df2)

col1 col2
0  001   SL
1  002   SL
2  004   SL

col1
0  009
1  004
2  025

for idx, val in df1["col1"].iteritems():
    for idx2, val2 in df2["col1"].iteritems():
        if val == val2:
            df1["col2"][idx] = "SL MATCH"

Output expected :

print(df1)

col1      col2
0  001        SL
1  002        SL
2  004  SL MATCH

Body:
Use Series.isin for check values by another column:

df1.loc[df1['col1'].isin(df2['col1']), "col2"] = "SL MATCH"
print (df1)
  col1      col2
0  001        SL
1  002        SL
2  004  SL MATCH

Or:

df1["col2"] = np.where(df1['col1'].isin(df2['col1']), "SL MATCH", df1["col2"])


问:
About input_shape in keras.layers from tensorflow
I am a beginner for tensorflow. I had just tried to fit a simple LeNet-5 for mnist data.

My training and test data are first in Numpy format. i.e., (60000, 28, 28). Then I set my model as below.

```<code>model_LeNet5 = Sequential([
    layers.Conv2D(6, kernel_size=3, strides=1, input_shape=(28, 28, 1)),
    layers.MaxPooling2D(pool_size=2,strides=2),
    layers.ReLU(),
    layers.Conv2D(16,kernel_size=3,strides=1),
    layers.MaxPooling2D(pool_size=2,strides=2),
    layers.ReLU(),
    layers.Flatten(),
    layers.Dense(120, activation='relu'),
    layers.Dense(84, activation='relu'),
    layers.Dense(10)
])
</code>```

I could understand that I get success when I set input_shape as (28,28) or train_images.shape[1:], but I can not understand that input_shape = (28,28,1) is also worked (shown as code above).

It seems that there is an inconsistancy between the shape of data and setting of input size (i.e., [60000,28,28] vs [28,28,1]). Also the broadcast rule may not link [60000,28,28] with [28,28,1].
Thanks for anyone who will explain the mechanism of input_shape.

答:
A single grayscale image can be represented using a two-dimensional (2D) NumPy array or a tensor. Since there is only one channel in a grayscale image, we don’t need an extra dimension to represent the color channel. The two dimensions represent the height and width of the image.

A batch of 3 grayscale images can be represented using a three-dimensional (3D) NumPy array or a tensor. Here, we need an extra dimension to represent the number of images.

For more information, check out this article on towardsdatascience.

Body:
I am a beginner for tensorflow. I had just tried to fit a simple LeNet-5 for mnist data.

My training and test data are first in Numpy format. i.e., (60000, 28, 28). Then I set my model as below.

model_LeNet5 = Sequential([
    layers.Conv2D(6, kernel_size=3, strides=1, input_shape=(28, 28, 1)),
    layers.MaxPooling2D(pool_size=2,strides=2),
    layers.ReLU(),
    layers.Conv2D(16,kernel_size=3,strides=1),
    layers.MaxPooling2D(pool_size=2,strides=2),
    layers.ReLU(),
    layers.Flatten(),
    layers.Dense(120, activation='relu'),
    layers.Dense(84, activation='relu'),
    layers.Dense(10)
])

I could understand that I get success when I set input_shape as (28,28) or train_images.shape[1:], but I can not understand that input_shape = (28,28,1) is also worked (shown as code above).

It seems that there is an inconsistancy between the shape of data and setting of input size (i.e., [60000,28,28] vs [28,28,1]). Also the broadcast rule may not link [60000,28,28] with [28,28,1].
Thanks for anyone who will explain the mechanism of input_shape.


问:
What is the best way of converting a large folder of bmp files to jpeg?
I have a large folder of BMP files and I want to write a script that will loop through all the files in the folder and convert all BMP files into jpeg. I want it to continuously run as it will be used on a production line where new BMP images will be uploaded regularly.</p>

答:
You can simply use Pillow library. Use os.listdir to get a list of all the images to convert, then open each image with Pillow and save it as .png.</p>
```<code>from PIL import Image
import os

path = "/image_folder/"
images= os.listdir(path)
for img in images:
    Image.open(img).save(os.path.join(path+ str(img).replace(".bmp",".png") + '.png'))
    os.remove(os.path.join(path + img))
</code>```

Body:
You can simply use Pillow library. Use os.listdir to get a list of all the images to convert, then open each image with Pillow and save it as .png.

from PIL import Image
import os

path = "/image_folder/"
images= os.listdir(path)
for img in images:
    Image.open(img).save(os.path.join(path+ str(img).replace(".bmp",".png") + '.png'))
    os.remove(os.path.join(path + img))


问:
Can I use data query in ejs inside html tag
```<code>  <% tag.forEach(function(tag) { %>
    <div class="badge bg-primary" style="color: <%=tag.fontcolor%>"><%= tag.name %>
    <button class="deleteTag" data-id="<%=tag.id%>">X</button></div>
  <% }) %>
</code>```

I want to use tag.fontcolor for div style color
but I have problem which appears in this next image:

property value expectedcss(css-propertyvalueexpected)

If you can give me a hint on how to solve this problem, that would be grateful.

答: in EJS templating, for what is not text (attributes, class, ...), use the tag <%- instead of <%=

Body:
  <% tag.forEach(function(tag) { %>
    <div class="badge bg-primary" style="color: <%=tag.fontcolor%>"><%= tag.name %>
    <button class="deleteTag" data-id="<%=tag.id%>">X</button>

  <% }) %>

I want to use tag.fontcolor for div style color
but I have problem which appears in this next image:

property value expectedcss(css-propertyvalueexpected)

If you can give me a hint on how to solve this problem, that would be grateful.