问:
Wordpress remove Robots Meta Tag noindex
were experiencing a strange issue with a wordpress sites meta robots tag. All pages have the following meta tag and we cant seem to remove it

```<code><meta name="robots" content="noindex,follow"/>
</code>```

We have unchecked "Discourage search engines from indexing this site" in Settings > Reading > Search Engine Visibility but it does nothing.

We are using the Yoast SEO plugin but even when this is disabled the   still remains. In fact, we have tried disabling all plugins to check nothing was interfering with it.

We have setup our Robots.txt file as follows:

```<code>User-agent: *
Disallow:
Sitemap: http://speysidedistillery.co.uk/sitemap.xml
</code>```

Im not sure if the Robots.txt takes precedent over the robots meta tag or not and there doesn't seem to be a definitive answer, as far as i can gather the most restrictive one will take precedent i.e in our case the meta tag.

This is mainly giving us issues with our google listing with the warning "A description for this result is not available because of this site's robots.txt" appearing instead of our sites description.

If worse comes to worst we can edit the wp_no_robots function in wp-includes/general-templates.php but would prefer to resolve this without editing the wp core files.

Any light anyone could shone on this would be great as we are at a loss, cheers

The site can be found at http://speysidedistillery.co.uk/

答:
How to Remove WordPress Robots Meta Tag noindex, nofollow

We will show you how to remove meta name=’robots’ content=’noindex nofollow’ in WordPress using replace some code inside the admin panel, no plugin request.

Step 1 – Log into your cPanel

Well, you log inside the public_html directory, now you find a folder, name wp-includes, double click to open this folder. At the same time, there are so many folders and files, take a breath, and simply click to your keyboard Ctrl+f and type general-template.php.

Step 2 – Edit general-template.php File

Find this code inside general-template.php

```<code>function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='noindex,follow' />\n";
    return;
}

echo "<meta name='robots' content='noindex,nofollow' />\n";
</code>```

}

Replace first with this code:

```<code>function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='index,follow' />\n";
    return;
}
echo "<meta name='robots' content='index,follow' />\n";
</code>```

}

2 – Find this second code same file general-template.php:

This

```<code>function wp_sensitive_page_meta() {
?>
<meta name='robots' content='noindex,noarchive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php
</code>```

}

Replace to

```<code>function wp_sensitive_page_meta() {
?>
<meta name='robots' content='index,archive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php
</code>```

}

Once that is complete, go back to the website check, change into Search Console, resubmit the URL you tried earlier. The URL inspection report should be void of all warnings and error messages, at least ones related to indexing and crawl ability, and you’ll be able to “Request Indexing,”.

I found a solution that worked 100% Read Full Details here

Body:
were experiencing a strange issue with a wordpress sites meta robots tag. All pages have the following meta tag and we cant seem to remove it

<meta name="robots" content="noindex,follow"/>

We have unchecked "Discourage search engines from indexing this site" in Settings > Reading > Search Engine Visibility but it does nothing.

We are using the Yoast SEO plugin but even when this is disabled the   still remains. In fact, we have tried disabling all plugins to check nothing was interfering with it.

We have setup our Robots.txt file as follows:

User-agent: *
Disallow:
Sitemap: http://speysidedistillery.co.uk/sitemap.xml

Im not sure if the Robots.txt takes precedent over the robots meta tag or not and there doesn't seem to be a definitive answer, as far as i can gather the most restrictive one will take precedent i.e in our case the meta tag.

This is mainly giving us issues with our google listing with the warning "A description for this result is not available because of this site's robots.txt" appearing instead of our sites description.

If worse comes to worst we can edit the wp_no_robots function in wp-includes/general-templates.php but would prefer to resolve this without editing the wp core files.

Any light anyone could shone on this would be great as we are at a loss, cheers

The site can be found at http://speysidedistillery.co.uk/

Body:
How to Remove WordPress Robots Meta Tag noindex, nofollow

We will show you how to remove meta name=’robots’ content=’noindex nofollow’ in WordPress using replace some code inside the admin panel, no plugin request.

Step 1 – Log into your cPanel

Well, you log inside the public_html directory, now you find a folder, name wp-includes, double click to open this folder. At the same time, there are so many folders and files, take a breath, and simply click to your keyboard Ctrl+f and type general-template.php.

Step 2 – Edit general-template.php File

Find this code inside general-template.php

function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='noindex,follow' />\n";
    return;
}

echo "<meta name='robots' content='noindex,nofollow' />\n";

}

Replace first with this code:

function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='index,follow' />\n";
    return;
}
echo "<meta name='robots' content='index,follow' />\n";

}

2 – Find this second code same file general-template.php:

This

function wp_sensitive_page_meta() {
?>
<meta name='robots' content='noindex,noarchive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php

}

Replace to

function wp_sensitive_page_meta() {
?>
<meta name='robots' content='index,archive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php

}

Once that is complete, go back to the website check, change into Search Console, resubmit the URL you tried earlier. The URL inspection report should be void of all warnings and error messages, at least ones related to indexing and crawl ability, and you’ll be able to “Request Indexing,”.

I found a solution that worked 100% Read Full Details here


来源: stackexchange

问:
How to convert this for loop C# code to Linq or make the process time faster?
Convert this for loop C# code to Linq or make the process time faster

```<code>List<List<Array_Group>> array_Group = new List<List<Array_Group>>();
array_Group.Add(new List<Array_Group>());
object previosSelecter = null;

for (int i = 0; i < array_count; i++)
{
    Type Group = typeof(Array_Group);
    var current = after_Rounded.ElementAt(i);

    Type type = current.GetType();

    PropertyInfo prop = Group.GetProperty("FD_T_Act_");

    object currentSelector = prop.GetValue(current);
    if (previosSelecter == null)
    {
        array_Group.LastOrDefault().Add(current);
    }
    else
        if (currentSelector.Equals(previosSelecter))
        {
            array_Group.LastOrDefault().Add(current);
        }
        else
        {
            array_Group.Add(new List<Array_Group>() { current });
        }
    previosSelecter = currentSelector;
}
</code>```

The execution time takes very long time due to the huge data that needs to be processed.
How can I make it more simpler and faster execution?

答:
Try this:

```<code>using System.Linq;
using System.Collections.Generic;

var array_Group = after_Rounded.GroupBy(x => (x as Array_Group)?.FD_T_Act_);
</code>```

This will produce a System.Collections.Generic.IEnumerable<System.Linq.IGrouping<string, T>> where T is whatever is inside your after_Rounded.

ContentLicense: CC BY-SA 4.0

Body:
Convert this for loop C# code to Linq or make the process time faster

List<List<Array_Group>> array_Group = new List<List<Array_Group>>();
array_Group.Add(new List<Array_Group>());
object previosSelecter = null;

for (int i = 0; i < array_count; i++)
{
    Type Group = typeof(Array_Group);
    var current = after_Rounded.ElementAt(i);

    Type type = current.GetType();

    PropertyInfo prop = Group.GetProperty("FD_T_Act_");

    object currentSelector = prop.GetValue(current);
    if (previosSelecter == null)
    {
        array_Group.LastOrDefault().Add(current);
    }
    else
        if (currentSelector.Equals(previosSelecter))
        {
            array_Group.LastOrDefault().Add(current);
        }
        else
        {
            array_Group.Add(new List<Array_Group>() { current });
        }
    previosSelecter = currentSelector;
}

The execution time takes very long time due to the huge data that needs to be processed.
How can I make it more simpler and faster execution?

Body:
Try this:

using System.Linq;
using System.Collections.Generic;

var array_Group = after_Rounded.GroupBy(x => (x as Array_Group)?.FD_T_Act_);

This will produce a System.Collections.Generic.IEnumerable<System.Linq.IGrouping<string, T>> where T is whatever is inside your after_Rounded.


问:
Spring Security: How to get the initial target url
I am using the spring security to restricted urls. I am trying to provide signup and login page, on the same page.

On login spring security transfers to the restricted page. However i am trying to pass the target url to the signup process, so that after signup we can redirect to the restricted page.

How to get the actual URL that user was redirected from.

Any Ideas?

答:
```<code>DefaultSavedRequest savedRequest = (DefaultSavedRequest)session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");

String requestURL = savedRequest.getRequestURL();   // URL <br>
String requestURI = savedRequest.getRequestURI();   // URI
</code>```

ContentLicense: CC BY-SA 2.5


问:
how can i check the presence of sound in a video using a script
Hi
i am working for a broadcasting company, we have a PC with TV tuner Card (windows xp), this PC is recording channel TV 24h/24 no stop.
the output are video files "wmv" each one has a duration of an hour.
The video files are copied automatically to a NAS, then final users works on them.

the problem is sometimes, there is no signal in the antenna, or there is just video without sound, then the video files recorded are no more exploitables.

i am searching for a way to write a script that can check a file after being recorded before being transfered to the NAS, the script must check the presence of the sound (perhaps volume statistics) to be sure the sounds exists really, same thing of video.
(for video i am using a script checking the size of the file)

is there anyway to do so ?
is there any command line in vlc, mplayer, media player classic, ..... ?

Thanks

