问:
building dll to run python scripts in AutoCAD
My goal is to run python scripts in Autocad. In order to do this I am using IronPython 2.7.9 to create a NET API. A difficulty encountered is that Autocad uses custom attributes for identifying commands, so my plan is to use this code which allows selection and loading of a Python script:

```<code>using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.EditorInput;

using IronPython.Hosting;

using Microsoft.Scripting.Hosting;

using System;

namespace PythonLoader

{

  public class CommandsAndFunctions

  {

    [CommandMethod("-PYLOAD")]

    public static void PythonLoadCmdLine()

    {

      PythonLoad(true);

    }

    [CommandMethod("PYLOAD")]

    public static void PythonLoadUI()

    {

      PythonLoad(false);

    }

    public static void PythonLoad(bool useCmdLine)

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Editor ed = doc.Editor;

      short fd =

        (short)Application.GetSystemVariable("FILEDIA");

      // As the user to select a .py file

      PromptOpenFileOptions pfo =

          new PromptOpenFileOptions(

            "Select Python script to load"

          );

      pfo.Filter = "Python script (*.py)|*.py";

      pfo.PreferCommandLine =

        (useCmdLine || fd == 0);

      PromptFileNameResult pr =

        ed.GetFileNameForOpen(pfo);

      // And then try to load and execute it

      if (pr.Status == PromptStatus.OK)

        ExecutePythonScript(pr.StringResult);

    }

    [LispFunction("PYLOAD")]

    public ResultBuffer PythonLoadLISP(ResultBuffer rb)

    {

      const int RTSTR = 5005;

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Editor ed = doc.Editor;

      if (rb == null)

      {

        ed.WriteMessage("\nError: too few arguments\n");

      }

      else

      {

        // We're only really interested in the first argument

        Array args = rb.AsArray();

        TypedValue tv = (TypedValue)args.GetValue(0);

        // Which should be the filename of our script

        if (tv != null && tv.TypeCode == RTSTR)

        {

          // If we manage to execute it, let's return the

          // filename as the result of the function

          // (just as (arxload) does)

          bool success =

            ExecutePythonScript(Convert.ToString(tv.Value));

          return

            (success ?

              new ResultBuffer(

                new TypedValue(RTSTR, tv.Value)

              )

              : null);

        }

      }

      return null;

    }

    private static bool ExecutePythonScript(string file)

    {

      // If the file exists, let's load and execute it

      // (we could/should probably add some more robust

      // exception handling here)

      bool ret = System.IO.File.Exists(file);

      if (ret)

      {

        ScriptEngine engine = Python.CreateEngine();

        engine.ExecuteFile(file);

      }

      return ret;

    }

  }

}
</code>```

blog post with code

in the article, the author says I need to build a .dll of that script and add references to:

```<code>IronPython.dll
IronPythonmodules.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Core.dll
</code>```

and "the standard references" to

```<code>acmgd.dll
acdbmgd.dll
</code>```

I have downloaded a decompiler and have begun looking at the code for these .dll and there are of course many different pieces of code to look at. How do I figure out where to add the references for the PYLOAD script posted above so that I can begin executing python scripts in Autocad?

Much Thanks,

答:
First you'll need to compile the .NET code you posted into an assembly (call it "PythonLoader.dll", for example). Once you've created an assembly out of your PythonLoader code, you can reference it in the PYLOAD IronPython script by loading the assembly following one of the sets of instructions here. The examples the author give make use of clr.AddReferenceToFileAndPath, so I would probably start by doing that as well.

```<code>>>> import clr
>>> clr.AddReferenceToFileAndPath(path_to_PythonLoader.dll)
</code>```

Note that you'll need to compile your .NET code to a version of .NET Core or .NET Framework that matches the framework version that your IronPython environment is targeting. (From the IronPython 2.7.9 source, it looks like it targets .NET Framework 4.5, .NET Core 2.0, and .NET Core 2.1.)

Body:
My goal is to run python scripts in Autocad. In order to do this I am using IronPython 2.7.9 to create a NET API. A difficulty encountered is that Autocad uses custom attributes for identifying commands, so my plan is to use this code which allows selection and loading of a Python script:

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.EditorInput;

using IronPython.Hosting;

using Microsoft.Scripting.Hosting;

using System;

namespace PythonLoader

{

  public class CommandsAndFunctions

  {

    [CommandMethod("-PYLOAD")]

    public static void PythonLoadCmdLine()

    {

      PythonLoad(true);

    }

    [CommandMethod("PYLOAD")]

    public static void PythonLoadUI()

    {

      PythonLoad(false);

    }

    public static void PythonLoad(bool useCmdLine)

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Editor ed = doc.Editor;

      short fd =

        (short)Application.GetSystemVariable("FILEDIA");

      // As the user to select a .py file

      PromptOpenFileOptions pfo =

          new PromptOpenFileOptions(

            "Select Python script to load"

          );

      pfo.Filter = "Python script (*.py)|*.py";

      pfo.PreferCommandLine =

        (useCmdLine || fd == 0);

      PromptFileNameResult pr =

        ed.GetFileNameForOpen(pfo);

      // And then try to load and execute it

      if (pr.Status == PromptStatus.OK)

        ExecutePythonScript(pr.StringResult);

    }

    [LispFunction("PYLOAD")]

    public ResultBuffer PythonLoadLISP(ResultBuffer rb)

    {

      const int RTSTR = 5005;

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Editor ed = doc.Editor;

      if (rb == null)

      {

        ed.WriteMessage("\nError: too few arguments\n");

      }

      else

      {

        // We're only really interested in the first argument

        Array args = rb.AsArray();

        TypedValue tv = (TypedValue)args.GetValue(0);

        // Which should be the filename of our script

        if (tv != null && tv.TypeCode == RTSTR)

        {

          // If we manage to execute it, let's return the

          // filename as the result of the function

          // (just as (arxload) does)

          bool success =

            ExecutePythonScript(Convert.ToString(tv.Value));

          return

            (success ?

              new ResultBuffer(

                new TypedValue(RTSTR, tv.Value)

              )

              : null);

        }

      }

      return null;

    }

    private static bool ExecutePythonScript(string file)

    {

      // If the file exists, let's load and execute it

      // (we could/should probably add some more robust

      // exception handling here)

      bool ret = System.IO.File.Exists(file);

      if (ret)

      {

        ScriptEngine engine = Python.CreateEngine();

        engine.ExecuteFile(file);

      }

      return ret;

    }

  }

}

blog post with code

in the article, the author says I need to build a .dll of that script and add references to:

IronPython.dll
IronPythonmodules.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Core.dll

and "the standard references" to

acmgd.dll
acdbmgd.dll

I have downloaded a decompiler and have begun looking at the code for these .dll and there are of course many different pieces of code to look at. How do I figure out where to add the references for the PYLOAD script posted above so that I can begin executing python scripts in Autocad?

Much Thanks,

Body:
First you'll need to compile the .NET code you posted into an assembly (call it "PythonLoader.dll", for example). Once you've created an assembly out of your PythonLoader code, you can reference it in the PYLOAD IronPython script by loading the assembly following one of the sets of instructions here. The examples the author give make use of clr.AddReferenceToFileAndPath, so I would probably start by doing that as well.

>>> import clr
>>> clr.AddReferenceToFileAndPath(path_to_PythonLoader.dll)

Note that you'll need to compile your .NET code to a version of .NET Core or .NET Framework that matches the framework version that your IronPython environment is targeting. (From the IronPython 2.7.9 source, it looks like it targets .NET Framework 4.5, .NET Core 2.0, and .NET Core 2.1.)


来源: stackexchange