答: Perhaps you can use ffmpeg (http://linux.byexamples.com/archives/229/extract-audio-from-video-or-online-stream/) to dump the audio to a seperate file in a compressed state, and the filesize can give you some information about the amount of data?</p>

ContentLicense: CC BY-SA 3.0


问:
Jacoco multimodule with integration tests - REST Controllers not covered
I have mutliple layers on an application (web, business...).
I want to publish coverage of each test (unit and integration tests) on sonar by using jacoco-maven-plugin.

In the application, all the code is covered by unit and integration tests, and the pom.xml is correct but I have this problem:

The controllers code is not considered to be covered by the tests in jacoco reports, unlike the services (business layer) called by these controllers !

Example :

FunctionalityAService.java covered by FunctionalityAServiceTest.java (unit test)

FunctionalityBService.java covered, FunctionalityBController.java not covered by FunctionalityBControllerIT.java (integration test)

You can find an example here : https://github.com/salimchami/maven-jacoco-multimodule-sonar

How to include coverage on Controllers ?

EDIT 1 :

I don't understand why it's mandatory to create a module only to aggragate results... Why We can't do this in the root module (jacoco-aggregate directory in the root module) ?

EDIT 2 :

It's a spring boot project and I'm using spring mockMvc in the integration tests.
So, the controllers are not called by an instantiation.

答:
I found a solution :

Root pom :

<modules>
    <module>dao</module>
    <module>domain</module>
    <module>web</module>
    <module>coverage</module>
</modules>

<properties>
    <project.xmlReportPaths>coverage/target/site/jacoco-aggregate/jacoco.xml</project.xmlReportPaths>
</properties>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
            </plugin>
            <plugin>
                <groupId>org.sonarsource.scanner.maven</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>3.7.0.1746</version>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.5</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>3.0.0-M4</version>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.sonarsource.scanner.maven</groupId>
            <artifactId>sonar-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>**/*IT.java</exclude>
                </excludes>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
                <execution>
                    <id>report</id>
                    <goals>
                        <goal>report</goal>
                    </goals>
                </execution>
                <execution>
                    <id>report-aggregate</id>
                    <goals>
                        <goal>report-aggregate</goal>
                    </goals>
                    <phase>verify</phase>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>its</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <configuration>
                        <includes>
                            <include>**/*IT.java</include>
                        </includes>
                    </configuration>
                    <executions>
                        <execution>
                            <id>integration-test</id>
                            <goals>
                                <goal>integration-test</goal>
                                <goal>verify</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>it-agent</id>
                            <goals>
                                <goal>prepare-agent-integration</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>it-report</id>
                            <goals>
                                <goal>report-integration</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
```
<p>coverage module pom :</p>
<pre class="lang-xml prettyprint-override"><code><properties>
    <sonar.coverage.jacoco.xmlReportPaths>${project.basedir}/../${project.xmlReportPaths}
        </sonar.coverage.jacoco.xmlReportPaths>
</properties>

<dependencies>
<!-- list of all sub modules dependencies -->
</dependencies>
</code>```

example of sub module :

<properties>
    <sonar.coverage.jacoco.xmlReportPaths>${project.basedir}/../${project.xmlReportPaths}</sonar.coverage.jacoco.xmlReportPaths>
</properties>
```

Body:
I found a solution :

Root pom :

<modules>
    <module>dao</module>
    <module>domain</module>
    <module>web</module>
    <module>coverage</module>
</modules>

<properties>
    <project.xmlReportPaths>coverage/target/site/jacoco-aggregate/jacoco.xml</project.xmlReportPaths>
</properties>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
            </plugin>
            <plugin>
                <groupId>org.sonarsource.scanner.maven</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>3.7.0.1746</version>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.5</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>3.0.0-M4</version>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.sonarsource.scanner.maven</groupId>
            <artifactId>sonar-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>**/*IT.java</exclude>
                </excludes>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
                <execution>
                    <id>report</id>
                    <goals>
                        <goal>report</goal>
                    </goals>
                </execution>
                <execution>
                    <id>report-aggregate</id>
                    <goals>
                        <goal>report-aggregate</goal>
                    </goals>
                    <phase>verify</phase>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>its</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <configuration>
                        <includes>
                            <include>**/*IT.java</include>
                        </includes>
                    </configuration>
                    <executions>
                        <execution>
                            <id>integration-test</id>
                            <goals>
                                <goal>integration-test</goal>
                                <goal>verify</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>it-agent</id>
                            <goals>
                                <goal>prepare-agent-integration</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>it-report</id>
                            <goals>
                                <goal>report-integration</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

coverage module pom :

<properties>
    <sonar.coverage.jacoco.xmlReportPaths>${project.basedir}/../${project.xmlReportPaths}
        </sonar.coverage.jacoco.xmlReportPaths>
</properties>

<dependencies>
<!-- list of all sub modules dependencies -->
</dependencies>

example of sub module :

<properties>
    <sonar.coverage.jacoco.xmlReportPaths>${project.basedir}/../${project.xmlReportPaths}</sonar.coverage.jacoco.xmlReportPaths>
</properties>


问:
Supporting Native OS APIs from Blazor WebAssembly
I have an IPP/CUPS library that allows local printing, can i integrate same library from Blazor Web Assembly running in a browser sandbox on Windows?
In Chrome or Chromebook, it has been supported using Browser extension.
Any feedback is appreciated.
Thanks</p>

答: Blazor is a web page. What you can do with JS in the browser, you can do from a blazor app. If you have an extension that lets you access the OS (hopefully, a calculated security risk), you can call these methods through the JS Interop now


问:
I couldn't able to run my MVC.net project in my Visual Studio Community 2017
Whenever i try to run my any .net project from mine Microsoft Visual Studio Community 2017. It is suddenly stop and throw me an error.The program '[191420] iisexpress.exe' has exited with code 0 (0x0)."

In Browser:
Click here to see an error occur in browser

In VS 2017:
Click here to see an error occur in VS 2017

Note:

After Drupal 8 setup in to my pc, I start getting this error.

I am happy to see the reply on this issue.

Thanks :)

答:
Please refer this LINK

Several method below might be helpful:

1) Check your solution folder for a hidden ".vs" folder with a "config" sub-folder. If that folder exists and it has it's own applicationhost.config file you need to either rename (or delete) that file or edit it and make sure the website(s) configured inside match the ASP.NET web app(s) in your solution that you are trying to debug. Hope this helps.

2) Solution Explorer in Visual Studio, right click on the web project, chose properties and then navigated to the "web" tab. From there I changed the Project URL to another port number.
For example, if it was http://localhost:1052 - I changed it to  http://localhost:4356.

3)

If your machine is 64bit, please go to Tools-> options -> projects and solutions:

Please let me know which one shown above could help.


问:
How can I loop over sub folders in Assets folder?
```<code>string selectedPath = GetPath();
var subFolders = AssetDatabase.GetSubFolders(selectedPath);
List<string> paths = new List<string>();
foreach(string path in subFolders)
{
    paths.Add(path);
}
</code>```

For example the subFolders is Assets/My Folder
but under My Folder there are many more subfolders.

AssetDatabase.GetSubFolders don't make recursive it's getting the first sub folder only.
I want to get all the sub folders recursive.

I tried :

List paths = new List();
foreach(string path in subFolders)
{
    paths.Add(path);
}

but it's still giving me only the first sub folder.

This is how I'm getting the selected path name in the Assets :

[MenuItem("Assets/Get Path")]
private static string GetClickedDirFullPath()
{
    string clickedAssetGuid = Selection.assetGUIDs[0];
    string clickedPath = AssetDatabase.GUIDToAssetPath(clickedAssetGuid);
    string clickedPathFull = Path.Combine(Directory.GetCurrentDirectory(), clickedPath);

    FileAttributes attr = File.GetAttributes(clickedPathFull);
    return attr.HasFlag(FileAttributes.Directory) ? clickedPathFull : Path.GetDirectoryName(clickedPathFull);
}

[MenuItem("Assets/Get Path")]
private static string GetPath()
{
    string path = GetClickedDirFullPath();
    int index = path.IndexOf("Assets");
    string result = path.Substring(index);

    return result;
}
```

答:
You could simply make it recursive using List<T>.AddRange like

```<code>private static string[] GetSubFoldersRecursive(string root)
{
    var paths = new List<string>();

    // If there are no further subfolders then AssetDatabase.GetSubFolders returns
    // an empty array => foreach will not be executed
    // This is the exit point for the recursion
    foreach (var path in AssetDatabase.GetSubFolders(root))
    {
        // add this subfolder itself
        paths.Add(path);

        // If this has no further subfolders then simply no new elements are added
        paths.AddRange(GetSubFoldersRecursive(path));
    }

    return paths.ToArray();
}
</code>```

So e.g.

```<code>[ContextMenu("Test")]
private void Test()
{
    var sb = new StringBuilder();

    var folders = SubFolders("Assets");

    if(folders.Length > 0)
    {
        foreach (var folder in SubFolders("Assets"))
        {
            sb.Append(folder).Append('\n');
        }
    }
    else
    {
        sb.Append(" << The given path has no subfolders! >>");
    }

    Debug.Log(sb.ToString());
}
</code>```

will print out the entire project's folder structure.

For

I get

```<code>Assets/Example 1
Assets/Example 1/SubFolder A
Assets/Example 1/SubFolder B
Assets/Example 1/SubFolder C
Assets/Example 2
Assets/Example 2/SubFolder A
Assets/Example 2/SubFolder A/SubSubFolder A
</code>```

So in your case it would be

```<code>string selectedPath = GetPath();
var folders = SubFolders(selectedPath);
foreach(var path in folders)
{
    ...
}
</code>```

Body:
string selectedPath = GetPath();
var subFolders = AssetDatabase.GetSubFolders(selectedPath);
List<string> paths = new List<string>();
foreach(string path in subFolders)
{
    paths.Add(path);
}

For example the subFolders is Assets/My Folder
but under My Folder there are many more subfolders.

AssetDatabase.GetSubFolders don't make recursive it's getting the first sub folder only.
I want to get all the sub folders recursive.

I tried :

List paths = new List();
foreach(string path in subFolders)
{
    paths.Add(path);
}

but it's still giving me only the first sub folder.

This is how I'm getting the selected path name in the Assets :

[MenuItem("Assets/Get Path")]
private static string GetClickedDirFullPath()
{
    string clickedAssetGuid = Selection.assetGUIDs[0];
    string clickedPath = AssetDatabase.GUIDToAssetPath(clickedAssetGuid);
    string clickedPathFull = Path.Combine(Directory.GetCurrentDirectory(), clickedPath);

    FileAttributes attr = File.GetAttributes(clickedPathFull);
    return attr.HasFlag(FileAttributes.Directory) ? clickedPathFull : Path.GetDirectoryName(clickedPathFull);
}

[MenuItem("Assets/Get Path")]
private static string GetPath()
{
    string path = GetClickedDirFullPath();
    int index = path.IndexOf("Assets");
    string result = path.Substring(index);

    return result;
}

Body:
You could simply make it recursive using List<T>.AddRange like

private static string[] GetSubFoldersRecursive(string root)
{
    var paths = new List<string>();

    // If there are no further subfolders then AssetDatabase.GetSubFolders returns
    // an empty array => foreach will not be executed
    // This is the exit point for the recursion
    foreach (var path in AssetDatabase.GetSubFolders(root))
    {
        // add this subfolder itself
        paths.Add(path);

        // If this has no further subfolders then simply no new elements are added
        paths.AddRange(GetSubFoldersRecursive(path));
    }

    return paths.ToArray();
}

So e.g.

[ContextMenu("Test")]
private void Test()
{
    var sb = new StringBuilder();

    var folders = SubFolders("Assets");

    if(folders.Length > 0)
    {
        foreach (var folder in SubFolders("Assets"))
        {
            sb.Append(folder).Append('\n');
        }
    }
    else
    {
        sb.Append(" << The given path has no subfolders! >>");
    }

    Debug.Log(sb.ToString());
}

will print out the entire project's folder structure.

For

I get

Assets/Example 1
Assets/Example 1/SubFolder A
Assets/Example 1/SubFolder B
Assets/Example 1/SubFolder C
Assets/Example 2
Assets/Example 2/SubFolder A
Assets/Example 2/SubFolder A/SubSubFolder A

So in your case it would be

string selectedPath = GetPath();
var folders = SubFolders(selectedPath);
foreach(var path in folders)
{
    ...
}


问:
Count Number of Swaps in Merge Sort (Java)
Im trying to find the number of times the elements in an array are swapped to sort the array. The program uses recursion and merge sort. After trying many times by putting a counter in what i believe where the sort happens i get what looks like to be randomly generated numbers as the number of swaps.

Here is the code. I just want a number that shows the correct amount of swaps rather than the random numbers.

```<code>    /**
 *
 * @author Frank Stalteri
 *
 */
public class mergeExample {
    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        int [] list = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};
        /**
         * performs merge sort
         */
        mergeSort(list);
        /**
         * prints array to screen
         */
        printArray(list);
    }
    /**
     *
     * @param list
     */
    public static void mergeSort(int [] list) {
        if (list.length > 1) {
            /**
             * merge first half of array
             */
            int [] firstHalf = new int[list.length / 2];
            System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
            mergeSort(firstHalf);
            /**
             * merge second part of array
             */
            int secondHalfLength = list.length - list.length / 2;
            int [] secondHalf = new int[secondHalfLength];
            System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);
            mergeSort(secondHalf);
            /**
             * put the sorted parts together
             */
            merge(firstHalf, secondHalf, list);
        }
    }
    /**
     *
     * @param list1
     * @param list2
     * @param temp
     * @return
     */
    public static void merge(int [] list1, int [] list2, int [] temp) {
        int current1 = 0;   //current index in list1
        int current2 = 0;   //current index in list2
        int current3 = 0;   //current index in temp

        while (current1 < list1.length && current2 < list2.length) {
            if (list1[current1] < list2[current2]) {
                temp[current3++] = list1[current1++];
            }
            else {
                temp[current3++] = list2[current2++];
            }
        }
        while (current1 < list1.length) {
            temp[current3++] = list1[current1++];

        }
        while (current2 < list2.length) {
            temp[current3++] = list2[current2++];
        }
    }
    /**
     *
     * @param list
     */
    public static void printArray(int [] list) {
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }
    }
}
</code>```

This is the output

```<code>1
1
1
2
0
0
1
2
5
-2 1 2 2 3 3 5 6 12 14
</code>```

答:
You'd have to add something like a count variable outside your merge function, for example as a static int in your class:

public class MergeExample {
    static int mergeCount = 0;
    // ...
}
```

and whenever you do a swap in your code in your mergeSort function you'd have to increment MergeExample.mergeCount by 1. In the end, you will have the number of swaps performed in that variable.

Body:
Im trying to find the number of times the elements in an array are swapped to sort the array. The program uses recursion and merge sort. After trying many times by putting a counter in what i believe where the sort happens i get what looks like to be randomly generated numbers as the number of swaps.

Here is the code. I just want a number that shows the correct amount of swaps rather than the random numbers.

    /**
 *
 * @author Frank Stalteri
 *
 */
public class mergeExample {
    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        int [] list = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};
        /**
         * performs merge sort
         */
        mergeSort(list);
        /**
         * prints array to screen
         */
        printArray(list);
    }
    /**
     *
     * @param list
     */
    public static void mergeSort(int [] list) {
        if (list.length > 1) {
            /**
             * merge first half of array
             */
            int [] firstHalf = new int[list.length / 2];
            System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
            mergeSort(firstHalf);
            /**
             * merge second part of array
             */
            int secondHalfLength = list.length - list.length / 2;
            int [] secondHalf = new int[secondHalfLength];
            System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);
            mergeSort(secondHalf);
            /**
             * put the sorted parts together
             */
            merge(firstHalf, secondHalf, list);
        }
    }
    /**
     *
     * @param list1
     * @param list2
     * @param temp
     * @return
     */
    public static void merge(int [] list1, int [] list2, int [] temp) {
        int current1 = 0;   //current index in list1
        int current2 = 0;   //current index in list2
        int current3 = 0;   //current index in temp

        while (current1 < list1.length && current2 < list2.length) {
            if (list1[current1] < list2[current2]) {
                temp[current3++] = list1[current1++];
            }
            else {
                temp[current3++] = list2[current2++];
            }
        }
        while (current1 < list1.length) {
            temp[current3++] = list1[current1++];

        }
        while (current2 < list2.length) {
            temp[current3++] = list2[current2++];
        }
    }
    /**
     *
     * @param list
     */
    public static void printArray(int [] list) {
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }
    }
}

This is the output

1
1
1
2
0
0
1
2
5
-2 1 2 2 3 3 5 6 12 14

Body:
You'd have to add something like a count variable outside your merge function, for example as a static int in your class:

public class MergeExample {
    static int mergeCount = 0;
    // ...
}

and whenever you do a swap in your code in your mergeSort function you'd have to increment MergeExample.mergeCount by 1. In the end, you will have the number of swaps performed in that variable.


问:
Is it meaningful to verifyText() on an element that has just had type() executed on it?
I'm curious about whether the following functional test is possible. I'm working with PHPUnit_Extensions_SeleniumTestCase with Selenium-RC here, but the principle (I think) should apply everywhere.

Suppose I execute the following command on a particular div:

```<code>function testInput() {
    $locator = $this->get_magic_locator(); // for the sake of abstraction
    $this->type( $locator, "Beatles" ); // Selenium API call
    $this->verifyText( $locator, "Beatles" ); // Selenium API call
}
</code>```

Conceptually, I feel that this test should work. I'm entering data into a particular field, and I simply want to verify that the text now exists as entered.

However, the results of my test (the verifyText assertion fails) suggest that the content of the $locator element are empty, even after input.

```<code>There was 1 failure:

1) test::testInput
Failed asserting that <string:> matches PCRE pattern "/Beatles/".`
</code>```

Has anyone else tried anything like this? Should it work? Am I making a simple mistake?

答:
To answer your initial question ("Is it meaningful ..."), well, maybe.  What you're testing at that point is the browser's ability to respond to keystrokes, which would be sort of lame.  Unless you've got some JavaScript code wired to some of the field's properties, in which case it might be sort of important.

Standard programmer's answer - "It depends".

Body:
I'm curious about whether the following functional test is possible. I'm working with PHPUnit_Extensions_SeleniumTestCase with Selenium-RC here, but the principle (I think) should apply everywhere.

Suppose I execute the following command on a particular div:

function testInput() {
    $locator = $this->get_magic_locator(); // for the sake of abstraction
    $this->type( $locator, "Beatles" ); // Selenium API call
    $this->verifyText( $locator, "Beatles" ); // Selenium API call
}

Conceptually, I feel that this test should work. I'm entering data into a particular field, and I simply want to verify that the text now exists as entered.

However, the results of my test (the verifyText assertion fails) suggest that the content of the $locator element are empty, even after input.

There was 1 failure:

1) test::testInput
Failed asserting that <string:> matches PCRE pattern "/Beatles/".`

Has anyone else tried anything like this? Should it work? Am I making a simple mistake?


问:
Install Android App Bundle on device
I built my project using the new Android App Bundle format. With APK files, I can download the APK to my device, open it, and immediately install the app. I downloaded my app as a bundle (.aab format) and my Nexus 5X running Android 8.1 can't open the file. Is there any way to install AABs on devices in the same convenient manner as APKs? </p>

答:
If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.

Go to Edit Configurations

Select the Deploy dropdown and change it from "Default apk" to "APK from app bundle".

Apply the changes and then run it on the device connected. Build time will increase after making this change.

This will install an apk directly on the device connected from the aab.

Title: Install Android App Bundle on device


问:
How do I get the word density of my text using vanilla JavaScript?
This is where I enter a text:

Upon clicking on the COUNT button, it goes to this page:

My text and word count got displayed. But how do I get the word density of this text using vanilla JavaScript, and actually display it on this page?

Here's my HTML:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Word Counter</title>
    </head>
    <body>
        <div id="input-page">
            <h1>Word Counter</h1>
            <form action="">
                <textarea id="text" type="text" rows="22" cols="60"></textarea>
                <br />
            </form>
            <button onclick="displayText()">COUNT</button>
        </div>

        <div id="count-page" style="display: none;">
            <h1>Your Text:</h1>
            <p id="display-text"></p>
            <div id="word-count"></div>
            <div id="word-density">
                <h1>Word Density:</h1>
            </div>
        </div>
    </body>
    <script src="app.js"></script>
</html>
</code>```