问:
Custom wordpress HTTP redirects to HTTPS breaks website
I have added extra rules in my .htaccess file.

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule !^/articles/(.*)$ https://%{HTTP_HOST}/index.php?name=$1 [L,R=301]
RewriteRule ^(articles/)(.*)$ https://%{HTTP_HOST}/index.php?name=$2 [L,R=301]
</IfModule>
</code>```

I have two conditions which seems to work:

http://example.com/this-is-old-url/ meets the first rewrite rule

http://example.com/articles/this-is-old-url/ meets the second rule

But the problem is that after these rules are added my website is starting to make redirects everywhere. For example, I can't access my domain https://example.com which changes to https://example.com/index.php?name=. All my website links breaks.

What am I doing wrong?

答:
```<code>RewriteCond %{HTTPS} off
RewriteRule !^/articles/(.*)$ https://%{HTTP_HOST}/index.php?name=$1 [L,R=301]
RewriteRule ^(articles/)(.*)$ https://%{HTTP_HOST}/index.php?name=$2 [L,R=301]
</code>```

The first rule matches everything, since the URL-path that is matched by the RewriteRule pattern in an .htaccess context never starts with a slash (you appear to have recognised this in your second rule). You also can't have capturing groups in negated patterns - by definition, a negated pattern doesn't actually match anything.

And the second rule executes unconditionally, for both HTTP and HTTPS, since RewriteCond directives only apply to the first RewriteRule that follows. (But these two rules can be combined into one anyway.)

To externally "redirect" (as per your example) a URL of the form http://example.com/this-is-old-url/ (or http://example.com/articles/this-is-old-url/) to https://example.com/index.php?name=this-is-old-url then you can do the following at the top of your .htaccess file:

```<code>RewriteCond %{HTTPS} off
RewriteRule ^(?:articles/)?([\w-]+/)$ https://%{HTTP_HOST}/index.php?name=$1 [R=301,L]
</code>```

UPDATE: the regex now includes - (hyphens) and trailing slash. Note that the trailing slash is included as part of the capturing group. So, it redirects to /index.php?name=this-is-old-url/ (with the trailing slash).

The subpattern (?:articles/)? is optional and non-capturing. So, this one rule matches both your example URLs.

The <IfModule> wrapper is not required. And neither is the RewriteEngine directive, since you presumably already have that in the WordPress code block that follows.

You don't necessarily need to expose the index.php, you could redirect to /?name=... instead, assuming the DirectoryIndex is set correctly.

You will need to clear your browser cache before testing. (Preferably test first with 302 - temporary - redirects.)

I can't access my domain https://example.com which changes to https://example.com/index.php?name=.

That couldn't have happened with your existing rules, only if you'd requested http://example.com (note HTTP, not HTTPS).

ContentLicense: CC BY-SA 4.0

Body:
I have added extra rules in my .htaccess file.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule !^/articles/(.*)$ https://%{HTTP_HOST}/index.php?name=$1 [L,R=301]
RewriteRule ^(articles/)(.*)$ https://%{HTTP_HOST}/index.php?name=$2 [L,R=301]
</IfModule>

I have two conditions which seems to work:

http://example.com/this-is-old-url/ meets the first rewrite rule

http://example.com/articles/this-is-old-url/ meets the second rule

But the problem is that after these rules are added my website is starting to make redirects everywhere. For example, I can't access my domain https://example.com which changes to https://example.com/index.php?name=. All my website links breaks.

What am I doing wrong?

Body:
RewriteCond %{HTTPS} off
RewriteRule !^/articles/(.*)$ https://%{HTTP_HOST}/index.php?name=$1 [L,R=301]
RewriteRule ^(articles/)(.*)$ https://%{HTTP_HOST}/index.php?name=$2 [L,R=301]

The first rule matches everything, since the URL-path that is matched by the RewriteRule pattern in an .htaccess context never starts with a slash (you appear to have recognised this in your second rule). You also can't have capturing groups in negated patterns - by definition, a negated pattern doesn't actually match anything.

And the second rule executes unconditionally, for both HTTP and HTTPS, since RewriteCond directives only apply to the first RewriteRule that follows. (But these two rules can be combined into one anyway.)

To externally "redirect" (as per your example) a URL of the form http://example.com/this-is-old-url/ (or http://example.com/articles/this-is-old-url/) to https://example.com/index.php?name=this-is-old-url then you can do the following at the top of your .htaccess file:

RewriteCond %{HTTPS} off
RewriteRule ^(?:articles/)?([\w-]+/)$ https://%{HTTP_HOST}/index.php?name=$1 [R=301,L]

UPDATE: the regex now includes - (hyphens) and trailing slash. Note that the trailing slash is included as part of the capturing group. So, it redirects to /index.php?name=this-is-old-url/ (with the trailing slash).

The subpattern (?:articles/)? is optional and non-capturing. So, this one rule matches both your example URLs.

The <IfModule> wrapper is not required. And neither is the RewriteEngine directive, since you presumably already have that in the WordPress code block that follows.

You don't necessarily need to expose the index.php, you could redirect to /?name=... instead, assuming the DirectoryIndex is set correctly.

You will need to clear your browser cache before testing. (Preferably test first with 302 - temporary - redirects.)

I can't access my domain https://example.com which changes to https://example.com/index.php?name=.

That couldn't have happened with your existing rules, only if you'd requested http://example.com (note HTTP, not HTTPS).


问:
How do I format a String in an email so Outlook will print the line breaks?
I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook.

I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?

Thanks

答: If you can add in a '.' (dot) character at the end of each line, this seems to prevent Outlook ruining text formatting.</p>

OwnerDisplayName: MattGrommes

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris

ContentLicense: CC BY-SA 3.0


问:
Unable to fecth all user details using Microsoft Graph api graphServiceClient.Users.Request() C#
I am running below code :

```<code>using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

namespace MSGraphAPI
{
    class Program
    {

        private static string clientId = "XXXXX";

        private static string tenantID = "XXXX";

        private static string objectId = "XXXX";

        private static string clientSecret = "XXXX";

        static async System.Threading.Tasks.Task Main(string[] args)
        {

            //     IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            //.Create(clientId)
            //.WithTenantId(tenantID)
            //.WithClientSecret(clientSecret)
            //.Build();

            //        ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            //        GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            //        var users = await graphClient.Users
            //            .Request()
            //            .GetAsync();

            var tenantId = "XXXX.onmicrosoft.com";

            // The client ID of the app registered in Azure AD
            var clientId = "XXXX";

            // *Never* include client secrets in source code!
            var clientSecret = "XXXX"; // Or some other secure place.

            // The app registration should be configured to require access to permissions
            // sufficient for the Microsoft Graph API calls the app will be making, and
            // those permissions should be granted by a tenant administrator.
            var scopes = new string[] { "https://graph.microsoft.com/.default" };

            // Configure the MSAL client as a confidential client
            var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithAuthority($"https://login.microsoftonline.com/XXXXX.onmicrosoft.com/v2.0")
                .WithClientSecret(clientSecret)
                .Build();

            // Build the Microsoft Graph client. As the authentication provider, set an async lambda
            // which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
            // and inserts this access token in the Authorization header of each API request.
            GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) => {

        // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
        var authResult = await confidentialClient
            .AcquireTokenForClient(scopes)
            .ExecuteAsync();

        // Add the access token in the Authorization header of the API request.
        requestMessage.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                })
                );

            // Make a Microsoft Graph API query
            var users = await graphServiceClient.Users.Request().GetAsync();
            Console.WriteLine(users.ToString());

            IGraphServiceUsersCollectionPage userss = graphServiceClient.Users.Request().GetAsync().Result;
            foreach (User user in userss)
            {
                Console.WriteLine("Found user: " + user.DisplayName);
            }
        }
    }
}
</code>```

I am getting only 100 users ( when i use debug and check the count and also put a watch on this variable)  in the userss variable  , but total number of users is around 1000 . I want to fetch all user details and also want to fetch users based on specific criteria using select or any other api in the same code.

Please help me.

答:
Below code works to show all user details.</p>

```<code>      do
            {
                foreach (User user in users)
                {

               if (user.Mail != null)
               {
                    if (user.Mail.Contains("Tom"))
                    {
                       Console.WriteLine("Hurray");
                    }
                }
                    Console.WriteLine($"{user.Id}");
                    Flag++;
                }
            }
            while (users.NextPageRequest != null && (users = await users.NextPageRequest.GetAsync()).Count > 0);
</code>```

Body:
I am running below code :

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

namespace MSGraphAPI
{
    class Program
    {

        private static string clientId = "XXXXX";

        private static string tenantID = "XXXX";

        private static string objectId = "XXXX";

        private static string clientSecret = "XXXX";

        static async System.Threading.Tasks.Task Main(string[] args)
        {

            //     IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            //.Create(clientId)
            //.WithTenantId(tenantID)
            //.WithClientSecret(clientSecret)
            //.Build();

            //        ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            //        GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            //        var users = await graphClient.Users
            //            .Request()
            //            .GetAsync();

            var tenantId = "XXXX.onmicrosoft.com";

            // The client ID of the app registered in Azure AD
            var clientId = "XXXX";

            // *Never* include client secrets in source code!
            var clientSecret = "XXXX"; // Or some other secure place.

            // The app registration should be configured to require access to permissions
            // sufficient for the Microsoft Graph API calls the app will be making, and
            // those permissions should be granted by a tenant administrator.
            var scopes = new string[] { "https://graph.microsoft.com/.default" };

            // Configure the MSAL client as a confidential client
            var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithAuthority($"https://login.microsoftonline.com/XXXXX.onmicrosoft.com/v2.0")
                .WithClientSecret(clientSecret)
                .Build();

            // Build the Microsoft Graph client. As the authentication provider, set an async lambda
            // which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
            // and inserts this access token in the Authorization header of each API request.
            GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) => {

        // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
        var authResult = await confidentialClient
            .AcquireTokenForClient(scopes)
            .ExecuteAsync();

        // Add the access token in the Authorization header of the API request.
        requestMessage.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                })
                );

            // Make a Microsoft Graph API query
            var users = await graphServiceClient.Users.Request().GetAsync();
            Console.WriteLine(users.ToString());

            IGraphServiceUsersCollectionPage userss = graphServiceClient.Users.Request().GetAsync().Result;
            foreach (User user in userss)
            {
                Console.WriteLine("Found user: " + user.DisplayName);
            }
        }
    }
}

I am getting only 100 users ( when i use debug and check the count and also put a watch on this variable)  in the userss variable  , but total number of users is around 1000 . I want to fetch all user details and also want to fetch users based on specific criteria using select or any other api in the same code.

Please help me.

Body:
Below code works to show all user details.

      do
            {
                foreach (User user in users)
                {

               if (user.Mail != null)
               {
                    if (user.Mail.Contains("Tom"))
                    {
                       Console.WriteLine("Hurray");
                    }
                }
                    Console.WriteLine($"{user.Id}");
                    Flag++;
                }
            }
            while (users.NextPageRequest != null && (users = await users.NextPageRequest.GetAsync()).Count > 0);


问:
How to get the placeholder and the text to begin from the start of the textarea?
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="comment-label" for="comments">Comments</label>
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required></code>```

OUTPUT

答:
Hope this help you.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
  position: relative;
}

.placeholder {
  position: absolute;
  left: -10px;
  top: 2px;
  background-color: white;
  padding: 0 20px;
}

.input-textarea:focus~.placeholder,
.input-textarea:valid~.placeholder {
  display: none;
}

.parent {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="comment-label" for="comments">Comments</label>
<div class="parent"><input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="" required>
  <span class="placeholder">Enter your comments here...</span></div></code>```

Body:
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}

Comments
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required>

OUTPUT

Body:
Hope this help you.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
  position: relative;
}

.placeholder {
  position: absolute;
  left: -10px;
  top: 2px;
  background-color: white;
  padding: 0 20px;
}

.input-textarea:focus~.placeholder,
.input-textarea:valid~.placeholder {
  display: none;
}

.parent {
  position: relative;
}

<label class="comment-label" for="comments">Comments</label>
<div class="parent"><input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="" required>
  <span class="placeholder">Enter your comments here...</span></div>


问:
Rename row values that have similar names in a dataframe
I have a dataframe with a bunch of names that are similar, but not identical.  These names belong to the same band/location, and I need a way to renaming all the similar ones to a single name, so I can group my values.

Ex:

```<code>Names:

HOT WATER BAND
Hot Water Band
HOT WATER BAND FROM SEATTLE
Ho t Water Band FROM seATTLE
HOT WATER
ho t wat er BAND from
BAND WATER HOT SEATTLE
</code>```

Is there an easy way to clean and take all of these and rename them to a new variables for example "Hot Water Band From Seattle"?  so that way it's easy to group all of my data afterwards

答:
You could use the Levenshtein distance between the two strings, and if below a certain threshold convert the value to the target.

Example:

```<code>import pandas as pd, numpy as np
import Levenshtein

df['names'] = df['Names'].str.lower().str.strip() # normalize names
df['distance'] = df.apply(lambda x: Levenshtein.distance(x['Names'],
                                               df.groupby(['names'])['names'].\
                                                               value_counts().\
                                                               idxmax()[0]),axis=1)
df['converted'] = df.apply(lambda x: x['Names'].strip()
                                     if x['distance'] <= 5
                                     else np.nan,axis=1)
</code>```

Result which you could then group by:

```<code>In [165]: df['converted']
Out[165]:
0               NaN
1    Hot Water Band
2               NaN
3               NaN
4               NaN
5               NaN
6               NaN
Name: converted, dtype: object
</code>```

Body:
I have a dataframe with a bunch of names that are similar, but not identical.  These names belong to the same band/location, and I need a way to renaming all the similar ones to a single name, so I can group my values.

Ex:

Names:

HOT WATER BAND
Hot Water Band
HOT WATER BAND FROM SEATTLE
Ho t Water Band FROM seATTLE
HOT WATER
ho t wat er BAND from
BAND WATER HOT SEATTLE

Is there an easy way to clean and take all of these and rename them to a new variables for example "Hot Water Band From Seattle"?  so that way it's easy to group all of my data afterwards

Body:
You could use the Levenshtein distance between the two strings, and if below a certain threshold convert the value to the target.

Example:

import pandas as pd, numpy as np
import Levenshtein

df['names'] = df['Names'].str.lower().str.strip() # normalize names
df['distance'] = df.apply(lambda x: Levenshtein.distance(x['Names'],
                                               df.groupby(['names'])['names'].\
                                                               value_counts().\
                                                               idxmax()[0]),axis=1)
df['converted'] = df.apply(lambda x: x['Names'].strip()
                                     if x['distance'] <= 5
                                     else np.nan,axis=1)

Result which you could then group by:

In [165]: df['converted']
Out[165]:
0               NaN
1    Hot Water Band
2               NaN
3               NaN
4               NaN
5               NaN
6               NaN
Name: converted, dtype: object


问:
How to add events to move to other page for a dynamically created listview in jquery mobile?
using the below code, I have inserted the data in the listview

```<code>var renderItemElement = function(item) {

    return $.tmpl("<li><a>${text}</a></li>", item)
        .data("item", item)
        .insertAfter(listHeaders[item.priority]);
};
</code>```

and when click it, i can remove the data, but when i click it, i want the data to be passed to the next page. Can anyone help me with this code?

```<code>$("#bankList").delegate("li.item", "click", function() {
   model.remove($(this).data("item"));
    $(this).slideUp(function() {
       $(this).remove();
    });
});
</code>```

答:
if your  has a href or if you want the whole thing to display as a listview at all, you need to use .listview() method. If the ul tag already existed and is a listview, use .listview('refresh')

to move to another page with javascript, not a href, you need to use

$.mobile.changePage()

Body:
using the below code, I have inserted the data in the listview

var renderItemElement = function(item) {

    return $.tmpl("
${text}
", item)
        .data("item", item)
        .insertAfter(listHeaders[item.priority]);
};

and when click it, i can remove the data, but when i click it, i want the data to be passed to the next page. Can anyone help me with this code?

$("#bankList").delegate("li.item", "click", function() {
   model.remove($(this).data("item"));
    $(this).slideUp(function() {
       $(this).remove();
    });
});


问:
display all 4 options each time in the select menu
I'm new to bash. I want to have a select menu in bash. It has four options. Here is the code:

```<code>PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Option 4")
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Option 2")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Option 3")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Exit")
            break
            ;;
        *) echo "invalid option $REPLY";;
    esac
done
</code>```

When I execute this code, the first time full menu with 4 options appears, but later times (2nd, 3rd and ... times) only "Please enter your choice:" appears. I want each time all 4 options appear like the first time.

As another problem, I want each time that the program is executed and 4 options are re-appeared, the previous commands and terminal content to be cleared. I did this by putting a "clear" before:

```<code>select opt in "${options[@]}"
</code>```

but this way only the first time the terminal content was cleared.

What can I do to solve these problems?

答:
You would have to add a new loop that embeds your menu and then add another break to each case, and for option 4 edit to break 2 as shown in code below. I also added the option to clear the screen after an option is selected.

```<code>#!/bin/bash
PS3='Please enter your choice: '
while true; do
    clear
    options=("Option 1" "Option 2" "Option 3" "Exit")
    select opt in "${options[@]}"
    do
        case $opt in
            "Option 1")
                echo "you chose choice $REPLY which is $opt"
                break
                ;;
            "Option 2")
                echo "you chose choice $REPLY which is $opt"
                break
                ;;
            "Option 3")
                echo "you chose choice $REPLY which is $opt"
                break
                ;;
            "Exit")
                break 2
                ;;
            *) echo "invalid option $REPLY";;
        esac
    done
done
</code>```

So a case of use of this code would be:

```<code>$ ./select.sh
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 1
you chose choice 1 which is Option 1
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 2
you chose choice 2 which is Option 2
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 3
you chose choice 3 which is Option 3
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 4