JavaScript:

```<code>const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  const text = document.getElementById("text");
  const textValue = text.value;

  if (text.value !== "") { // normal flow will continue if the text-area is not empty
    inputPage.style.display = "none";
    document.getElementById("display-text").innerText = textValue;
    countPage.style.display = "block";
  } else { // if the text-area is empty, it will issue a warning.
    alert("Please enter some text first.")
  }

  const countWords = (str) => {
    return str.split(" ").length;
  };
  const wordCount = (countWords(textValue));

  const renderWordCount = () => {
    const wordCountDiv = document.getElementById("word-count");
    wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
  };

  renderWordCount();
};
</code>```

答:
For getting the word density like @SimoneRossaini told, simply use a list and save how many times you found each word. This ends up like this for example:

I modified your code and added the word density.

const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  const text = document.getElementById("text");
  const textValue = text.value;

  if (text.value !== "") { // normal flow will continue if the text-area is not empty
    inputPage.style.display = "none";
    document.getElementById("display-text").innerText = textValue;
    countPage.style.display = "block";
  } else { // if the text-area is empty, it will issue a warning.
    alert("Please enter some text first.")
  }

  const countWords = (str) => {
    return str.split(" ").length;
  };
  const wordCount = (countWords(textValue));

  const renderWordCount = () => {
    const wordCountDiv = document.getElementById("word-count");
    wordCountDiv.innerHTML = "
 Words Counted: " + wordCount + "
";
  };

  const getWordDensity = (str) => {
    let wordList = {};
    str.split(/[\s\.,]+/).forEach(word => {
      if(typeof wordList[word] == "undefined"){
        wordList[word] = 1;
      }
      else{
        wordList[word]++;
      }
    });
    return wordList;
  };
  const wordDensity = (getWordDensity(textValue));

  const renderWordDensity = () => {
    const wordDensityDiv = document.getElementById("word-density");

    let table = "
";
    for(let word in wordDensity){
      table += "
" + word + "	" + wordDensity[word] + "
";
    }
    table += "
";

    wordDensityDiv.innerHTML = "
 Word Density:
" + table;
  };

  renderWordCount();
  renderWordDensity();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <title>Word Counter</title>
    </head>
    <body>
        <div id="input-page">
            <h1>Word Counter</h1>
            <form action="">
                <textarea id="text" type="text" rows="22" cols="60"></textarea>
                <br />
            </form>
            <button onclick="displayText()">COUNT</button>
        </div>

        <div id="count-page" style="display: none;">
            <h1>Your Text:</h1>
            <p id="display-text"></p>
            <div id="word-count"></div>
            <div id="word-density"></div>
        </div>
    </body>
    <script src="app.js"></script>
</html></code>```

Body:
This is where I enter a text:

Upon clicking on the COUNT button, it goes to this page:

My text and word count got displayed. But how do I get the word density of this text using vanilla JavaScript, and actually display it on this page?

Here's my HTML:

<!DOCTYPE html>

        <title>Word Counter</title>

Word Counter

            <form action="">
                <textarea id="text" type="text" rows="22" cols="60"></textarea>

            </form>
            <button onclick="displayText()">COUNT</button>

Your Text:

Word Density:

JavaScript:

const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  const text = document.getElementById("text");
  const textValue = text.value;

  if (text.value !== "") { // normal flow will continue if the text-area is not empty
    inputPage.style.display = "none";
    document.getElementById("display-text").innerText = textValue;
    countPage.style.display = "block";
  } else { // if the text-area is empty, it will issue a warning.
    alert("Please enter some text first.")
  }

  const countWords = (str) => {
    return str.split(" ").length;
  };
  const wordCount = (countWords(textValue));

  const renderWordCount = () => {
    const wordCountDiv = document.getElementById("word-count");
    wordCountDiv.innerHTML = "
 Words Counted: " + wordCount + "
";
  };

  renderWordCount();
};

Body:
For getting the word density like @SimoneRossaini told, simply use a list and save how many times you found each word. This ends up like this for example:

I modified your code and added the word density.

const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  const text = document.getElementById("text");
  const textValue = text.value;

  if (text.value !== "") { // normal flow will continue if the text-area is not empty
    inputPage.style.display = "none";
    document.getElementById("display-text").innerText = textValue;
    countPage.style.display = "block";
  } else { // if the text-area is empty, it will issue a warning.
    alert("Please enter some text first.")
  }

  const countWords = (str) => {
    return str.split(" ").length;
  };
  const wordCount = (countWords(textValue));

  const renderWordCount = () => {
    const wordCountDiv = document.getElementById("word-count");
    wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
  };

  const getWordDensity = (str) => {
    let wordList = {};
    str.split(/[\s\.,]+/).forEach(word => {
      if(typeof wordList[word] == "undefined"){
        wordList[word] = 1;
      }
      else{
        wordList[word]++;
      }
    });
    return wordList;
  };
  const wordDensity = (getWordDensity(textValue));

  const renderWordDensity = () => {
    const wordDensityDiv = document.getElementById("word-density");

    let table = "<table>";
    for(let word in wordDensity){
      table += "<tr><td>" + word + "</td><td>" + wordDensity[word] + "</td></tr>";
    }
    table += "</table>";

    wordDensityDiv.innerHTML = "<h1> Word Density: </h1>" + table;
  };

  renderWordCount();
  renderWordDensity();
};

<!DOCTYPE html>
<html>
    <head>
        <title>Word Counter</title>
    </head>
    <body>
        <div id="input-page">
            <h1>Word Counter</h1>
            <form action="">
                <textarea id="text" type="text" rows="22" cols="60"></textarea>
                <br />
            </form>
            <button onclick="displayText()">COUNT</button>
        </div>

        <div id="count-page" style="display: none;">
            <h1>Your Text:</h1>
            <p id="display-text"></p>
            <div id="word-count"></div>
            <div id="word-density"></div>
        </div>
    </body>
    <script src="app.js"></script>
</html>


问:
django Pagination with Class-Based Views
How do i create pagination in Django ListView? and i just want that per page have 5 records only

this is my views.py

```<code>class ArticleListView(ListView):
    model = StudentsEnrollmentRecord
    template_name = 'Homepage/studentsenrollmentrecord_list.html'
    paginate_by = 5
    queryset = StudentsEnrollmentRecord.objects.all()
    def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       return(context)
</code>```

and this is my html search_and_page.html

```<code>    <table id="customers">
        <tr>
            <th>Username</th>
            <th>Firstname</th>
            <th>Email</th>
        </tr>
        {% for article in object_list %}
        <tr  id="myAnchor">
            <td class="grpTextBox">{{ article.username }}</td>
            <td class="grpTextBox">{{ article.Firstname }}</td>
            <td class="grpTextBox">{{article.Email}}</td>
        </tr>
        {% endfor %}
    </table>
</code>```

in web view

答:
I think you miss out this

check out this documentation https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html

```<code><center>
    {% if is_paginated %}
  <ul class="pagination">
    {% if page_obj.has_previous %}
      <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}">«</a></li>
    {% else %}
      <li class="disabled page-item"><span>«</span></li>
    {% endif %}
    {% for i in paginator.page_range %}
      {% if page_obj.number == i %}
        <li class="active page-item"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
      {% else %}
        <li class="page-item"><a href="?page={{ i }}">{{ i }}</a></li>
      {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
      <li><a href="?page={{ page_obj.next_page_number }}">»</a></li>
    {% else %}
      <li class="disabled page-item"><span>»</span></li>
    {% endif %}
  </ul>
{% endif %}
</center>
</code>```

Body:
How do i create pagination in Django ListView? and i just want that per page have 5 records only

this is my views.py

class ArticleListView(ListView):
    model = StudentsEnrollmentRecord
    template_name = 'Homepage/studentsenrollmentrecord_list.html'
    paginate_by = 5
    queryset = StudentsEnrollmentRecord.objects.all()
    def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       return(context)

and this is my html search_and_page.html

            Username
            Firstname
            Email

        {% for article in object_list %}

            {{ article.username }}
            {{ article.Firstname }}
            {{article.Email}}

        {% endfor %}

in web view

Body:
I think you miss out this

check out this documentation https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html

<center>
    {% if is_paginated %}
  <ul class="pagination">
    {% if page_obj.has_previous %}
      <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
    {% else %}
      <li class="disabled page-item"><span>&laquo;</span></li>
    {% endif %}
    {% for i in paginator.page_range %}
      {% if page_obj.number == i %}
        <li class="active page-item"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
      {% else %}
        <li class="page-item"><a href="?page={{ i }}">{{ i }}</a></li>
      {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
      <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li>
    {% else %}
      <li class="disabled page-item"><span>&raquo;</span></li>
    {% endif %}
  </ul>
{% endif %}
</center>


问:
To free the pallets from a wait block with a dynamic event
I would like to free the different amount of pallets sitting in my wait block to the certain time. I don't know how to use the free function in my dynamic event. The database is called lkw76 and my different pallet amounts called amount in my database which are released to the certain date. So I have the wait block where the pallets sit in before they will be released to the time of my database. So I need the function for my dynamic event which release the amount of pallets in my wait block. In main on startup I have following function to connect the dynamic event with my database. In general I don't have java knowledge so I am currently in the process to learn it. Thank you for helping.

```<code>List< Tuple > amounts =selectFrom( lkw76 ).list();
for( Tuple tup : amounts ) {
    Date today=date();
    Date future=tup.get(lkw76.dates);
    long diff = future.getTime() - today.getTime();
    int amount=tup.get(lkw76.amount);
    create_MyDynamicEvent(diff,MILLISECOND,amount);
}
</code>```

database

dynamic_event

process

答:
You may do it like this in the dynamic event:

```<code>for(int i=min(amount,wait.size());i>0;i--){
   wait.free(wait.get(i-1));
}
</code>```

This implies FIFO and will free the first amount agents that entered the wait block, unless there are less agents in the wait block, in which case it will free all of them

Body:
I would like to free the different amount of pallets sitting in my wait block to the certain time. I don't know how to use the free function in my dynamic event. The database is called lkw76 and my different pallet amounts called amount in my database which are released to the certain date. So I have the wait block where the pallets sit in before they will be released to the time of my database. So I need the function for my dynamic event which release the amount of pallets in my wait block. In main on startup I have following function to connect the dynamic event with my database. In general I don't have java knowledge so I am currently in the process to learn it. Thank you for helping.

List< Tuple > amounts =selectFrom( lkw76 ).list();
for( Tuple tup : amounts ) {
    Date today=date();
    Date future=tup.get(lkw76.dates);
    long diff = future.getTime() - today.getTime();
    int amount=tup.get(lkw76.amount);
    create_MyDynamicEvent(diff,MILLISECOND,amount);
}

database

dynamic_event

process

Body:
You may do it like this in the dynamic event:

for(int i=min(amount,wait.size());i>0;i--){
   wait.free(wait.get(i-1));
}

This implies FIFO and will free the first amount agents that entered the wait block, unless there are less agents in the wait block, in which case it will free all of them


问:
How to distinguish between "using declaration" and "using directive" in C++?
How can I distinguish between "using-declaration" and "using directive" in C++? What are the main differences between "using-declaration" and "using directive"? Could somebody make it clear by giving some simple examples? I would be grateful to have some help with this question.</p>

答:
As description in https://en.cppreference.com/w/cpp/keyword/using

using-directives for namespaces and using-declarations for namespace members

```<code>using namespace std; // using-directive
using std::string;   // using-declaration
</code>```

Body:
As description in https://en.cppreference.com/w/cpp/keyword/using

using-directives for namespaces and using-declarations for namespace members

using namespace std; // using-directive
using std::string;   // using-declaration


问:
Framework7 and Android: Icons render in browser but not on device
When I use framework7-icons on the web, they render just fine, but when I launch my project on my Galaxy S8, the name of the icon is displayed instead of the actual icon.

On the web:

On my Galaxy S8:

My code:

```<code><div id="app">
    <div class="page">
        <div class="row">
            <div class="navbar">
                <div class="navbar-inner">
                    <div class="left"><i class="f7-icons size-28">menu</i></div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答: Before copying build folder to cordova, in build/static/Css folder, open the css files and search for  src:url(/static/media/MaterialIcons-Regular.e79bfd88.eot) and replace it with src:url(../media/MaterialIcons-Regular.e79bfd88.eot). This will work for sure.

Body:
When I use framework7-icons on the web, they render just fine, but when I launch my project on my Galaxy S8, the name of the icon is displayed instead of the actual icon.

On the web:

On my Galaxy S8:

My code:

menu


问:
Is it possible to declare a function which takes Win32 event HANDLE as a parameter in idl 3.0 file?
I am trying to author a set of APIs for my customer.

They need a function which takes Win32 event HANDLE as a parameter for them to wait event via WaitForSingleObject().

However, I cannot find the correct data types for this HANDLE type.

Is it possible to use Win32 event HANDLE in idl 3.0 file?

答:
According to Raymond's comment, the MIDL 3.0 doesn't support HANDLE type and he recommended to use Windows Runtime event instead.

I developed Windows Runtime event following Microsoft's instruction.


问:
Randomising background of a div
I'm trying to randomise the background of a div by adding a script into the html. My css sheet linked does not prescribe any background image or colour but has some webkit transition.

I did look for some solution but its not really working -

```<code><div id="maincontent">

        <script type="text/javascript">
            $(document).ready(function() {

            var images =["lockimg1.jpg","lockimg2.jpg","lockimg3.jpg","lockimg4.jpg","lockimg5.jpg","lockimg6.jpg","lockimg7.jpg"];

            $(document.getElementById('maincontent').css({'backgroundimage':'url('+ images[Math.floor(Math.random()*images.length)]+')'});

              )};
        </script>
</code>```

On my css sheet, the "maincontent" div has the following -

```<code>#maincontent{
    padding:20%;
    display:flex;
    width:100vm;
    height:100vh;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    background:url(lockimg2.jpg);
    background-blend-mode: darken;
    background-size:contain;
      opacity:0.98;
    -webkit-transition: background ease-in-out 3s, opacity 15s, border 10s;

}

#maincontent:hover{
  opacity:0.98;
background-color:black;

  border:-1px solid black;
}
</code>```

Any help would be deeply appreciated.
Thank you!

答:
I believe you need to define your  tag's "id" attribute.

```<code>(document.**getElementById**('maincontent').
</code>```

But in yout HTML,

```<code><div class="maincontent">
</code>```

Can you add an id to your ?

```<code><div class="maincontent" id="**mainContentID**">
//And change this:
(document.**getElementById**('**mainContentID**').
</code>```

Title: Randomising background of a div

Body:
I'm trying to randomise the background of a div by adding a script into the html. My css sheet linked does not prescribe any background image or colour but has some webkit transition.

I did look for some solution but its not really working -

On my css sheet, the "maincontent" div has the following -

#maincontent{
    padding:20%;
    display:flex;
    width:100vm;
    height:100vh;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    background:url(lockimg2.jpg);
    background-blend-mode: darken;
    background-size:contain;
      opacity:0.98;
    -webkit-transition: background ease-in-out 3s, opacity 15s, border 10s;

}

#maincontent:hover{
  opacity:0.98;
background-color:black;

  border:-1px solid black;
}

Any help would be deeply appreciated.
Thank you!

Body:
I believe you need to define your  tag's "id" attribute.