$
</code>```

Adding a pause after selection

In case you want to ensure that the user can read the option selected you can add the following line before the last done of the code:

```<code>read -p "Press [Enter] key to continue..."
</code>```

That way the user will see the message and will have to press the Enter key to get the menu shown again.

And a case of use of this would be:

```<code>1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 1
you chose choice 1 which is Option 1
Press [Enter] key to continue...
</code>```

Body:
I'm new to bash. I want to have a select menu in bash. It has four options. Here is the code:

PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Option 4")
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Option 2")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Option 3")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Exit")
            break
            ;;
        *) echo "invalid option $REPLY";;
    esac
done

When I execute this code, the first time full menu with 4 options appears, but later times (2nd, 3rd and ... times) only "Please enter your choice:" appears. I want each time all 4 options appear like the first time.

As another problem, I want each time that the program is executed and 4 options are re-appeared, the previous commands and terminal content to be cleared. I did this by putting a "clear" before:

select opt in "${options[@]}"

but this way only the first time the terminal content was cleared.

What can I do to solve these problems?

Body:
You would have to add a new loop that embeds your menu and then add another break to each case, and for option 4 edit to break 2 as shown in code below. I also added the option to clear the screen after an option is selected.

#!/bin/bash
PS3='Please enter your choice: '
while true; do
    clear
    options=("Option 1" "Option 2" "Option 3" "Exit")
    select opt in "${options[@]}"
    do
        case $opt in
            "Option 1")
                echo "you chose choice $REPLY which is $opt"
                break
                ;;
            "Option 2")
                echo "you chose choice $REPLY which is $opt"
                break
                ;;
            "Option 3")
                echo "you chose choice $REPLY which is $opt"
                break
                ;;
            "Exit")
                break 2
                ;;
            *) echo "invalid option $REPLY";;
        esac
    done
done

So a case of use of this code would be:

$ ./select.sh
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 1
you chose choice 1 which is Option 1
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 2
you chose choice 2 which is Option 2
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 3
you chose choice 3 which is Option 3
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 4

$

Adding a pause after selection

In case you want to ensure that the user can read the option selected you can add the following line before the last done of the code:

read -p "Press [Enter] key to continue..."

That way the user will see the message and will have to press the Enter key to get the menu shown again.

And a case of use of this would be:

1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 1
you chose choice 1 which is Option 1
Press [Enter] key to continue...


问:
how to replace name with an ID in javascript
I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used   name="items[]" to get the values i was wondering if there is a way to use ID  or Class instead of the name.Any help would be appreciated in advance .

var count = 0;
var tax = 0.05;

var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate()
{
  initVariable();

 for(var i =0 ;i< checks.length;i++)
   {
     if(checks[i].checked)
       {
         count+=parseFloat(checks[i].value);
       }
   }
  ItemTotal.innerHTML +=count;
  taxFeild.innerHTML+=(parseFloat(tax*count));
  Total.innerHTML+= (tax*count) + count;
}

btn.addEventListener('click',Calculate);

function initVariable()
{
  count =0;
  ItemTotal.innerHTML="Item Total: ";
  taxFeild.innerHTML =" Tax: ";
  Total.innerHTML ="Total with Tax: ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>

<head>

<title>Test</title>
</head>

<body>
  <div class = "container">
   <div id="checkBoxes">
  <input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)<br>
  <input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)<br>
  <input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)<br><br>
    </div>
   <button id="btn">Calculate</button>

    <div id="Sums">
      <p id="ItemTotal"> Item Total: </p>
      <p id="Tax"> Tax: </p>
      <p id="TotalWithTax">Total with Tax: </p>

    </div>
  </div>

</body>

</html></code>```

答:
The possible variants could be to use querySelectorAll or getElementsByClassName:

<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)
<input type="checkbox" class="items" value='7.99' id="item1"> Hamburger ($7.99)
```

<pre class="lang-js prettyprint-override"><code>const checkboxes = document.getElementsByClassName('items');
// OR
const checkboxes = document.querySelectorAll('.items');
</code>```

Or you still could use name attribute on input (instead of class):

const checkboxes = document.querySelectorAll('input[name="items[]"]');
```

Body:
I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used   name="items[]" to get the values i was wondering if there is a way to use ID  or Class instead of the name.Any help would be appreciated in advance .

var count = 0;
var tax = 0.05;

var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate()
{
  initVariable();

 for(var i =0 ;i< checks.length;i++)
   {
     if(checks[i].checked)
       {
         count+=parseFloat(checks[i].value);
       }
   }
  ItemTotal.innerHTML +=count;
  taxFeild.innerHTML+=(parseFloat(tax*count));
  Total.innerHTML+= (tax*count) + count;
}

btn.addEventListener('click',Calculate);

function initVariable()
{
  count =0;
  ItemTotal.innerHTML="Item Total: ";
  taxFeild.innerHTML =" Tax: ";
  Total.innerHTML ="Total with Tax: ";
}

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>

<title>Test</title>

  <input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)

  <input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)

  <input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)

   <button id="btn">Calculate</button>

 Item Total:

 Tax:

Total with Tax:

Body:
The possible variants could be to use querySelectorAll or getElementsByClassName:

<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)
<input type="checkbox" class="items" value='7.99' id="item1"> Hamburger ($7.99)

const checkboxes = document.getElementsByClassName('items');
// OR
const checkboxes = document.querySelectorAll('.items');

Or you still could use name attribute on input (instead of class):

const checkboxes = document.querySelectorAll('input[name="items[]"]');


问:
Is there alternative to get middle element from array using Ramda?
I tried this code and it produces me wanted result:

```<code>const {
  __,
  compose,
  converge,
  divide,
  identity,
  length,
  prop
} = require("ramda");

const div2 = divide(__, 2);
const lengthDiv2 = compose(Math.floor, div2, length);
const midElement = converge(prop, [lengthDiv2, identity]);