(document.**getElementById**('maincontent').

But in yout HTML,

<div class="maincontent">

Can you add an id to your ?

<div class="maincontent" id="**mainContentID**">
//And change this:
(document.**getElementById**('**mainContentID**').


问:
EF Core 3.1 using Authentication=Active Directory Integrated
[Update 1]

I could make it work using the following connection string

```<code>Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname
</code>```

and implementing an interceptor as mentioned in this article.

This proves that Azure is correctly configured, and the problem is somewhere in the application (maybe a missing package?).

Anyway, I would still like to be able to change the connection string and switch between AAD authentication and sql authentication, without additional logic in the application.

[/Update 1]

I'm using EF Core 3.1.4 on an Azure WebApp, and I would like to use the Azure AD identity assigned to the application for authentication, but I run into the following exception:

```<code>ArgumentException: Invalid value for key 'authentication'.
Microsoft.Data.Common.DbConnectionStringBuilderUtil.ConvertToAuthenticationType(string keyword, object value)
</code>```

This is the connection string:

```<code>{
    "ConnectionStrings": {
        "Admin": "Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname;Authentication=Active Directory Integrated"
    }
}
</code>```

I initialize the context using the following code:

var connectionString = this.Configuration.GetConnectionString("Admin");
services.AddDbContext<NetCoreDataContext>(builder => builder.UseSqlServer(connectionString));
```

The Microsoft.Azure.Services.AppAuthentication package is also imported (version 1.5.0)

答:
UPDATE

If you use azure msi, pls read this document.

https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi

PRIVIOUS

Your problems maybe not configure in portal. You can follow the offical document to finished it, then try again.

First, you need to create SQL managed instances which maybe cost your long time. Then u need to configure Active Directory admin and your db. When you finished it, you will find ADO.NET(Active Directory password authentication) in your SQL database ->Connection strings in portal. You can copy and paste it in your code to solve the issue.

I have tried it by myself, and  it works for me. For more detail, you can see this post.

Body:
[Update 1]

I could make it work using the following connection string

Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname

and implementing an interceptor as mentioned in this article.

This proves that Azure is correctly configured, and the problem is somewhere in the application (maybe a missing package?).

Anyway, I would still like to be able to change the connection string and switch between AAD authentication and sql authentication, without additional logic in the application.

[/Update 1]

I'm using EF Core 3.1.4 on an Azure WebApp, and I would like to use the Azure AD identity assigned to the application for authentication, but I run into the following exception:

ArgumentException: Invalid value for key 'authentication'.
Microsoft.Data.Common.DbConnectionStringBuilderUtil.ConvertToAuthenticationType(string keyword, object value)

This is the connection string:

{
    "ConnectionStrings": {
        "Admin": "Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname;Authentication=Active Directory Integrated"
    }
}

I initialize the context using the following code:

var connectionString = this.Configuration.GetConnectionString("Admin");
services.AddDbContext<NetCoreDataContext>(builder => builder.UseSqlServer(connectionString));

The Microsoft.Azure.Services.AppAuthentication package is also imported (version 1.5.0)


问:
How to scale histogram y-axis in million in matplotlib
I am plotting a histogram using matplotlib but my y-axis range is in the millions. How can I scale the y-axis so that instead of printing 5000000 it will print 5

Here is my code

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

filename = './norstar10readlength.csv'
df=pd.read_csv(filename, sep=',',header=None)

n, bins, patches = plt.hist(x=df.values, bins=10, color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('My Very Own Histogram')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()
</code>```

And here is the plot I am generating now

答:
You can modify your df itself, you just need to decide one ratio
so if you want to make 50000 to 5 then it means the ratio is 5/50000 which is 0.0001

Once you have the ratio just multiply all the values of y-axis with the ratio in your DataFrame itself.

Hope this helps!!

Body:
I am plotting a histogram using matplotlib but my y-axis range is in the millions. How can I scale the y-axis so that instead of printing 5000000 it will print 5

Here is my code

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

filename = './norstar10readlength.csv'
df=pd.read_csv(filename, sep=',',header=None)

n, bins, patches = plt.hist(x=df.values, bins=10, color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('My Very Own Histogram')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()

And here is the plot I am generating now


问:
Convert ConfigParser.items('') to dictionary
How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:</p>

```<code>import ConfigParser

config = ConfigParser.ConfigParser()
config.read('conf.ini')

connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
                     "password='%(password)s' port='%(port)s'")

print connection_string % config.items('db')
</code>```

答:
Another alternative would be:

config.ini

```<code>[DEFAULT]
potato=3

[foo]
foor_property=y
potato=4

[bar]
bar_property=y
</code>```

parser.py

```<code>import configparser
from typing import Dict

def to_dict(config: configparser.ConfigParser) -> Dict[str, Dict[str, str]]:
    """
    function converts a ConfigParser structure into a nested dict
    Each section name is a first level key in the the dict, and the key values of the section
    becomes the dict in the second level
    {
        'section_name': {
            'key': 'value'
        }
    }
    :param config:  the ConfigParser with the file already loaded
    :return: a nested dict
    """
    return {section_name: dict(config[section_name]) for section_name in config.sections()}
</code>```

main.py

```<code>import configparser

from parser import to_dict

def main():
    config = configparser.ConfigParser()
    # By default section names are parsed to lower case, optionxform = str sets to no conversion.
    # For more information: https://docs.python.org/3/library/configparser.html#configparser-objects
    # config.optionxform = str
    config.read('config.ini')
    print(f'Config read: {to_dict(config)}')
    print(f'Defaults read: {config.defaults()}')

if __name__ == '__main__':
    main()
</code>```

Body:
How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('conf.ini')

connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
                     "password='%(password)s' port='%(port)s'")

print connection_string % config.items('db')

Body:
Another alternative would be:

config.ini

[DEFAULT]
potato=3

[foo]
foor_property=y
potato=4

[bar]
bar_property=y

parser.py

import configparser
from typing import Dict

def to_dict(config: configparser.ConfigParser) -> Dict[str, Dict[str, str]]:
    """
    function converts a ConfigParser structure into a nested dict
    Each section name is a first level key in the the dict, and the key values of the section
    becomes the dict in the second level
    {
        'section_name': {
            'key': 'value'
        }
    }
    :param config:  the ConfigParser with the file already loaded
    :return: a nested dict
    """
    return {section_name: dict(config[section_name]) for section_name in config.sections()}

main.py

import configparser

from parser import to_dict

def main():
    config = configparser.ConfigParser()
    # By default section names are parsed to lower case, optionxform = str sets to no conversion.
    # For more information: https://docs.python.org/3/library/configparser.html#configparser-objects
    # config.optionxform = str
    config.read('config.ini')
    print(f'Config read: {to_dict(config)}')
    print(f'Defaults read: {config.defaults()}')

if __name__ == '__main__':
    main()


问:
Clustered Nifi running erratically,the issue often appear
java.net.SocketTimeoutException: Read timed out

3 NODE,Nifi-1.10.0,ZK-3.6.5

i reset the relevant setting to make Nifi to respond in given time as following.But this ways can't work!?

```<code>nifi.cluster.node.connection.timeout=120 sec
nifi.cluster.node.read.timeout=120 sec
nifi.zookeeper.connect.timeout=30 secs
nifi.zookeeper.session.timeout=30 secs

nifi.zookeeper.connect.timeout=30 secs
nifi.zookeeper.session.timeout=30 secs

nifi.cluster.load.balance.comms.timeout=30 sec
</code>```

UPDATED:
While enter NIFI UI,Nifi can't running.There are only an app in this VM.

3 Node has same spec and configuration

java.arg.2=-Xms4g
java.arg.3=-Xmx4g

NIFI-APP.LOG

```<code>2020-06-03 08:54:27,845 WARN [Curator-ConnectionStateManager-0] o.a.c.f.state.ConnectionStateManager Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: 32546. Adjusted session timeout ms: 30000
</code>```

ZK-LOG

```<code>2020-06-02 18:12:45,232 [myid:1] - WARN  [NIOWorkerThread-5:NIOServerCnxn@366] - Unable to read additional data from client sessionid 0x1014019b26f0005, likely client has closed socket
</code>```

答:
I suppose that the memory of JVM is too much,so that VM isn't enough for performance to make the Zookeeper work.

Tune JVM to 2G,the Nifi can work successfully.

Body:
java.net.SocketTimeoutException: Read timed out

3 NODE,Nifi-1.10.0,ZK-3.6.5

i reset the relevant setting to make Nifi to respond in given time as following.But this ways can't work!?

nifi.cluster.node.connection.timeout=120 sec
nifi.cluster.node.read.timeout=120 sec
nifi.zookeeper.connect.timeout=30 secs
nifi.zookeeper.session.timeout=30 secs

nifi.zookeeper.connect.timeout=30 secs
nifi.zookeeper.session.timeout=30 secs

nifi.cluster.load.balance.comms.timeout=30 sec

UPDATED:
While enter NIFI UI,Nifi can't running.There are only an app in this VM.

3 Node has same spec and configuration

java.arg.2=-Xms4g
java.arg.3=-Xmx4g

NIFI-APP.LOG

2020-06-03 08:54:27,845 WARN [Curator-ConnectionStateManager-0] o.a.c.f.state.ConnectionStateManager Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: 32546. Adjusted session timeout ms: 30000

ZK-LOG

2020-06-02 18:12:45,232 [myid:1] - WARN  [NIOWorkerThread-5:NIOServerCnxn@366] - Unable to read additional data from client sessionid 0x1014019b26f0005, likely client has closed socket


问:
Python 3 - Hangman game using .txt doc word bank
Im trying to make a hangman using a word bank stored on a .txt document but I'm so confused and just going round in circles.

Can anyone point me in the right direction? My code so far is below. Cheers!

```<code>#Word list
from random import choice

word = with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(words,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")
</code>```

答:
Here is a tested working bit of code. You'll find the main issues were with your import, an incorrect open statement, incorrect indexing of non-list variables ... in many cases, you were indexing a string, which was clearly not what you wanted to be doing.

```<code>import random

# note: get in the habit now of putting your code in a function and not polluting the global scope
# we can test the code using a test word in the event that a stackoverflow contributor doesn't have a words.txt file at hand :P
def main(test_word = "banana"):
    # if there is no words.txt, we will use the test word
    try:
        with open("words.txt") as f:
            word_list = f.read().splitlines()
    except IOError:
        word_list = [test_word]

    # we use random.choice, as we have a list and we want a random word from that list
    # we also want to make sure we put the word and our guesses into the same case, so here I chose lower case
    hidden_word = random.choice(word_list).lower()

    print("Welcome to Hangman! You have 7 lives to guess.")
    print("The length of the word is: " , len(hidden_word))

    failures    = 0
    guessed     = []
    # python is cool, and you can get repeat characters in a list by multiplying!!
    word        = ['*'] * len(hidden_word)

    while failures < 7:
        print("The word is: %s" % ''.join(word))

        try:
            guess = input("Please enter your next guess: ""\n")[0].lower()
        except IndexError:
            # just hitting enter will allow us to break out of the program early
            break

        if guess in guessed:
            # ignore an already guessed letter
            continue
        elif guess in hidden_word:
            print("The letter is correct.")
            for index, letter in enumerate(hidden_word):
                if letter == guess:
                    word[index] = "%s" % guess
        else:
            print("That letter is incorrect.")
            failures += 1
        guessed.append(guess)

        if ''.join(word) == hidden_word:
            break

    if failures == 7:
        print("You lose. The word was:" , hidden_word)
    else:
        print("Indeed, the word is:", hidden_word)

# see https://stackoverflow.com/questions/419163/what-does-if-name-main-do for details on why we do this
if __name__ == "__main__":
    main()
</code>```

Sample Usage

```<code>Welcome to Hangman! You have 7 lives to guess.
The length of the word is:  6
The word is: ******
Please enter your next guess:
n
The letter is correct.
The word is: **n*n*
Please enter your next guess:
b
The letter is correct.
The word is: b*n*n*
Please enter your next guess:
a
The letter is correct.
Indeed, the word is: banana

Process finished with exit code 0
</code>```

Body:
Im trying to make a hangman using a word bank stored on a .txt document but I'm so confused and just going round in circles.

Can anyone point me in the right direction? My code so far is below. Cheers!

#Word list
from random import choice

word = with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(words,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")

Body:
Here is a tested working bit of code. You'll find the main issues were with your import, an incorrect open statement, incorrect indexing of non-list variables ... in many cases, you were indexing a string, which was clearly not what you wanted to be doing.

import random

# note: get in the habit now of putting your code in a function and not polluting the global scope
# we can test the code using a test word in the event that a stackoverflow contributor doesn't have a words.txt file at hand :P
def main(test_word = "banana"):
    # if there is no words.txt, we will use the test word
    try:
        with open("words.txt") as f:
            word_list = f.read().splitlines()
    except IOError:
        word_list = [test_word]

    # we use random.choice, as we have a list and we want a random word from that list
    # we also want to make sure we put the word and our guesses into the same case, so here I chose lower case
    hidden_word = random.choice(word_list).lower()

    print("Welcome to Hangman! You have 7 lives to guess.")
    print("The length of the word is: " , len(hidden_word))

    failures    = 0
    guessed     = []
    # python is cool, and you can get repeat characters in a list by multiplying!!
    word        = ['*'] * len(hidden_word)

    while failures < 7:
        print("The word is: %s" % ''.join(word))

        try:
            guess = input("Please enter your next guess: ""\n")[0].lower()
        except IndexError:
            # just hitting enter will allow us to break out of the program early
            break

        if guess in guessed:
            # ignore an already guessed letter
            continue
        elif guess in hidden_word:
            print("The letter is correct.")
            for index, letter in enumerate(hidden_word):
                if letter == guess:
                    word[index] = "%s" % guess
        else:
            print("That letter is incorrect.")
            failures += 1
        guessed.append(guess)

        if ''.join(word) == hidden_word:
            break

    if failures == 7:
        print("You lose. The word was:" , hidden_word)
    else:
        print("Indeed, the word is:", hidden_word)

# see https://stackoverflow.com/questions/419163/what-does-if-name-main-do for details on why we do this
if __name__ == "__main__":
    main()

Sample Usage

Welcome to Hangman! You have 7 lives to guess.
The length of the word is:  6
The word is: ******
Please enter your next guess:
n
The letter is correct.
The word is: **n*n*
Please enter your next guess:
b
The letter is correct.
The word is: b*n*n*
Please enter your next guess:
a
The letter is correct.
Indeed, the word is: banana

Process finished with exit code 0


问:
For loop skips as counter increase
I wanna write a program that gets data about student name, grades and birthday and save it into a structure. I have written a "for loop" to do so, but my loop does not work properly as i increases.
EDIT:
So my loop works good with i=0 but as i gets higher (i=1) it does not scan the info properly.

inputs:

```<code>       name:a
       birthdate:79/4/18
       grades:20 20 20
       name:b
       birthdate:76/12/2
       grades:16 13 19

       Output:
       Enter student's name: a
       Enter student's birthday(y/m/d): 79 4 18
       Enter student's grades: 20
       Enter student's grades: 20
       Enter student's grades: 20
       Enter student's name:
       Enter student's birthday(y/m/d):
       b
       Enter student's grades:
       Enter student's grades:
       Enter student's grades:
</code>```

**

```<code>       #include <stdio.h>

    struct date
    {
        int year;
        int month;
        int day;
    };
    typedef struct
    {
        char name[30];
        float grade[3];
        struct date birthdate;
    }student;

    int main()
    {
        student list[2];
        int i,j;
        for(i=0;i<2;i++)
        {
            printf("Enter student's name:\n");
            gets(list[i].name);
            printf("Enter student's birthday(y/m/d):\n");
            scanf("%d%d%d",&list[i].birthdate.year,&list[i].birthdate.month,&list[i].birthdate.day);
            for(j=0;j<3;j++)
            {
                printf("Enter student's grades:\n");
                scanf("%f",&list[i].grade[j]);
            }

        }
return 0;
       }
</code>```

答:
You should do:

```<code>scanf("%d/%d/%d", &list[i].birthdate.year, &list[i].birthdate.month, &list[i].birthdate.day);
</code>```

Instead of:

```<code>scanf("%d%d%d",&list[i].birthdate.year,&list[i].birthdate.month,&list[i].birthdate.day);
</code>```

Warning: Do not use gets(), it's dangerous. You may replace that syntax as follows:

```<code>fflush(stdin); // MUST REQUIRED OR INPUT WILL BE SKIPPED
fgets(list[i].name, 30, stdin);
</code>```

Sample Output:

```<code>Enter student's name:
a
Enter student's birthday(y/m/d):
2003/03/05
Enter student's grades:
12
Enter student's grades:
35
Enter student's grades:
66
Enter student's name:
b
Enter student's birthday(y/m/d):
2005/02/01
Enter student's grades:
44
Enter student's grades:
88
Enter student's grades:
5
</code>```

Title: For loop skips as counter increase

Body:
I wanna write a program that gets data about student name, grades and birthday and save it into a structure. I have written a "for loop" to do so, but my loop does not work properly as i increases.
EDIT:
So my loop works good with i=0 but as i gets higher (i=1) it does not scan the info properly.

inputs:

       name:a
       birthdate:79/4/18
       grades:20 20 20
       name:b
       birthdate:76/12/2
       grades:16 13 19

       Output:
       Enter student's name: a
       Enter student's birthday(y/m/d): 79 4 18
       Enter student's grades: 20
       Enter student's grades: 20
       Enter student's grades: 20
       Enter student's name:
       Enter student's birthday(y/m/d):
       b
       Enter student's grades:
       Enter student's grades:
       Enter student's grades:

**

       #include <stdio.h>

    struct date
    {
        int year;
        int month;
        int day;
    };
    typedef struct
    {
        char name[30];
        float grade[3];
        struct date birthdate;
    }student;

    int main()
    {
        student list[2];
        int i,j;
        for(i=0;i<2;i++)
        {
            printf("Enter student's name:\n");
            gets(list[i].name);
            printf("Enter student's birthday(y/m/d):\n");
            scanf("%d%d%d",&list[i].birthdate.year,&list[i].birthdate.month,&list[i].birthdate.day);
            for(j=0;j<3;j++)
            {
                printf("Enter student's grades:\n");
                scanf("%f",&list[i].grade[j]);
            }

        }
return 0;
       }

Body:
You should do:

scanf("%d/%d/%d", &list[i].birthdate.year, &list[i].birthdate.month, &list[i].birthdate.day);

Instead of:

scanf("%d%d%d",&list[i].birthdate.year,&list[i].birthdate.month,&list[i].birthdate.day);

Warning: Do not use gets(), it's dangerous. You may replace that syntax as follows:

fflush(stdin); // MUST REQUIRED OR INPUT WILL BE SKIPPED
fgets(list[i].name, 30, stdin);

Sample Output:

Enter student's name:
a
Enter student's birthday(y/m/d):
2003/03/05
Enter student's grades:
12
Enter student's grades:
35
Enter student's grades:
66
Enter student's name:
b
Enter student's birthday(y/m/d):
2005/02/01
Enter student's grades:
44
Enter student's grades:
88
Enter student's grades:
5


问:
Input type number translated
I'm building for mobile.

I have a form that includes an input type number. When the device language is set to Arabic whenever I set a value to this input it will show it in Arabic numbers.

If I do something like this:

document.getElementById('input-id').value = 444

In the UI, we can see the input will have a value of ٤٤٤, this is the equivalent to 444 in Arabic numerals.

I don't have this issue in Input type="text" because it shows an String of characters so it doesn't convert them.

I know that I could use an Input type text instead but I would like to keep the consistency with the rest of my application and use an Input type number

I have this issue in Chrome, Safari and Firefox.

Clarification: I don't want it to translate it to Arabic Numerals. How can I make this?

答:
for all input that have text type
use jQuery Library</p>

```<code>var arabics = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
var engs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

$(document).on('keyup', 'input[type=text]', function (e) {

    var insideText = (e.key);
    var index = arabics.indexOf(insideText);
    if (index >= 0) {
        var value = $(this).val();
        value.substr(0, value.length - 1) != null ? value = value.substr(0, value.length - 1) + engs[index] : value = engs[index];
        $(this).val(value);
    }

});
</code>```

Title: Input type number translated

Body:
for all input that have text type
use jQuery Library

var arabics = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
var engs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

$(document).on('keyup', 'input[type=text]', function (e) {

    var insideText = (e.key);
    var index = arabics.indexOf(insideText);
    if (index >= 0) {
        var value = $(this).val();
        value.substr(0, value.length - 1) != null ? value = value.substr(0, value.length - 1) + engs[index] : value = engs[index];
        $(this).val(value);
    }

});


问:
Properly use PrimeNG table with scrollable width and height and frozen columns [Angular 7]
I want to try out the scrollable table from PrimeNG. For the moment I'd just like to display some data and let the user edit these. So I wanted to start off with a table that contains a header and a few rows of cells without data. The cells in the frozenColumns-area should not be editable, the ones in the scrollable-area should be. Now I tried around and it is looking quite weird:

Now the static content is displayed in both sections (scrollable and frozen), I could not change the cell-width of the scrollable-area and the table-size is different, aswell as the row-alignment. What am I doing wrong? How should I properly create this table? I tried to follow the examples on PrimeNG, but that did not help me out. I am using Angular 7 btw.

The code:

My HTML:

```<code><p-table [columns]="scrollableCols" [frozenColumns]="frozenCols" [value]="items" [scrollable]="true" scrollHeight="400px" frozenWidth="400px">

  <ng-template pTemplate="colgroup" let-coumns>
    <colgroup>
      <col *ngFor="let col of columns">
    </colgroup>
  </ng-template>

  <ng-template pTemplate="header" let-columns>
      <tr>
          <th *ngFor="let col of columns">
              {{col.header}}
          </th>
      </tr>
  </ng-template>

  <ng-template pTemplate="body" let-rowData let-columns="columns">
    <!-- procude some more rows (without data) -->
    <tr *ngFor="let row of scrollableCols">

      <!-- static columns should not be editable -->
      <td *ngFor="let static of frozenCols">
        frozenColumn
      </td>

      <!-- scrollable columns should be editable -->
      <ng-template ngFor let-col [ngForOf]="columns">
      <td pEditableColumn>
          <p-cellEditor>
              <ng-template pTemplate="input">
                  <input pInputText type="text" [(ngModel)]="col.header" [style]="{'width':'100%'}">
              </ng-template>
              <ng-template pTemplate="output">
                  {{col.field}}
              </ng-template>
          </p-cellEditor>
      </td>
    </ng-template>

    </tr>

  </ng-template>
</p-table>
</code>```

I have the following code in my component:

```<code> cols: any[];
 scrollableCols: any[];
 frozenCols: any[];

 items: any[];

 ngOnInit() {
 this.cols = [
  { field: 'fixedCol1', header: 'Fixed-Col 1' },
  { field: 'fixedCol2', header: 'Fixed-Col 2' },
  { field: 'fixedCol3', header: 'Fixed-Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' }
 ];

 this.frozenCols = [
  { field: 'fixedCol1', header: 'Fixed-Col 1' },
  { field: 'fixedCol2', header: 'Fixed-Col 2' },
  { field: 'fixedCol3', header: 'Fixed-Col 3' }
 ];
 this.scrollableCols = [
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' }
 ];
 //Items-array should contain a value for the table to be created, although it is not used
 this.items = [{placeholder: "placeholder"}];

}
</code>```

答:
You can use this method and can call it in subscribe in case of fetching data from an api:

```<code>makeRowsSameHeight() {
   setTimeout(() => {
       if (document.getElementsByClassName('ui-table-scrollable-wrapper').length) {
           let wrapper = document.getElementsByClassName('ui-table-scrollable-wrapper');
           for (var i = 0; i < wrapper.length; i++) {
              let w = wrapper.item(i) as HTMLElement;
              let frozen_rows: any = w.querySelectorAll('.ui-table-frozen-view tr');
              let unfrozen_rows: any = w.querySelectorAll('.ui-table-unfrozen-view tr');
              for (let i = 0; i < frozen_rows.length; i++) {
                 if (frozen_rows[i].clientHeight > unfrozen_rows[i].clientHeight) {
                    unfrozen_rows[i].style.height = frozen_rows[i].clientHeight+"px";
                    }
                 else if (frozen_rows[i].clientHeight < unfrozen_rows[i].clientHeight)
                 {
                    frozen_rows[i].style.height = unfrozen_rows[i].clientHeight+"px";
                 }
               }
             }
           }
        });
      }
</code>```

And call it in:

```<code>this.someapiservice.get().subscribe(result => {
        .....
        this.makeRowsSameHeight();
    });
</code>```

I hope this helps.

Body:
I want to try out the scrollable table from PrimeNG. For the moment I'd just like to display some data and let the user edit these. So I wanted to start off with a table that contains a header and a few rows of cells without data. The cells in the frozenColumns-area should not be editable, the ones in the scrollable-area should be. Now I tried around and it is looking quite weird:

Now the static content is displayed in both sections (scrollable and frozen), I could not change the cell-width of the scrollable-area and the table-size is different, aswell as the row-alignment. What am I doing wrong? How should I properly create this table? I tried to follow the examples on PrimeNG, but that did not help me out. I am using Angular 7 btw.

The code:

My HTML:

  <ng-template pTemplate="colgroup" let-coumns>
    <colgroup>
      <col *ngFor="let col of columns">
    </colgroup>
  </ng-template>

  <ng-template pTemplate="header" let-columns>

              {{col.header}}

  </ng-template>

  <ng-template pTemplate="body" let-rowData let-columns="columns">

        frozenColumn

      <ng-template ngFor let-col [ngForOf]="columns">

              <ng-template pTemplate="input">
                  <input pInputText type="text" [(ngModel)]="col.header" [style]="{'width':'100%'}">
              </ng-template>
              <ng-template pTemplate="output">
                  {{col.field}}
              </ng-template>

    </ng-template>

  </ng-template>

I have the following code in my component:

 cols: any[];
 scrollableCols: any[];
 frozenCols: any[];

 items: any[];

 ngOnInit() {
 this.cols = [
  { field: 'fixedCol1', header: 'Fixed-Col 1' },
  { field: 'fixedCol2', header: 'Fixed-Col 2' },
  { field: 'fixedCol3', header: 'Fixed-Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' }
 ];

 this.frozenCols = [
  { field: 'fixedCol1', header: 'Fixed-Col 1' },
  { field: 'fixedCol2', header: 'Fixed-Col 2' },
  { field: 'fixedCol3', header: 'Fixed-Col 3' }
 ];
 this.scrollableCols = [
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' },
  { field: 'scrollableCol1', header: 'Scrollable Col 1' },
  { field: 'scrollableCol2', header: 'Scrollable Col 2' },
  { field: 'scrollableCol3', header: 'Scrollable Col 3' }
 ];
 //Items-array should contain a value for the table to be created, although it is not used
 this.items = [{placeholder: "placeholder"}];

}

Body:
You can use this method and can call it in subscribe in case of fetching data from an api:

makeRowsSameHeight() {
   setTimeout(() => {
       if (document.getElementsByClassName('ui-table-scrollable-wrapper').length) {
           let wrapper = document.getElementsByClassName('ui-table-scrollable-wrapper');
           for (var i = 0; i < wrapper.length; i++) {
              let w = wrapper.item(i) as HTMLElement;
              let frozen_rows: any = w.querySelectorAll('.ui-table-frozen-view tr');
              let unfrozen_rows: any = w.querySelectorAll('.ui-table-unfrozen-view tr');
              for (let i = 0; i < frozen_rows.length; i++) {
                 if (frozen_rows[i].clientHeight > unfrozen_rows[i].clientHeight) {
                    unfrozen_rows[i].style.height = frozen_rows[i].clientHeight+"px";
                    }
                 else if (frozen_rows[i].clientHeight < unfrozen_rows[i].clientHeight)
                 {
                    frozen_rows[i].style.height = unfrozen_rows[i].clientHeight+"px";
                 }
               }
             }
           }
        });
      }

And call it in:

this.someapiservice.get().subscribe(result => {
        .....
        this.makeRowsSameHeight();
    });

I hope this helps.


问:
django-crontab missing hash after a day
I'm using django-crontabto run a function every day in my server. When I add the cron with python manage.py crontab add everything is ok, I can see the crons and they execute normally (I've tested them running every minute and they do what I want). The problem is the next day it always throws this error:

```<code>RuntimeError: No job with hash bdd84e8eebbbbc48c5d39e0245c78c93 found. It
    seems the crontab is out of sync with your settings.CRONJOBS. Run "python
    manage.py crontab add" again to resolve this issue!`
</code>```

I have set the CRONTAB_DJANGO_PROJECT_NAME and CRONTAB_DJANGO_MANAGE_PATH because i have a local manage.py.

Seems like it loses the hash somehow from one day to another. This is my settings:

```<code>CRONJOBS = [
('0 7 * * 1-5', 'api.cron.email_to_late_docs', '>> {}'.format(BASE_DIR + '/logs/log_{:%d_%m_%Y}.log'.format(time.now()))),
('0 7 * * 1-5', 'api.cron.email_ten_days_before', '>> {}'.format(BASE_DIR + 'logs/log_{:%d_%m_%Y}.log'.format(time.now())))
]

CRONTAB_DJANGO_PROJECT_NAME = 'public_html'
CRONTAB_DJANGO_MANAGE_PATH = BASE_DIR + '/manage_local.py'
</code>```

Has someone face this error before?

答: In case someone has this problem in the future, the answer from Alberto worked for me. Also, don't use relative paths for the log file. For example, "~/path/to/file" gets translated to something like "/home/user/path/to/file" which changes the hash as well. Use an absolute path</p>

Title: django-crontab missing hash after a day

Body:
I'm using django-crontabto run a function every day in my server. When I add the cron with python manage.py crontab add everything is ok, I can see the crons and they execute normally (I've tested them running every minute and they do what I want). The problem is the next day it always throws this error:

RuntimeError: No job with hash bdd84e8eebbbbc48c5d39e0245c78c93 found. It
    seems the crontab is out of sync with your settings.CRONJOBS. Run "python
    manage.py crontab add" again to resolve this issue!`

I have set the CRONTAB_DJANGO_PROJECT_NAME and CRONTAB_DJANGO_MANAGE_PATH because i have a local manage.py.

Seems like it loses the hash somehow from one day to another. This is my settings:

CRONJOBS = [
('0 7 * * 1-5', 'api.cron.email_to_late_docs', '>> {}'.format(BASE_DIR + '/logs/log_{:%d_%m_%Y}.log'.format(time.now()))),
('0 7 * * 1-5', 'api.cron.email_ten_days_before', '>> {}'.format(BASE_DIR + 'logs/log_{:%d_%m_%Y}.log'.format(time.now())))
]

CRONTAB_DJANGO_PROJECT_NAME = 'public_html'
CRONTAB_DJANGO_MANAGE_PATH = BASE_DIR + '/manage_local.py'

Has someone face this error before?