console.log(midElement([1, 5, 4]); //5
</code>```

But I dont know is there another way to get property from array, particularly some other implementation of midElement function?

答:
Simplification

Yes, there is a somewhat easier way to write midElement.  This feels a bit cleaner:

const div2 = divide (__, 2)
const lengthDiv2 = compose (floor, div2, length)
const midElement = chain (nth, lengthDiv2)

console.log (midElement ([8, 6, 7, 5, 3, 0, 9]))  //=> 5
console.log (midElement ([8, 6, 7, 5, 3, 0]))     //=> 5```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script><script>
const {divide, __, compose, length, chain, nth} = R
const {floor} = Math                                         </script></code>```

(We choose nth over prop here only because it's semantically more correct.  nth is specific to arrays and their indices.  prop works only because of the coincidence that Javascript builds its arrays atop plain objects.)

chain is an interesting function.  You can find many more details in its FantasyLand specification.  But for our cases, the important point is how it works with functions.

chain (f, g) //=> (x) => f (g (x)) (x)
```

<p>And that explains how (here at least) it's a simpler alternative to <code>converge</code>.</p>

<p>Note that this version -- like your original -- chooses the second of the two central values when the list has an even length.  I usually find that we more naturally choose the first one.  That is, for example, <code>midpoint([3, 6, 9, 12])</code> would usually be <code>6</code>.  To alter that we could simply add a decrement operation before dividing:</p>

<pre class="lang-js prettyprint-override"><code>const midpoint = chain(nth, compose(floor, divide(__, 2), dec, length))
</code>```

But Why?

However, Ramda is not offering much useful here.  Ramda (disclaimer: I'm one of its main authors) offers help with many problems.  But it's a tool, and I would not suggest using it except when it makes your code cleaner.

And this version seems to me much easier to comprehend:

const midpoint = (xs) => xs[Math.floor ((xs.length / 2))]

console.log (midpoint ([8, 6, 7, 5, 3, 0, 9]))  //=> 5
console.log (midpoint ([8, 6, 7, 5, 3, 0]))     //=> 5```
</div>
</div>
</p>

<p>Or this version if you want the decrement behavior above:</p>

<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>const midpoint = (xs) => xs[Math.floor (((xs.length - 1) / 2))]

console.log (midpoint ([8, 6, 7, 5, 3, 0, 9]))  //=> 5
console.log (midpoint ([8, 6, 7, 5, 3, 0]))     //=> 7</code>```

Another Option

But there are so many different ways to write such a function.  While I wouldn't really recommend it, since it's performance cannot compare, a recursive solution is very elegant:

// choosing the first central option
const midpoint = (xs) => xs.length <= 2 ? xs[0] : midpoint (xs.slice(1, -1))
```

<pre class="lang-js prettyprint-override"><code>// choosing the second central option
const midpoint = (xs) => xs.length <= 2 ? xs[xs.length - 1] : midpoint (xs.slice(1, -1))
</code>```

These simply take one of the two central elements if there are no more than two left and otherwise recursively takes the midpoint of the array remaining after removing the first and last elements.

What to remember

I'm a founder of Ramda, and proud of the library.  But we need to remember that it just a library.  It should make a certain style of coding easier, but it should not dictate any particular style.  Use it when it makes your code simpler, more maintainable, more consistent, or more performant.  Never use it simply because you can.

Body:
I tried this code and it produces me wanted result:

const {
  __,
  compose,
  converge,
  divide,
  identity,
  length,
  prop
} = require("ramda");

const div2 = divide(__, 2);
const lengthDiv2 = compose(Math.floor, div2, length);
const midElement = converge(prop, [lengthDiv2, identity]);

console.log(midElement([1, 5, 4]); //5

But I dont know is there another way to get property from array, particularly some other implementation of midElement function?

Body:
Simplification

Yes, there is a somewhat easier way to write midElement.  This feels a bit cleaner:

const div2 = divide (__, 2)
const lengthDiv2 = compose (floor, div2, length)
const midElement = chain (nth, lengthDiv2)

console.log (midElement ([8, 6, 7, 5, 3, 0, 9]))  //=> 5
console.log (midElement ([8, 6, 7, 5, 3, 0]))     //=> 5

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script><script>
const {divide, __, compose, length, chain, nth} = R
const {floor} = Math                                         </script>

(We choose nth over prop here only because it's semantically more correct.  nth is specific to arrays and their indices.  prop works only because of the coincidence that Javascript builds its arrays atop plain objects.)

chain is an interesting function.  You can find many more details in its FantasyLand specification.  But for our cases, the important point is how it works with functions.

chain (f, g) //=> (x) => f (g (x)) (x)

And that explains how (here at least) it's a simpler alternative to converge.

Note that this version -- like your original -- chooses the second of the two central values when the list has an even length.  I usually find that we more naturally choose the first one.  That is, for example, midpoint([3, 6, 9, 12]) would usually be 6.  To alter that we could simply add a decrement operation before dividing:

const midpoint = chain(nth, compose(floor, divide(__, 2), dec, length))

But Why?

However, Ramda is not offering much useful here.  Ramda (disclaimer: I'm one of its main authors) offers help with many problems.  But it's a tool, and I would not suggest using it except when it makes your code cleaner.

And this version seems to me much easier to comprehend:

const midpoint = (xs) => xs[Math.floor ((xs.length / 2))]

console.log (midpoint ([8, 6, 7, 5, 3, 0, 9]))  //=> 5
console.log (midpoint ([8, 6, 7, 5, 3, 0]))     //=> 5

Or this version if you want the decrement behavior above:

const midpoint = (xs) => xs[Math.floor (((xs.length - 1) / 2))]

console.log (midpoint ([8, 6, 7, 5, 3, 0, 9]))  //=> 5
console.log (midpoint ([8, 6, 7, 5, 3, 0]))     //=> 7

Another Option

But there are so many different ways to write such a function.  While I wouldn't really recommend it, since it's performance cannot compare, a recursive solution is very elegant:

// choosing the first central option
const midpoint = (xs) => xs.length <= 2 ? xs[0] : midpoint (xs.slice(1, -1))

// choosing the second central option
const midpoint = (xs) => xs.length <= 2 ? xs[xs.length - 1] : midpoint (xs.slice(1, -1))

These simply take one of the two central elements if there are no more than two left and otherwise recursively takes the midpoint of the array remaining after removing the first and last elements.

What to remember

I'm a founder of Ramda, and proud of the library.  But we need to remember that it just a library.  It should make a certain style of coding easier, but it should not dictate any particular style.  Use it when it makes your code simpler, more maintainable, more consistent, or more performant.  Never use it simply because you can.


答:
textarea.comment {
    height: 59px;
    resize: none;
    width: 100%;
    padding-top: 16px;
    padding-left: 22px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="comment" placeholder="Enter your comments here..." spellcheck="false"></textarea></code>```

Title: How to get the placeholder and the text to begin from the start of the textarea?

Body:
textarea.comment {
    height: 59px;
    resize: none;
    width: 100%;
    padding-top: 16px;
    padding-left: 22px;
}

<textarea class="comment" placeholder="Enter your comments here..." spellcheck="false"></textarea>


问:
Regular expression for SQL query to extract date range which is in String format
How can I extract a date range from a string format field by using sql query. Here is a sample data

```<code>TABLE
------
AUDIT+1+2019-08-24T04:28:34
AUDIT+1+2019-10-22T12:36:11
AUDIT+1+2020-02-16T13:08:08
AUDIT+1+2020-02-18T15:08:08
</code>```

I need to extract all the records with date lesser than 2020-02-18T15:08:08

答:
You can use string functions comparisons:

```<code>where substr(col, -19) < '2020-02-18T15:08:08'
</code>```

You are lucky that the string representation works for ordering, so you don't need to convert this to a date or timestamp.

Body:
How can I extract a date range from a string format field by using sql query. Here is a sample data

TABLE
------
AUDIT+1+2019-08-24T04:28:34
AUDIT+1+2019-10-22T12:36:11
AUDIT+1+2020-02-16T13:08:08
AUDIT+1+2020-02-18T15:08:08

I need to extract all the records with date lesser than 2020-02-18T15:08:08

Body:
You can use string functions comparisons:

where substr(col, -19) < '2020-02-18T15:08:08'

You are lucky that the string representation works for ordering, so you don't need to convert this to a date or timestamp.


问:
Digital root of a number using recursion
I am writing a recursive function to calculate the digital root of a given number:

```<code>def digital_root(num):
    sum = 0
    while num > 0:
        sum += num % 10
        num = num // 10

    while sum > 10:
        sum = digital_root(sum)

    return sum
</code>```

I am not sure if the second while should be replaced with an if statement, and if so, why? (and if not, why not?)

When I try both of the version, the return value is the same.
For example, for the number 10598, the output in both of them is 5.

答:
Please make sure to accept the answer if it works tired of people not accepting my solutions, when it works for them

def digital_root(num):
    #Base case for recursion.
    # recursion always needs a base case
    if len(str(num)) == 1:
        return num
    #Get sum of num by turning it into a string and looping through it,
    #adding each index one by one
    sum = 0
    for i in str(num):
        sum += int(i)
    #get the digital root of the sum
    return digital_root(sum)

def main():
    print(digital_root(27518))

if __name__ == '__main__':
    main()
```

There you go

Body:
I am writing a recursive function to calculate the digital root of a given number:

def digital_root(num):
    sum = 0
    while num > 0:
        sum += num % 10
        num = num // 10

    while sum > 10:
        sum = digital_root(sum)

    return sum

I am not sure if the second while should be replaced with an if statement, and if so, why? (and if not, why not?)

When I try both of the version, the return value is the same.
For example, for the number 10598, the output in both of them is 5.

Body:
Please make sure to accept the answer if it works tired of people not accepting my solutions, when it works for them

def digital_root(num):
    #Base case for recursion.
    # recursion always needs a base case
    if len(str(num)) == 1:
        return num
    #Get sum of num by turning it into a string and looping through it,
    #adding each index one by one
    sum = 0
    for i in str(num):
        sum += int(i)
    #get the digital root of the sum
    return digital_root(sum)

def main():
    print(digital_root(27518))

if __name__ == '__main__':
    main()

There you go


问:
502 when running SQS test using localstack
I'm trying to run some tests with SQS using localstack. However, I keep getting a 502. This works for a co-worker, but it doesn't work on my local machine, on our pipeline, or on docker. The error is the same everywhere, so I'm sending the docker version, since it's probably easier to show what's installed.

Basically I'm creating a docker image that installs java, python, and executes the gradle build from the /repo folder, executing integration tests.

```<code>FROM openjdk:11.0.2-jdk-oraclelinux7

RUN ["yum", "install", "-y", "python", "python-pip"]
RUN ["pip", "install", "--upgrade", "pip"]
RUN ["pip", "install", "virtualenv"]

VOLUME ["/repo"]

ARG sourceDir

COPY ["${sourceDir}", "/repo"]
WORKDIR "/repo"

ENTRYPOINT ["/repo/gradlew", "clean", "integrationTest"]
</code>```

My test code looks like this:

```<code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(LocalstackTestRunner.class)
public class TimeoutQueueTest {

    private AmazonSQS client;
    private static final String QUEUE_NAME = "my queue";

   @LocalServerPort
    private int port;

   @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

   @Before
    public void setup() {
        Map<String, String> attributeMap = new HashMap<>();
        attributeMap.put("DelaySeconds", "0");
        attributeMap.put("MaximumMessageSize", "262144");
        attributeMap.put("MessageRetentionPeriod", "1209600");
        attributeMap.put("ReceiveMessageWaitTimeSeconds", "20");
        attributeMap.put("VisibilityTimeout", "30");

        client = TestUtils.getClientSQS();
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME).withAttributes(attributeMap);
        //FAILS IN THE LINE BELOW!!!!!!!!!!!!!!!!!!
        String standardQueueUrl = client.createQueue(createQueueRequest).getQueueUrl();

        RestAssured.port = port;
    }

(...)
}
</code>```

It fails with:

```<code> com.amazonaws.services.sqs.model.AmazonSQSException: null (Service: AmazonSQS; Status Code: 502; Error Code: 502 Bad Gateway; Request ID: null)

at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1660)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1324)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1074)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:745)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:719)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:701)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:669)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:651)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:515)
at com.amazonaws.services.sqs.AmazonSQSClient.doInvoke(AmazonSQSClient.java:2147)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2116)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2105)
at com.amazonaws.services.sqs.AmazonSQSClient.executeCreateQueue(AmazonSQSClient.java:756)
at com.amazonaws.services.sqs.AmazonSQSClient.createQueue(AmazonSQSClient.java:728)
at uk.co.sainsburys.giftcardservice.TimeoutQueueTest.setup(TimeoutQueueTest.java:76)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.RunPrepareTestInstanceCallbacks.evaluate(RunPrepareTestInstanceCallbacks.java:64)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.statements.SpringFailOnTimeout.evaluate(SpringFailOnTimeout.java:87)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.springframework.test.context.junit4.rules.SpringClassRule$TestContextManagerCacheEvictor.evaluate(SpringClassRule.java:190)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cloud.localstack.LocalstackTestRunner.run(LocalstackTestRunner.java:25)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

Any ideas? What am I missing? The code seems to work, since it's working for my co-worker (saw it with my own eyes). He doesn't remember having done anything different than me in terms of setup.

We're both using python 2.7.10, btw (if it matters).

答:
Most likely this happens because your container is not ready yet by the time tests start running. You can wait for an ok healthcheck or some http path, something along the line of:</p>

```<code>@ClassRule
public static final LocalStackContainer localstack = new LocalStackContainer().withServices(SQS);

@Before
public void before(){
    localstack.waitingFor(Wait.forHealthcheck()); //or Wait.forHttp("/")
}
</code>```

Body:
I'm trying to run some tests with SQS using localstack. However, I keep getting a 502. This works for a co-worker, but it doesn't work on my local machine, on our pipeline, or on docker. The error is the same everywhere, so I'm sending the docker version, since it's probably easier to show what's installed.

Basically I'm creating a docker image that installs java, python, and executes the gradle build from the /repo folder, executing integration tests.

FROM openjdk:11.0.2-jdk-oraclelinux7

RUN ["yum", "install", "-y", "python", "python-pip"]
RUN ["pip", "install", "--upgrade", "pip"]
RUN ["pip", "install", "virtualenv"]

VOLUME ["/repo"]

ARG sourceDir

COPY ["${sourceDir}", "/repo"]
WORKDIR "/repo"

ENTRYPOINT ["/repo/gradlew", "clean", "integrationTest"]

My test code looks like this:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(LocalstackTestRunner.class)
public class TimeoutQueueTest {

    private AmazonSQS client;
    private static final String QUEUE_NAME = "my queue";

   @LocalServerPort
    private int port;

   @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

   @Before
    public void setup() {
        Map<String, String> attributeMap = new HashMap<>();
        attributeMap.put("DelaySeconds", "0");
        attributeMap.put("MaximumMessageSize", "262144");
        attributeMap.put("MessageRetentionPeriod", "1209600");
        attributeMap.put("ReceiveMessageWaitTimeSeconds", "20");
        attributeMap.put("VisibilityTimeout", "30");

        client = TestUtils.getClientSQS();
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME).withAttributes(attributeMap);
        //FAILS IN THE LINE BELOW!!!!!!!!!!!!!!!!!!
        String standardQueueUrl = client.createQueue(createQueueRequest).getQueueUrl();

        RestAssured.port = port;
    }

(...)
}

It fails with:

 com.amazonaws.services.sqs.model.AmazonSQSException: null (Service: AmazonSQS; Status Code: 502; Error Code: 502 Bad Gateway; Request ID: null)

at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1660)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1324)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1074)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:745)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:719)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:701)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:669)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:651)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:515)
at com.amazonaws.services.sqs.AmazonSQSClient.doInvoke(AmazonSQSClient.java:2147)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2116)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2105)
at com.amazonaws.services.sqs.AmazonSQSClient.executeCreateQueue(AmazonSQSClient.java:756)
at com.amazonaws.services.sqs.AmazonSQSClient.createQueue(AmazonSQSClient.java:728)
at uk.co.sainsburys.giftcardservice.TimeoutQueueTest.setup(TimeoutQueueTest.java:76)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.RunPrepareTestInstanceCallbacks.evaluate(RunPrepareTestInstanceCallbacks.java:64)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.statements.SpringFailOnTimeout.evaluate(SpringFailOnTimeout.java:87)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.springframework.test.context.junit4.rules.SpringClassRule$TestContextManagerCacheEvictor.evaluate(SpringClassRule.java:190)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cloud.localstack.LocalstackTestRunner.run(LocalstackTestRunner.java:25)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Any ideas? What am I missing? The code seems to work, since it's working for my co-worker (saw it with my own eyes). He doesn't remember having done anything different than me in terms of setup.

We're both using python 2.7.10, btw (if it matters).

Body:
Most likely this happens because your container is not ready yet by the time tests start running. You can wait for an ok healthcheck or some http path, something along the line of:

@ClassRule
public static final LocalStackContainer localstack = new LocalStackContainer().withServices(SQS);

@Before
public void before(){
    localstack.waitingFor(Wait.forHealthcheck()); //or Wait.forHttp("/")
}


问:
Why i have array [] option as consturctor invoke?
I have a class for example GooglePlayConnection. When I create object of this class without variable initialization (just to invoke method) new GooglePlayConnection() IDEA suggest to me 2 options: like default empty constructor () and .. array []? What does it mean?

I don't have any constructors in these classes.

答:
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html


问:
Java OffsetDateTime showing strange year value
Per the IntelliJ debugger, the OffsetDateTime value is showing like:

+51434-04-02T15:28:41Z

Any idea how to parse the year part or make sense of it? The raw date is actually in milliseconds when I view it on the DB. I have no access to the team that is saving these dates. Also, when accessing the data via my tests it's showing the same when I do a log.debug.

答:
Seeing the timestamp, I think I know why this is happening. Some part of the code has incorrectly interpreted the timestamp 1559909381182. This timestamp represents a the number of milliseconds since the epoch, but your code has interpreted it as a number of seconds. Compare these two lines:

```<code>System.out.println(Instant.ofEpochSecond(1559909381182L));
System.out.println(Instant.ofEpochMilli(1559909381182L));
</code>```

The first will print out a date thousands of years in the future, while the second line will print a more reasonable date.

You should try and find where you have interpreted it as a second.

Body:
Seeing the timestamp, I think I know why this is happening. Some part of the code has incorrectly interpreted the timestamp 1559909381182. This timestamp represents a the number of milliseconds since the epoch, but your code has interpreted it as a number of seconds. Compare these two lines:

System.out.println(Instant.ofEpochSecond(1559909381182L));
System.out.println(Instant.ofEpochMilli(1559909381182L));

The first will print out a date thousands of years in the future, while the second line will print a more reasonable date.

You should try and find where you have interpreted it as a second.


问:
Slow query operations on Azure database
I have 1.2 million rows in Azure data table. The following command:

```<code>DELETE FROM _PPL_DETAIL WHERE RunId <> 229
</code>```

is painfully slow.
There is an index on RunId.
I am deleting most of the data.
229 is a small number of records.
It has been running for an hour now
Should it take this long?
I am pretty sure it will finish.
Is there anything I can do to make operations like this faster?
The database does have a PK, although it is a dummy PK (not used).  I already saw that as an optimization need to help this problem, but it still takes way too long (SQL Server treats a table without a PK differently -- much less efficient).  It is still taking 1+ hour.

答:
How about trying something like below</p>

```<code>BEGIN TRAN
SELECT * INTO #T FROM _PPL_DETAIL WHERE RunId = 229
TRUNCATE TABLE _PPL_DETAIL
INSERT INTO _PPL_DETAIL
SELECT * FROM #T
COMMIT TRAN
</code>```

Title: Slow query operations on Azure database

Body:
I have 1.2 million rows in Azure data table. The following command:

DELETE FROM _PPL_DETAIL WHERE RunId <> 229

is painfully slow.
There is an index on RunId.
I am deleting most of the data.
229 is a small number of records.
It has been running for an hour now
Should it take this long?
I am pretty sure it will finish.
Is there anything I can do to make operations like this faster?
The database does have a PK, although it is a dummy PK (not used).  I already saw that as an optimization need to help this problem, but it still takes way too long (SQL Server treats a table without a PK differently -- much less efficient).  It is still taking 1+ hour.

Body:
How about trying something like below

BEGIN TRAN
SELECT * INTO #T FROM _PPL_DETAIL WHERE RunId = 229
TRUNCATE TABLE _PPL_DETAIL
INSERT INTO _PPL_DETAIL
SELECT * FROM #T
COMMIT TRAN


问:
Does Python ldap module support LDAP channel binding and LDAP signing
There will be a Microsoft Active Directory update in March 2020 that enables LDAP channel binding and LDAP signing as default, see https://support.microsoft.com/en-us/help/4520412/2020-ldap-channel-binding-and-ldap-signing-requirement-for-windows

Will the Python ldap modules still work when LDAP channel binding and LDAP signing is activated to query Active Directory for data?

Do I have to change anything or will it work out of the box?

I connect to Active directory like this:

conn = ldap.initialize('url', bytes_mode=False)
conn.set_option(ldap.OPT_REFERRALS, 0)
conn.start_tls_s()
conn.simple_bind_s('username', 'password')
```

What is the minimum required Python and ldap module version that I have to use after the update?

Thanks in advance.

答:
If you are using simple bind (like in your code example) then there is no changes needed in your client. It will continue to work with LdapEnforceChannelBinding=2.

If you make request signing mandatory (LDAPServerIntegrity=2) then you will not be able to use simple bind without ldaps or STARTLS (But your sample code seems to request STARTTLS so it should keep working).

However I haven't tested yet if Pyton-ldap with SASL sets the binding information, it would be relevant if you want to use GSSAPI/Kerberos or SASL/Digest-md5. Both do no longer work with unmodified clients (for example fails with Java sun-ldap JNDI Provider).

Body:
There will be a Microsoft Active Directory update in March 2020 that enables LDAP channel binding and LDAP signing as default, see https://support.microsoft.com/en-us/help/4520412/2020-ldap-channel-binding-and-ldap-signing-requirement-for-windows

Will the Python ldap modules still work when LDAP channel binding and LDAP signing is activated to query Active Directory for data?

Do I have to change anything or will it work out of the box?

I connect to Active directory like this:

conn = ldap.initialize('url', bytes_mode=False)
conn.set_option(ldap.OPT_REFERRALS, 0)
conn.start_tls_s()
conn.simple_bind_s('username', 'password')

What is the minimum required Python and ldap module version that I have to use after the update?

Thanks in advance.


问:
Powershell Array of Hashtable
How do you pass some data from parameter to an Array of Hashtable?

```<code>filnemane.ps1 -param @{ a = 1, b = 2, c =3}, @{ a = 4, b = 5, c =6}
</code>```

to this output:

```<code>$param = @(
           @{
             a=1,
             b=2,
             c=3
            },
           @{
             a=4,
             b=5,
             c=6
            }
          )
</code>```

Thanks.

答:
You declare a parameter to be of type [hashtable[]] (that is, an array of [hashtable]'s):

```<code># filename.ps1
param(
    [hashtable[]]$Hashtables
)

Write-Host "Hashtables: @("
foreach($hashtable in $Hashtables){
    Write-Host "  @{"
    foreach($entry in $hashtable.GetEnumerator()){
        Write-Host "    " $entry.Key = $entry.Value
    }
    Write-Host "  }"
}
Write-Host ")"
</code>```

With you're sample input you'd get something like:

```<code>PS C:\> .\filename.ps1 -Hashtables @{ a = 1; b = 2; c =3},@{ a = 4; b = 5; c =6}
Hashtables: @(
  @{
     c = 3
     b = 2
     a = 1
  }
  @{
     c = 6
     b = 5
     a = 4
  }
)
</code>```

Notice that the output won't necessarily retain the key order from the input, because, well, that's not how hash tables work :)

As Matthew helpfully points out, if maintaining the key order is important, go with an ordered dictionary instead ([ordered]@{}).

To support accepting either kind without messing up the key order, declare the parameter type as an array of [System.Collections.IDictionary] - an interface that both types implement:

```<code>param(
    [System.Collections.IDictionary[]]$Hashtables
)
</code>```

Title: Powershell Array of Hashtable

Body:
How do you pass some data from parameter to an Array of Hashtable?

filnemane.ps1 -param @{ a = 1, b = 2, c =3}, @{ a = 4, b = 5, c =6}

to this output:

$param = @(
           @{
             a=1,
             b=2,
             c=3
            },
           @{
             a=4,
             b=5,
             c=6
            }
          )

Thanks.

Body:
You declare a parameter to be of type [hashtable[]] (that is, an array of [hashtable]'s):

# filename.ps1
param(
    [hashtable[]]$Hashtables
)

Write-Host "Hashtables: @("
foreach($hashtable in $Hashtables){
    Write-Host "  @{"
    foreach($entry in $hashtable.GetEnumerator()){
        Write-Host "    " $entry.Key = $entry.Value
    }
    Write-Host "  }"
}
Write-Host ")"

With you're sample input you'd get something like:

PS C:\> .\filename.ps1 -Hashtables @{ a = 1; b = 2; c =3},@{ a = 4; b = 5; c =6}
Hashtables: @(
  @{
     c = 3
     b = 2
     a = 1
  }
  @{
     c = 6
     b = 5
     a = 4
  }
)

Notice that the output won't necessarily retain the key order from the input, because, well, that's not how hash tables work :)

As Matthew helpfully points out, if maintaining the key order is important, go with an ordered dictionary instead ([ordered]@{}).

To support accepting either kind without messing up the key order, declare the parameter type as an array of [System.Collections.IDictionary] - an interface that both types implement:

param(
    [System.Collections.IDictionary[]]$Hashtables
)


问:
create and then remove random markers google maps api3 flash
I am trying to add an array of randomly placed markers to a Google Map in Flash with the API V3 and AS3.

I can create the markers no problem, but I'm having a bit of trouble putting them into an array and then clearing them afterwards as I need to provide this functionality.

I saw another post where people were talking about the lack of map.clearOverlays(); in V3? and I need a bit of help incorporated my code .

var markers:Array = new Array();

```<code> function addmarkers()
{
    // Add 10 markers to the map at random locations
    var bounds:LatLngBounds = map.getLatLngBounds();
var southWest:LatLng = bounds.getSouthWest();
var northEast:LatLng = bounds.getNorthEast();
var lngSpan:Number = northEast.lng() - southWest.lng();
var latSpan:Number = northEast.lat() - southWest.lat();
for (var i:int = 0; i < 10; i++)
{
    var newLat:Number = southWest.lat() + (latSpan * Math.random());
    var newLng:Number = southWest.lng() + (lngSpan * Math.random());
    var latlng:LatLng = new LatLng(newLat,newLng);
    map.addOverlay(new Marker(latlng));
    markers.push();

}
</code>```

}

I've got a button that calls this but then I also want a button that

答:
my working code with yours incorporated, thanks.</p>

```<code>function dorandomPoints(e:MouseEvent):void
{
if (chkbox.selected)
{

    var bounds:LatLngBounds = map.getLatLngBounds();
    var southWest:LatLng = bounds.getSouthWest();
    var northEast:LatLng = bounds.getNorthEast();
    var lngSpan:Number = northEast.lng() - southWest.lng();
    var latSpan:Number = northEast.lat() - southWest.lat();

    for (var i:int = 0; i < 10; i++)
    {
        var newLat:Number = southWest.lat() + (latSpan * Math.random());
        var newLng:Number = southWest.lng() + (lngSpan * Math.random());
        var latlng:LatLng = new LatLng(newLat,newLng);
        var marker:Marker = new Marker(latlng);
        markerArray.push(marker);
        map.addOverlay(markerArray[i]);
        //map.removeOverlay(marker);
        //trace(markerArray.length);
    }
}
else
{

    while (markerArray.length > 0)
    {
        var m:Marker = markerArray.shift() as Marker;
        map.removeOverlay(m);
        m = null;
    }

}
}
</code>```

Body:
I am trying to add an array of randomly placed markers to a Google Map in Flash with the API V3 and AS3.

I can create the markers no problem, but I'm having a bit of trouble putting them into an array and then clearing them afterwards as I need to provide this functionality.

I saw another post where people were talking about the lack of map.clearOverlays(); in V3? and I need a bit of help incorporated my code .

var markers:Array = new Array();

 function addmarkers()
{
    // Add 10 markers to the map at random locations
    var bounds:LatLngBounds = map.getLatLngBounds();
var southWest:LatLng = bounds.getSouthWest();
var northEast:LatLng = bounds.getNorthEast();
var lngSpan:Number = northEast.lng() - southWest.lng();
var latSpan:Number = northEast.lat() - southWest.lat();
for (var i:int = 0; i < 10; i++)
{
    var newLat:Number = southWest.lat() + (latSpan * Math.random());
    var newLng:Number = southWest.lng() + (lngSpan * Math.random());
    var latlng:LatLng = new LatLng(newLat,newLng);
    map.addOverlay(new Marker(latlng));
    markers.push();

}

}

I've got a button that calls this but then I also want a button that

Body:
my working code with yours incorporated, thanks.

function dorandomPoints(e:MouseEvent):void
{
if (chkbox.selected)
{

    var bounds:LatLngBounds = map.getLatLngBounds();
    var southWest:LatLng = bounds.getSouthWest();
    var northEast:LatLng = bounds.getNorthEast();
    var lngSpan:Number = northEast.lng() - southWest.lng();
    var latSpan:Number = northEast.lat() - southWest.lat();

    for (var i:int = 0; i < 10; i++)
    {
        var newLat:Number = southWest.lat() + (latSpan * Math.random());
        var newLng:Number = southWest.lng() + (lngSpan * Math.random());
        var latlng:LatLng = new LatLng(newLat,newLng);
        var marker:Marker = new Marker(latlng);
        markerArray.push(marker);
        map.addOverlay(markerArray[i]);
        //map.removeOverlay(marker);
        //trace(markerArray.length);
    }
}
else
{

    while (markerArray.length > 0)
    {
        var m:Marker = markerArray.shift() as Marker;
        map.removeOverlay(m);
        m = null;
    }

}
}


问:
Apple Mail and Applescript
I have has this script working fine on Outlook 2011 for Mac all on a local machine.

I have now found out my "rules" will now work on Apple mail after all these years.
The last part of the rule is to run this script which then sends an HTML email back to the sender.
If I change the tell application "Microsoft Outlook" to tell the application "Mail", I keep getting Syntax Errors and it highlights the "mail folder" telling me it is wrong.
I am stumped.
I am using Exchange with the Mail app. Not sure if that may be the issue?

```<code>tell application "Microsoft Outlook"
    set replyToMessage to message 1 of mail folder "•HOT FOLDER•"
    if (replyToMessage is "") then
        log ("NOTHING SELECTED!")
        return
    end if
    set replyMessageSubj to subject of replyToMessage
    set replyMessage to reply to replyToMessage without opening window
    set contentHTML to "Vault:Users:vault:Documents:VAULT:Digital_Subscription_Reply:Digital_issue22.html" as alias
    set contentHTML to read contentHTML
    set the content of replyMessage to contentHTML
    set the subject of replyMessage to "Vault Digital Issue - Issue 22"
    send replyMessage
end tell
</code>```

答:
Every scriptable application has its own scripting dictionary with its own unique terminology. We can't just change tell application "Microsoft Outlook" to tell application "Mail" and expect it to work, because Mail and Outlook use different keywords for their equivalent objects.  I don't have outlook installed on my machine, so I can't compile or run the original script, but I've modified it as best I can to use Mail terminology. No guarantee this will work, but it will compile and run so you can (at least) test it.

```<code>tell application "Mail"
    set replyToMessage to message 1 of mailbox "•HOT FOLDER•"
    if (replyToMessage is "") then
        log ("NOTHING SELECTED!")
        return
    end if
    set replyMessageSubj to subject of replyToMessage
    set replyMessage to reply replyToMessage without opening window
    set contentHTML to "Vault:Users:vault:Documents:VAULT:Digital_Subscription_Reply:Digital_issue22.html" as alias
    set contentHTML to read contentHTML
    set the content of replyMessage to contentHTML
    set the subject of replyMessage to "Vault Digital Issue - Issue 22"
    send replyMessage
end tell
</code>```

When you're in Script Editor, select "Open Dictionary..." from the File menu and scroll down to open the Mail scripting dictionary. That will give you all the relevant terminology for scripting Mail.app.

Title: Apple Mail and Applescript

Body:
I have has this script working fine on Outlook 2011 for Mac all on a local machine.

I have now found out my "rules" will now work on Apple mail after all these years.
The last part of the rule is to run this script which then sends an HTML email back to the sender.
If I change the tell application "Microsoft Outlook" to tell the application "Mail", I keep getting Syntax Errors and it highlights the "mail folder" telling me it is wrong.
I am stumped.
I am using Exchange with the Mail app. Not sure if that may be the issue?

tell application "Microsoft Outlook"
    set replyToMessage to message 1 of mail folder "•HOT FOLDER•"
    if (replyToMessage is "") then
        log ("NOTHING SELECTED!")
        return
    end if
    set replyMessageSubj to subject of replyToMessage
    set replyMessage to reply to replyToMessage without opening window
    set contentHTML to "Vault:Users:vault:Documents:VAULT:Digital_Subscription_Reply:Digital_issue22.html" as alias
    set contentHTML to read contentHTML
    set the content of replyMessage to contentHTML
    set the subject of replyMessage to "Vault Digital Issue - Issue 22"
    send replyMessage
end tell

Body:
Every scriptable application has its own scripting dictionary with its own unique terminology. We can't just change tell application "Microsoft Outlook" to tell application "Mail" and expect it to work, because Mail and Outlook use different keywords for their equivalent objects.  I don't have outlook installed on my machine, so I can't compile or run the original script, but I've modified it as best I can to use Mail terminology. No guarantee this will work, but it will compile and run so you can (at least) test it.

tell application "Mail"
    set replyToMessage to message 1 of mailbox "•HOT FOLDER•"
    if (replyToMessage is "") then
        log ("NOTHING SELECTED!")
        return
    end if
    set replyMessageSubj to subject of replyToMessage
    set replyMessage to reply replyToMessage without opening window
    set contentHTML to "Vault:Users:vault:Documents:VAULT:Digital_Subscription_Reply:Digital_issue22.html" as alias
    set contentHTML to read contentHTML
    set the content of replyMessage to contentHTML
    set the subject of replyMessage to "Vault Digital Issue - Issue 22"
    send replyMessage
end tell

When you're in Script Editor, select "Open Dictionary..." from the File menu and scroll down to open the Mail scripting dictionary. That will give you all the relevant terminology for scripting Mail.app.


问:
html from requests not the same as source code
I'm trying to scrape this link:
34th government

(https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp)

which has several tables, but when i perform a request using this code:

```<code>import requests
from bs4 import BeautifulSoup

govts_url = r'https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp'
website_url = requests.get(govts_url).text
soup = BeautifulSoup(website_url, 'lxml')
print(f"HTML: \n {soup.prettify()}")
</code>```

I get the following result:

```<code> <html>
 <head>
  <meta charset="utf-8"/>
  <script>
   window.rbzid="Q5gSRBmIWVopQazRgPTWKOEV0wGh1o+KvPO3KMiDuHxM9vVecPeHn4ult+Ba/KU9zInGRSRXUggEmkFs+D5NKSC/WEkCn+B4PCw9CeWkT+Q=";
        u82222.O=function(x){return x;};u82222.E=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.i=function(x,y){return x+y;};u82222.A=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.Y=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.n=function(x,y){return x+y;};u82222.f=function(x,y){return x+y;};u82222.u=function(){var M=function(K,N){var I=N&0xffff;var r=N-I;return(r*K|0)+(I*K|0)|0;},Y=function(x,d,Z){var n=0xcc9e2d51,b=0x1b873593;var E=Z;var O=d&~0x3;for(var w=0;w<O;w+=4){var e=x.charCodeAt(w)&0xff|(x.charCodeAt(w+1)&0xff)<<8|(x.charCodeAt(w+2)&0xff)<<16|(x.charCodeAt(w+3)&0xff)<<24;e=M(e,n);e=(e&0x1ffff)<<15|e>>>17;e=M(e,b);E^=e;E=(E&0x7ffff)<<13|E>>>19;E=E*5+0xe6546b64|0;}e=0;switch(d%4){case 3:e=(x.charCodeAt(O+2)&0xff)<<16;case 2:e|=(x.charCodeAt(O+1)&0xff)<<8;case 1:e|=x.charCodeAt(O)&0xff;e=M(e,n);e=(e&0x1ffff)<<15|e>>>17;e=M(e,b);E^=e;}E^=d;E^=E>>>16;E=M(E,0x85ebca6b);E^=E>>>13;E=M(E,0xc2b2ae35);E^=E>>>16;return E;};return{u:Y};}();u82222.d=function(x,y){return x+y;};u82222.K=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.N=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.Z=function(x,y){return x+y;};u82222.I=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.e=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.t=function(){return{u:function(K){var A='',I=decodeURI("1?'%1CYH.=uVWU~%254_hW,o,WKM%22(-W%5BW,o,LU%075?'%1CH%5D9.5LU%07#?'%1C@W,o6LU%07%22?'%1Ch%5C$.%25N%07D1?'%1C%5DW,o4LU%07%124=LU%07%3C.%25N%07F=?'%1COW,o7bAH%3E?'%1CL%5B.=uF@F%3E%02%25N%07v%0F13SG%5D?,:AWU~13LU%07%3E?'%1CvY8%205FFD.=uF%5BF%3C-%25N%07J1?'%1C%5CW,o7");for(var Y=0,M=0;Y<I.length;Y++,M++){if(M===K.length){M=0;}A+=String.fromCharCode(I.charCodeAt(Y)^K.charCodeAt(M));}A=A.split('~|.');return function(t){return A[t];};}('PA[2))')};}();u82222.o=function(x,y){return x+y;};u82222.r=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.b=function(x,y){return x+y;};u82222.w=function(x){return x;};u82222.s=function(x,y){return x+y;};u82222.F=function(x,y){return x+y;};u82222.M=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.T=function(x,y){return x>y;};function u82222(){}u82222.x=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};(typeof window==="object"?window:global).u82222=u82222;_=window;if(u82222.w(u82222.O(_[u82222.r(24)+u82222.e(0)+u82222.E(25)+u82222.E(14)+u82222.e(18)])||_[u82222.N(26)]||_[u82222.d(u82222.F(u82222.n(u82222.e(28),u82222.r(30))+u82222.N(20),u82222.N(14)),u82222.r(18))]||_[u82222.x(23)])||_[u82222.b(u82222.x(16),u82222.x(19))+u82222.r(6)+u82222.x(11)]||_[u82222.Z(u82222.E(6)+u82222.x(10)+u82222.e(9),u82222.x(14))]||_[u82222.s(u82222.T(975.11,476.89)?u82222.N(8):(13,105.77),u82222.E(1))+u82222.E(5)+u82222.N(25)]||_[u82222.E(4)]||_[u82222.o(u82222.x(3)+u82222.N(29)+u82222.e(14),u82222.e(15))+u82222.N(10)+u82222.x(7)]||_[u82222.i(u82222.e(2)+u82222.N(18)+u82222.N(12)+u82222.e(13)+u82222.x(22)+u82222.E(15)+u82222.E(25),u82222.e(27))+u82222.E(21)]){}else{location[u82222.f(u82222.r(11)+u82222.x(6)+u82222.e(17)+u82222.N(0),u82222.e(2))]();}
  </script>
 </head>
 <body>
 </body>
</html>
</code>```

Which is, of course, not the content i desire.
I guess i'm missing some kind of "activation" to the site, to see the true content. But how can i see it?

Thx!

答: I believe this could be one of those sites where javascript activates the page, which in that case you would have to use something like Selenium. Check out this post.</p>

Body:
I'm trying to scrape this link:
34th government

(https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp)

which has several tables, but when i perform a request using this code:

import requests
from bs4 import BeautifulSoup

govts_url = r'https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp'
website_url = requests.get(govts_url).text
soup = BeautifulSoup(website_url, 'lxml')
print(f"HTML: \n {soup.prettify()}")

I get the following result:

  <meta charset="utf-8"/>

Which is, of course, not the content i desire.
I guess i'm missing some kind of "activation" to the site, to see the true content. But how can i see it?

Thx!


答:
As I know SQL Server had a change and the default DOP is 1 on their servers, so if you run the query with OPTION(MAXDOP 0) could help.

Try this:

```<code>DELETE FROM _PPL_DETAIL
WHERE RunId <> 229
OPTION (MAXDOP 0);
</code>```

Title: Slow query operations on Azure database

Body:
As I know SQL Server had a change and the default DOP is 1 on their servers, so if you run the query with OPTION(MAXDOP 0) could help.

Try this:

DELETE FROM _PPL_DETAIL
WHERE RunId <> 229
OPTION (MAXDOP 0);