问:
Copy a byte to another register in GNU C inline asm, where the compiler chooses registers for both operands
I'm trying to mess around with strings in inline asm for c. I was able to understand how strcpy works (shown below):

static inline char *strcpy(char *dest, char *src)
{
  int d0, d1, d2;
  char temp;

  asm volatile(
    "loop:  lodsb;"   /* load value pointed to by %si into %al, increment %si */
    "       stosb;"   /* move %al to address pointed to by %di, increment %di */
    "       testb %%al, %%al;"
    "       jne loop;"
    : "=&S" (d0), "=&D" (d1), "=&a" (d2)
    : "0" (src), "1" (dest)
    : "memory"
  );
}
```

<p>I'm trying to use this structure to make it so I can modify individual characters of the string before returning them. As a result I'm attempting something that looks like:</p>

<pre class="lang-c prettyprint-override"><code>static inline char *strcpy(char *dest, char *src)
{
  int d0, d1, d2;
  char temp;

  asm volatile(
    "loop:  lodsb;"   /* load value pointed to by %si into %al, increment %si */
    "       mov %2, %3;" /* move al into temp */
    /*
     *
     * Do and comparisons and jumps based off how I want to change the characters
     *
     */
    "       stosb;"   /* move %al to address pointed to by %di, increment %di */
    "       testb %%al, %%al;"
    "       jne loop;"
    : "=&S" (d0), "=&D" (d1), "=&a" (d2), "+r" (temp)
    : "0" (src), "1" (dest)
    : "memory"
  );
}
</code>```

Where I'm basically moving the byte put into %al by the lodsb instruction into a temp variable where I do any processing after. However, it seems that the character is never actually stored in temp for some reason I cannot figure out.

答:
Your 2nd version won't even assemble because temp and d2 are different sizes, so you end up with mov %eax, %dl from GCC: https://godbolt.org/z/tng4g4.  When inline asm doesn't do what you want, always look at the compiler-generated asm to see what the compiler actually substituted into your template (and what registers it picked for which operand).

This doesn't match what you describe (runs but doesn't work) so it's not a MCVE of exactly what you were doing.  But the real question is still answerable.

One easy way is to declare both C temporaries the same size so GCC picks the same width registers.

Or you can use size overrides like mov %k2, %k3 to get movl or mov %b2, %b3 to get movb (8-bit operand-size).

Strangely you chose int for the "=a" temporary so the compiler picks EAX, even though you only load a char.

I'd actually recommend movzbl %2b, %3k to use the opposite sizes from how you declared the variables; that's more efficient than merging a byte into the low byte of the destination, and avoids introducing (or adding more) partial-register problems on P6-family, early Sandybridge-family, and CPUs that don't do any partial-register renaming.  Plus, Intel since Ivybridge can do mov-elimination on it.

BTW, your first version of strcpy looks safe and correct, nice.  And yes, the "memory" clobber is necessary.

Err, at least the inline asm is correct.  You have C undefined behaviour from falling off the end of a non-void function without a return statement, though.

You could simplify the asm operands with a "+&S"(src) read/write operand instead of a dummy output because you're inside a wrapper function (so it's ok to modify this function's local src).  Dummy output with matching constraint is the canonical way to take an input in a register you want to destroy, though.

(If you want to work like ISO C's poorly-designed strcpy, you'd want char *retval = dst ahead of the asm statement, if you're going to use the above suggestion of "+S" and "+D" operands.  A better idea would be to call it stpcpy and return a pointer to the end of the destination.  Also, your src should be const char*.)

Of course it's not particularly efficient to use lodsb/stosb in a loop, especially on CPUs that don't rename AL separately from RAX so every load also needs an ALU uop to merge into RAX. But byte-at-a-time is much worse than you can do with SSE2 so optimizing this with movzx loads, and maybe an indexed addressing mode is probably not worth the trouble.  See https://agner.org/optimize/ and other optimization links in https://stackoverflow.com/tags/x86/info, especially https://uops.info/ for instruction latency / throughput / uop count.  (stosb is 3 uops vs. 2 total for a mov store + inc edi.)

If you're actually optimizing for code-size over speed, just use 8-bit or 32-bit mov to copy registers, not movzbl.

BTW, with this many operands, you probably want to use named operands like [src] "+&S"(src) in the constraints, and then %[src] in the template.

Body:
I'm trying to mess around with strings in inline asm for c. I was able to understand how strcpy works (shown below):

static inline char *strcpy(char *dest, char *src)
{
  int d0, d1, d2;
  char temp;

  asm volatile(
    "loop:  lodsb;"   /* load value pointed to by %si into %al, increment %si */
    "       stosb;"   /* move %al to address pointed to by %di, increment %di */
    "       testb %%al, %%al;"
    "       jne loop;"
    : "=&S" (d0), "=&D" (d1), "=&a" (d2)
    : "0" (src), "1" (dest)
    : "memory"
  );
}

I'm trying to use this structure to make it so I can modify individual characters of the string before returning them. As a result I'm attempting something that looks like:

static inline char *strcpy(char *dest, char *src)
{
  int d0, d1, d2;
  char temp;

  asm volatile(
    "loop:  lodsb;"   /* load value pointed to by %si into %al, increment %si */
    "       mov %2, %3;" /* move al into temp */
    /*
     *
     * Do and comparisons and jumps based off how I want to change the characters
     *
     */
    "       stosb;"   /* move %al to address pointed to by %di, increment %di */
    "       testb %%al, %%al;"
    "       jne loop;"
    : "=&S" (d0), "=&D" (d1), "=&a" (d2), "+r" (temp)
    : "0" (src), "1" (dest)
    : "memory"
  );
}

Where I'm basically moving the byte put into %al by the lodsb instruction into a temp variable where I do any processing after. However, it seems that the character is never actually stored in temp for some reason I cannot figure out.


来源: stackexchange

问:
Logging in with a BOT in a private WIKI to read feedrecentchanges action
I have a private wiki installation:

```<code>MediaWiki   1.34.0
PHP     7.2.27
</code>```

with

```<code>$wgGroupPermissions['*']['read'] = false;
$wgGroupPermissions['*']['edit'] = false;
$wgGroupPermissions['*']['createaccount'] = false;
</code>```

in LocalSettings.php

What I'd like to do is to read recent changes through a bot, in order to display "Recente Wiki news - check them out!" to my users when they log into another web app.

So, following this example on official documentation, first I created a BOT Password.

Then I try to call:

```<code>https://mywiki.myhosting.com/api.php?action=query&meta=tokens&type=login&format=json
</code>```

and get the answer

```<code>{"error":{"code":"readapidenied","info":"You need read permission to use this module.","*":"See https://mywiki.myhosting.com/api.php for API usage. Subscribe to the mediawiki-api-announce mailing list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> for notice of API deprecations and breaking changes."}}
</code>```

If I try the same querystring in a new tab after loggin in to the Wiki (that is - the browser has the authentication cookie already) then I get the answer:

```<code>{"batchcomplete":"","query":{"tokens":{"logintoken":"0a0_some_token_letters_518+\\"}}}
</code>```

Where am I doing wrong?

In my understanding, if I don't get this first token, then I will not be able to make the second login call where I am supposed to use my BOT username / password, right?

Any help appreciated.

答: Apparently this is a bug that has been fixed just a few days ago. As a workaround, you can just make a login request without a token. You'll get an error message, but there will be a token in it. That login workflow is deprecated and will be removed eventually, but right now it works.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a private wiki installation:

MediaWiki   1.34.0
PHP     7.2.27

with

$wgGroupPermissions['*']['read'] = false;
$wgGroupPermissions['*']['edit'] = false;
$wgGroupPermissions['*']['createaccount'] = false;

in LocalSettings.php

What I'd like to do is to read recent changes through a bot, in order to display "Recente Wiki news - check them out!" to my users when they log into another web app.

So, following this example on official documentation, first I created a BOT Password.

Then I try to call:

https://mywiki.myhosting.com/api.php?action=query&meta=tokens&type=login&format=json

and get the answer

{"error":{"code":"readapidenied","info":"You need read permission to use this module.","*":"See https://mywiki.myhosting.com/api.php for API usage. Subscribe to the mediawiki-api-announce mailing list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> for notice of API deprecations and breaking changes."}}

If I try the same querystring in a new tab after loggin in to the Wiki (that is - the browser has the authentication cookie already) then I get the answer:

{"batchcomplete":"","query":{"tokens":{"logintoken":"0a0_some_token_letters_518+\\"}}}

Where am I doing wrong?

In my understanding, if I don't get this first token, then I will not be able to make the second login call where I am supposed to use my BOT username / password, right?

Any help appreciated.


问:
AADSTS90002: Tenant 'xx' not found. This may happen if there are no active subscriptions for the tenant
I followed this tutorial to generate an access token from client app for target app. According to the comment for this tutorial, for the resources, I changed to App ID URL. But I am still not able to successfully generate bearer token for the target app.

It shows this error message:

AdalException:
  {"error":"invalid_request","error_description":"AADSTS90002: Tenant
  '' not found. This may happen if there are no active
  subscriptions for the tenant....}

Anyone knows what else I missed?

答:
For me the issue was resolved by using older version of Microsoft.IdentityModel.Clients.ActiveDirectory.
I had to used 3.13.8 version. Latest version has issues.


问:
K2 Materials and Topics
I am a new K2 developer and I am looking for K2 materials  about below Topics

Introduction to K2 Blackpearl.

Feature of K2 Blackpearl.

How to design and deploy k2 Blackpearl workflows .

How to integrate k2 Blackpearl application/workflow with .net/asp.net.

What is k2 black pearl workspace .

How to connect to k2 Blackpearldatabase.And perform k2 Blackpearl database transaction .

How we can work on K2 mobility features

Can you help me to do that, I don't have any background on K2.

答:
K2 stores all of it's programming configuration in SQL Server.  You can search this information to overcome some of the deficiencies with the designer.

Workflows

Run this SQL against the K2 database - SELECT [Name],[Json] FROM [K2].[Designer].[Process]

Save the results as a CSV (trying to copy and paste the json column will not work as the copy buffer hits a hard limit).

You now have the contents of the workflow as K2 sees it, which can be searched using a text editor.

Forms

Run this SQL against the K2 database -

SELECT [Xml] FROM [K2].[Form].[AuditLog] where data = '8faa544a-1acb-407f-8648-d1ce7aa1b673' order by datetime desc

The guid in the SQL can be retrieved from the URL when editing the form.

You now have the contents of the form as K2 sees it, which can be searched using a text editor.

ContentLicense: CC BY-SA 3.0

Title: K2 Materials and Topics


问:
Xcode quits unexpectedly every time I open my project
After opening xcode, when I open my current project, it's showing a warning like "xcode quit unexpectedly" with 3 options: "Ignore", "Report" and "Reopen". When I click "Reopen", it will open the xcode window and again automatically it will close and show the same warning.

Why this is happening? If I open any other projects, then it opens with no issues; the issue is with my current app.

versions:

xcode is 4.3.1

mac OS X version is 10.7.3

Please tell me why it's happening like this.

答:
Delete Project.xcworkspace first.

Open Terminal

Go to application folder

Run command pod install

Delete Derived Data

Open Project.xcworkspace

It works for me.


问:
ASP.NET Core, AddOpenIdConnect - does ValidateIssuerSigningKey need to have a IssuerSigningKey?
I have a working open id authentication in my ASP.NET Core application. Now I asked myself, if the issuer token is automatically validated. I wasn't sure, so I did this

```<code>services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    options.MetadataAddress = Configuration.GetValue<string>("MetadataAddress");
    options.Authority = Configuration.GetValue<string>("Authority");
    options.ClientId = Configuration.GetValue<string>("ClientId");
    options.ClientSecret = Configuration.GetValue<string>("ClientSecret");

    options.TokenValidationParameters.ValidateIssuerSigningKey = true;
</code>```

Now i was wondering, if I set ValidateIssuerSigningKey to true, do I have to set a IssuerSigningKey? I didn't get any info in the documentations.

The issue I see is, that the signing algorithm can be whatever is possible. The MetadataAddress will tell it to me in the id_token_signing_alg_values_supported property, but do I have to implement any possible algorithm? Or does Microsofts IdentityModel do it by its own?

Thank you very much!

答:
You don't need to add ValidateIssuerSigningKey/IssuerSigningKey since you are setting Authority/MetadataAddress , the middleware will take responsible for retrieving, caching, and refreshing the configuration from metadata , including the keys which publish by trust STS .

In OIDC authentication flows , if you getting the ID token from authorize endpoing in Hybrid or Implicit flow , middleware will help validate the signature and payload . But as document : https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation

If  the ID Token is received via direct communication between the Client and the Token Endpoint, the TLS server validation MAY be used to validate the issuer in place of checking the token signature.

And  see source code of OIDC middleware , it will skip signature validation if ID token is received from token endpoint .

Body:
I have a working open id authentication in my ASP.NET Core application. Now I asked myself, if the issuer token is automatically validated. I wasn't sure, so I did this

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    options.MetadataAddress = Configuration.GetValue<string>("MetadataAddress");
    options.Authority = Configuration.GetValue<string>("Authority");
    options.ClientId = Configuration.GetValue<string>("ClientId");
    options.ClientSecret = Configuration.GetValue<string>("ClientSecret");

    options.TokenValidationParameters.ValidateIssuerSigningKey = true;

Now i was wondering, if I set ValidateIssuerSigningKey to true, do I have to set a IssuerSigningKey? I didn't get any info in the documentations.

The issue I see is, that the signing algorithm can be whatever is possible. The MetadataAddress will tell it to me in the id_token_signing_alg_values_supported property, but do I have to implement any possible algorithm? Or does Microsofts IdentityModel do it by its own?

Thank you very much!


问:
WPF Dependency Property Inheritance
I have a scenario in which DP Inheritance is not working, my code can also be wrong.

I have a Parent control with a bool Dependency Property "CanShow" on ViewModel. This enables/disables the button on this MainParent Window.

Now, I want a property/DP on child VM, which can set the CanShow property of Parent from childVM to enable/disable the button.

Is this a scenario for Dependency Property Inheritance? - Plz suggest.

I hope so, the scenario is clear.

Thanks,

VJ

答: No, inheritance does not work from child to parent, it works from parent to child. You will have to use some sort of event aggregation in order to propagate your event from child to parent which will change CanShow.</p>

Title: WPF Dependency Property Inheritance


问:
How do I make a concatenation? VB6
I have a ListView that is filled with TextBoxes data, I need that when saving all the values are saved concatenated in this way:

Value / Value

But it keeps me like this:

Value / / Value

[

How can you fix it?

This is my code to button save:

        Dim StringPrefijoTel As String
        Dim StringNumeroTel As String

        Dim StringPrefijoCel As String
        Dim StringNumeroCel As String

        Dim i As Integer

        For i = 1 To List_Contactos.ListItems.Count
            If List_Contactos.ListItems(i).SubItems(1) = "Fijo" Then
                StringPrefijoTel = List_Contactos.ListItems(i).SubItems(2)
                If StringNumeroTel = "" Then
                    StringNumeroTel = List_Contactos.ListItems.Item(i).SubItems(3) + " / " + StringNumeroTel
                Else
                    StringNumeroTel = StringNumeroTel + " / " + List_Contactos.ListItems.Item(i).SubItems(3)
                End If

                Rs!actelcli = StringNumeroTel
                Rs!preFijo = StringPrefijoTel
            Else
                StringPrefijoCel = List_Contactos.ListItems(i).SubItems(2)
                If StringNumeroCel = "" Then
                    StringNumeroCel = List_Contactos.ListItems.Item(i).SubItems(3) + " / " + StringNumeroCel
                Else
                    StringNumeroCel = StringNumeroCel + " / " + List_Contactos.ListItems.Item(i).SubItems(3)
                End If

                Rs!preCelu = StringPrefijoCel
                Rs!Celu = StringNumeroCel
            End If
        Next i
```

答: You can use the Replace function in VB6 to replace all double slashes with a single slash like this : a = Replace(StringToFind,"//","/")

Title: How do I make a concatenation? VB6


问:
How to create a list in Python that will yield the following result []
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

```<code>new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)
</code>```

My output:

```<code>[['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

But here is the expected output:

```<code>['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

Please why am I not getting the expected output?

答:
your 9th element is ['water', 'air', 'fire', 'earth'] (it is included) and 12th element is "code" (it is excluded in python)
so result is [['water', 'air', 'fire', 'earth'], 'games', 2.7]</p>

Body:
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)

My output:

[['water', 'air', 'fire', 'earth'], 'games', 2.7]

But here is the expected output:

['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]

Please why am I not getting the expected output?


问:
Only allow numbers from standard input (read command)
i have a file that has a list of routes to .sh files, but to execute the scripts a date is needed, it the file the date is YYYYMMD. When I run the script that executes the list of scripts, i prompt the user for the date with the readcommand.

My problem is that i need to be 100% sure that the date that the user inputs is at least all numbers, how can i do this? i have already made sure that the maximum chars inputed is 8, so all i need is to only allow the user to input numbers. This is all i have so far.

```<code>echo 'Input date (YYYYMMDD)'
read -n 8 date
</code>```

Any ideas?

Thankyou.

答:
I find an until loop can do this job just fine in many instances.

I found the syntax for the comparison on another forum and it works, while some of the syntax mentioned in here was throwing errors at me. Notice the "..+$" ending and inclusion of the [+-]?.. or [+].. in the case of positive numbers only.

To be honest, I'm still learning, and I don't know why this syntax works for me versus what others have posted here.

Note: this does not work without the -p flag and with -n the interpreter was unhappy.

```<code>#!/bin/bash
read -p 'Input date (YYYYMMDD): ' date
until [[ $date =~ ^[+]?[0-9]{8}+$ ]]
do
    echo "Oops! User input was not 8 characters and/or not a positive integer!"
    echo
    read -p 'Input date (YYYYMMDD): ' date
done

echo "User gave a valid input: $date"
</code>```

Console Output:

```<code>Input date (YYYYMMDD): very age
Oops! User input was not 8 characters and/or not a positive integer!

Input date (YYYYMMDD): -19670218
Oops! User input was not 8 characters and/or not a positive integer!

Input date (YYYYMMDD): 670218
Oops! User input was not 8 characters and/or not a positive integer!

Input date (YYYYMMDD): 19670218
User gave a valid input: 19670218
</code>```

Body:
i have a file that has a list of routes to .sh files, but to execute the scripts a date is needed, it the file the date is YYYYMMD. When I run the script that executes the list of scripts, i prompt the user for the date with the readcommand.

My problem is that i need to be 100% sure that the date that the user inputs is at least all numbers, how can i do this? i have already made sure that the maximum chars inputed is 8, so all i need is to only allow the user to input numbers. This is all i have so far.

echo 'Input date (YYYYMMDD)'
read -n 8 date

Any ideas?

Thankyou.

Body:
I find an until loop can do this job just fine in many instances.

I found the syntax for the comparison on another forum and it works, while some of the syntax mentioned in here was throwing errors at me. Notice the "..+$" ending and inclusion of the [+-]?.. or [+].. in the case of positive numbers only.

To be honest, I'm still learning, and I don't know why this syntax works for me versus what others have posted here.

Note: this does not work without the -p flag and with -n the interpreter was unhappy.

#!/bin/bash
read -p 'Input date (YYYYMMDD): ' date
until [[ $date =~ ^[+]?[0-9]{8}+$ ]]
do
    echo "Oops! User input was not 8 characters and/or not a positive integer!"
    echo
    read -p 'Input date (YYYYMMDD): ' date
done

echo "User gave a valid input: $date"

Console Output:

Input date (YYYYMMDD): very age
Oops! User input was not 8 characters and/or not a positive integer!

Input date (YYYYMMDD): -19670218
Oops! User input was not 8 characters and/or not a positive integer!

Input date (YYYYMMDD): 670218
Oops! User input was not 8 characters and/or not a positive integer!

Input date (YYYYMMDD): 19670218
User gave a valid input: 19670218


问:
MySQL partitioning or NoSQL like AWS DynamoDB?
Business logic:

My application crawls a lot(hundreds or sometimes thousands) of webpages every few hours and stores all the links(i.e. all anchor tags) on that webpage in a MySQL database table say links. This table is growing very big day by day (already around 20 million records as of now).

Technical:

I have a unique index combined on [webpage_id, link] in the links table. Also, I have a column crawl_count in the same table.
Now whenever I crawl a webpage, I already know webpage_id (the foreign key to webpages table) and I get links in that webpage (i.e. array of link) which I just do an insert or update query without worrying about what is already in the table.

```<code>INSERT INTO ........ ON DUPLICATE KEY UPDATE crawl_count=crawl_count+1
</code>```

Problem:

The table grows big every day & I want to optimize the table for performance. Options I considered are,

Partitioning: Partition table by domains. All webpages belong to a particular domain. For example: Webpage https://www.amazon.in/gp/goldbox?ref_=nav_topnav_deals belong to the domain https://www.amazon.in/

NoSQL like DynamoDB. I have other tables of application in MySQL DB which I do not want to migrate to DynamoDB unless it's absolutely required. Also I have considered change in application logic (eg: change the structure of webpages table to something like

```<code>{webpage: "http://example.com/new-brands", links: [link1, link2, link3]}
</code>```

and migrate this table to DynamoDB so I don't have a links table. But again, there is a limit for every record in DynamoDB(400kb). What if it exceeds this limit?

I have read pros & cons of using either of the approach. As far my understanding goes, DynamoDB doesn't seem to be a good fit for my situation. But still wanted to post this question so I can make a good decision for this scenario.

答:
PARTITION BY domain -- No.  There won't be any performance gain.  Anyway, you will find that one domain dominates the table, and a zillion domains show up only once.  (I'm speaking from experience.)

The only concept of an "array" is a separate table.  It would have, in your case, webpage_id and link as a 2-column PRIMARY KEY (which is 'unique').

Normalize.  This is to avoid having lots of copies of each domain and each link.  This saves some space.

I assume you have two categories of links -- the ones for pages you have scanned, and the ones for pages waiting to scan.  And probably the two sets are similar in size.  I don't understand the purpose of `crawl count, but it adds to the cost.

I may be able to advise further if I could see the queries -- both inserting and selecting.  Also, how big are the tables (GB) and what is the value of innodb_buffer_pool_size?  Putting these together, we can discuss likely points if sluggishness.

Also the slowlog would help.

Are you dealing with non-ascii urls?  Urls too long to index?  Do you split urls into domain + path?  Do you strip off "#..."?  And "?..."?

Body:
Business logic:

My application crawls a lot(hundreds or sometimes thousands) of webpages every few hours and stores all the links(i.e. all anchor tags) on that webpage in a MySQL database table say links. This table is growing very big day by day (already around 20 million records as of now).

Technical:

I have a unique index combined on [webpage_id, link] in the links table. Also, I have a column crawl_count in the same table.
Now whenever I crawl a webpage, I already know webpage_id (the foreign key to webpages table) and I get links in that webpage (i.e. array of link) which I just do an insert or update query without worrying about what is already in the table.

INSERT INTO ........ ON DUPLICATE KEY UPDATE crawl_count=crawl_count+1

Problem:

The table grows big every day & I want to optimize the table for performance. Options I considered are,

Partitioning: Partition table by domains. All webpages belong to a particular domain. For example: Webpage https://www.amazon.in/gp/goldbox?ref_=nav_topnav_deals belong to the domain https://www.amazon.in/

NoSQL like DynamoDB. I have other tables of application in MySQL DB which I do not want to migrate to DynamoDB unless it's absolutely required. Also I have considered change in application logic (eg: change the structure of webpages table to something like

{webpage: "http://example.com/new-brands", links: [link1, link2, link3]}

and migrate this table to DynamoDB so I don't have a links table. But again, there is a limit for every record in DynamoDB(400kb). What if it exceeds this limit?

I have read pros & cons of using either of the approach. As far my understanding goes, DynamoDB doesn't seem to be a good fit for my situation. But still wanted to post this question so I can make a good decision for this scenario.


问:
SwiftUI Nested NavigationViews show multiple navigation bars
My ContentView include a NavigationView and I drill down via NavigationLink to an OverviewView that displays a List and from there via NavigationLink to a DetailView. Now I want to tap text in my DetailView and bring up another view BUT when I now try to add a NavigationLink to that object I get an error that the NavigationLink requires to be embedded in a NavigationView, so I change my code to

```<code>    NavigationView{
  ScrollView() {
  VStack{
  VStack(spacing: -25) {
  HStack(spacing: -25) {
  NavigationLink(destination: WarehouseOrderLinesView(warehouseOrderLines: warehouseOrderLineController.warehouseOrderLines)){
  TaskSummaryView(title: "Total Lines", color: .blue, icon: "list.dash", value: warehouseOrderLineController.warehouseOrderLines.count)
  }
</code>```

but now since there is a NavigationView inside another NavigationView, I end up having 2 navigation bars on top.

Is there a way to use the NavigationLink without embedding it in another NaviagationView or to navigate to another view by NOT using the NavigationLink and something like .sheet (I don't want to display the new view as modal!).

Below the complete sample code for testing:

```<code>
//
//  ContentView.swift
//  Two Navbars
//
//  Created by Max on 2020-02-05.
//  Copyright © 2020 Max. All rights reserved.
//

import SwiftUI

struct ContentView: View {
  var body: some View {
  NavigationView{
  ScrollView{
  VStack{
  NavigationLink(destination: ListView1()){
  Text("Tap me")
  }

  Text("Nothing here")
  }
  }
  }
  }
}

struct ListView1: View {

  var body: some View {
  List{
  NavigationLink(destination: DetailView1()){
  Text("Tap me one more time")
  }

  Text("Item 2")
  Text("Item 3")
  }
  }
}

struct DetailView1: View {

  var body: some View {
  NavigationView{
  ScrollView() {
  VStack{
  NavigationLink(destination: DetailView2()){
  Text("Drill down more")
  }
  Text("Nothing here")
  }
  }
  }
  }
}

struct DetailView2: View {

  var body: some View {
  List {
  Text("That's it")
  Text("Nothing here")
  }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
  ContentView()
  }
}
</code>```

答:
You only need 1 NavigationView at the root View. Remove the one in DetailView1.</p>

```<code>struct DetailView1: View {
    var body: some View {
        ScrollView(){
            VStack {
                NavigationLink(destination: DetailView2()){
                    Text("Drill down more")
                }
                Text("Nothing here")
            }
         }
      }
  }
}
</code>```

Body:
My ContentView include a NavigationView and I drill down via NavigationLink to an OverviewView that displays a List and from there via NavigationLink to a DetailView. Now I want to tap text in my DetailView and bring up another view BUT when I now try to add a NavigationLink to that object I get an error that the NavigationLink requires to be embedded in a NavigationView, so I change my code to

    NavigationView{
  ScrollView() {
  VStack{
  VStack(spacing: -25) {
  HStack(spacing: -25) {
  NavigationLink(destination: WarehouseOrderLinesView(warehouseOrderLines: warehouseOrderLineController.warehouseOrderLines)){
  TaskSummaryView(title: "Total Lines", color: .blue, icon: "list.dash", value: warehouseOrderLineController.warehouseOrderLines.count)
  }

but now since there is a NavigationView inside another NavigationView, I end up having 2 navigation bars on top.

Is there a way to use the NavigationLink without embedding it in another NaviagationView or to navigate to another view by NOT using the NavigationLink and something like .sheet (I don't want to display the new view as modal!).

Below the complete sample code for testing:

//
//  ContentView.swift
//  Two Navbars
//
//  Created by Max on 2020-02-05.
//  Copyright © 2020 Max. All rights reserved.
//

import SwiftUI

struct ContentView: View {
  var body: some View {
  NavigationView{
  ScrollView{
  VStack{
  NavigationLink(destination: ListView1()){
  Text("Tap me")
  }

  Text("Nothing here")
  }
  }
  }
  }
}

struct ListView1: View {

  var body: some View {
  List{
  NavigationLink(destination: DetailView1()){
  Text("Tap me one more time")
  }

  Text("Item 2")
  Text("Item 3")
  }
  }
}

struct DetailView1: View {

  var body: some View {
  NavigationView{
  ScrollView() {
  VStack{
  NavigationLink(destination: DetailView2()){
  Text("Drill down more")
  }
  Text("Nothing here")
  }
  }
  }
  }
}

struct DetailView2: View {

  var body: some View {
  List {
  Text("That's it")
  Text("Nothing here")
  }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
  ContentView()
  }
}

Body:
You only need 1 NavigationView at the root View. Remove the one in DetailView1.

struct DetailView1: View {
    var body: some View {
        ScrollView(){
            VStack {
                NavigationLink(destination: DetailView2()){
                    Text("Drill down more")
                }
                Text("Nothing here")
            }
         }
      }
  }
}


问:
What is the difference between a pull request by a collaborator and contributor in GitHub?
what is the difference between a pull request by a collaborator and contributor in GitHub? I don't find any special privileges for collaborators.</p>

答:
The one special privilege a collaborator has over a contributor is... that they (the collaborator) can push directly to your repository (since you have added them as "collaborator").

They can push their own branch and do a pull request from withi your repo, between their branch and master.

As opposed to a contributor, who has to fork your repository first, and make a pull request from their own fork/branch to your repo/master.


问:
Escaping a forwardslash in a text string regex python
Trying to obtain the numerical value and it appears the forward slash along with the second word boundary if giving me some problems.  Any help would be greatly appreciated.

This is coming from a text file and it should return about a hundred or so values into a list so it needs to be dynamic

```<code>#Here is the text of interest, I am trying to obtain just the numerical value of 268
Average Price/Square Foot\n$268

#I've tried these different methods for escaping the backslash but they are not working
avg_sqft_price = re.findall(r'\bAverage Price\W/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price[\b]/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\B/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\/\bSquare Foot\n$268\n\$(d\*)',data)
</code>```

答:
Forward slash is not a regex metacharacter, and therefore does not require any special handling.  I would use this approach:

```<code>inp = "Average Price/Square Foot\n$268"
num = re.findall(r'\bAverage Price/Square Foot\s*?\$(\d+)\b', inp)[0]
print(num)
</code>```

This prints 268.

Body:
Trying to obtain the numerical value and it appears the forward slash along with the second word boundary if giving me some problems.  Any help would be greatly appreciated.

This is coming from a text file and it should return about a hundred or so values into a list so it needs to be dynamic

#Here is the text of interest, I am trying to obtain just the numerical value of 268
Average Price/Square Foot\n$268

#I've tried these different methods for escaping the backslash but they are not working
avg_sqft_price = re.findall(r'\bAverage Price\W/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price[\b]/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\B/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\/\bSquare Foot\n$268\n\$(d\*)',data)

Body:
Forward slash is not a regex metacharacter, and therefore does not require any special handling.  I would use this approach:

inp = "Average Price/Square Foot\n$268"
num = re.findall(r'\bAverage Price/Square Foot\s*?\$(\d+)\b', inp)[0]
print(num)

This prints 268.


问:
Where is my m2 folder on Mac OS X Mavericks
I cant seem to find the local .m2 folder on Mac OS X mavericks. Ideally it should be at {user.home}/.m2 but I cant seem to find it.

Should I create it?

答:
Go to finder:

Press on keyboard CMD+shift+G .  it will show u a popup like this

Enter path ~/.m2

press enter.


问:
How do I replace the connection string element
I have an issue I cannot seem to solve using XML Transform. My web.config contains the following

```<code><connectionStrings>
    <add name="SQLConnString"
         connectionString="yada yada"
         providerName="System.Data.SQLClient"/>
</connectionStrings>
</code>```

My QA server and above has this

```<code><connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData>
        <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
    </EncryptedData>
</connectionStrings>
</code>```

What task do I use in DevOps to achieve this kind of transform or what's the best way to go about this kind of transformation.

jc

答:
Not sure the exactly caused you mentioned is what, but you can use File transform task to achieve the above transformation. I have tested it again and it work very fine on my side.

```<code>steps:
- task: FileTransform@1
  displayName: 'File Transform: '
  inputs:
    folderPath: '$(System.DefaultWorkingDirectory)'
    enableXmlTransform: true
    xmlTransformationRules: '-transform **\*.Dev.config -xml **\*.config'
    fileType: xml
</code>```

For the rules syntax in this task definition, please follow:

```<code>-transform <path to the transform file> -xml <path to the source file> -result <path to the result file>
</code>```

In your scenario, you need also ensure your transform file is configured available. Before run it in azure devops pipeline, you can verify it firstly here.

Updated in 2/20/2020:

Based on your comments, the trouble for you to apply file transform is on transforma file configured. Though you have got the method of powershell, but I also help you written a transform file so that you can have more choice here.

```<code><connectionStrings xdt:Transform="Remove">
  <add name="SQLConnString"
       connectionString="yada yada"
       providerName="System.Data.SQLClient" />
</connectionStrings>

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider" xdt:Transform="Insert">
  <EncryptedData>
        <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" xdt:Transform="Replace"/>
    </EncryptedData>
</connectionStrings>
</code>```

You can see my transformation result:

Body:
I have an issue I cannot seem to solve using XML Transform. My web.config contains the following

<connectionStrings>
    <add name="SQLConnString"
         connectionString="yada yada"
         providerName="System.Data.SQLClient"/>
</connectionStrings>

My QA server and above has this

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData>
        <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
    </EncryptedData>
</connectionStrings>

What task do I use in DevOps to achieve this kind of transform or what's the best way to go about this kind of transformation.

jc

Body:
Not sure the exactly caused you mentioned is what, but you can use File transform task to achieve the above transformation. I have tested it again and it work very fine on my side.

steps:
- task: FileTransform@1
  displayName: 'File Transform: '
  inputs:
    folderPath: '$(System.DefaultWorkingDirectory)'
    enableXmlTransform: true
    xmlTransformationRules: '-transform **\*.Dev.config -xml **\*.config'
    fileType: xml

For the rules syntax in this task definition, please follow:

-transform <path to the transform file> -xml <path to the source file> -result <path to the result file>

In your scenario, you need also ensure your transform file is configured available. Before run it in azure devops pipeline, you can verify it firstly here.

Updated in 2/20/2020:

Based on your comments, the trouble for you to apply file transform is on transforma file configured. Though you have got the method of powershell, but I also help you written a transform file so that you can have more choice here.

<connectionStrings xdt:Transform="Remove">
  <add name="SQLConnString"
       connectionString="yada yada"
       providerName="System.Data.SQLClient" />
</connectionStrings>

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider" xdt:Transform="Insert">
  <EncryptedData>
        <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" xdt:Transform="Replace"/>
    </EncryptedData>
</connectionStrings>

You can see my transformation result:


问:
Modify .htaccess for Codeigniter | Subdomain | Many sub folders
My query is as following:

On my server, I have multiple codeigniter apps in one folder and 1 subdomain pointing to that folder

Please see the following structure:

eApps (Main Folder)

index.php (used to redirect to Main App) File

Main App (Used for redirecting to other apps) (Sub Folder)

Timekeeping App (Sub Folder)

Activity Delivery App (Sub Folder)

.....so on (15 Apps in total) (Sub Folders)

The main app redirects to other apps by having a common session. This is working perfectly fine on the local server

But on the live server (1and1.co.uk), it has the following problems:

This is due to improper (htaccess) I think:

I don't know what htaccess files to keep in the main folder and what in each folders in order for this to work properly

Sometimes it gives 404 page not found error as well

This is the .htaccess in the main folder:

答:
I also have many app in one folder in my server and for all .htaccess file I use the following code which works fine for me.
Try replacing the following code in your .htaccess:</p>

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|assets|images|js|css|uploads|fevicon.png)
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]
</code>```

Body:
I also have many app in one folder in my server and for all .htaccess file I use the following code which works fine for me.
Try replacing the following code in your .htaccess:

RewriteEngine on
RewriteCond $1 !^(index\.php|assets|images|js|css|uploads|fevicon.png)
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]


问:
Match rows in a panda dataframe based on values in two columns
I have a pandas dataframe df with about half a million rows.
The columns are ['in','out'].
I need to find whether for each row i there is another row j that matches it. The condition for the match is:

```<code>df.in[i] == df.out[j]  and df.out[i] == df.in[j]
</code>```

I've implemented it as a for loop:

for i, row in df.iterrows():
    match_row = (d.out == row['in']) & (df.in == row['out'])
    if len(df[match_row].value) > 0:
        #do something
```
<p>As Nick Becker suggested, here is a small sample data:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'in':[10,20,30,40,50,60], 'out':[20,10,40,30,70,80]})
</code>```
```<code>    in  out
0   10  20
1   20  10
2   30  40
3   40  30
4   50  70
5   60  80
</code>```

I need to match row 0 with row 1 and row 2 with row 3.
I wonder if there is a more efficient way to do it without using a for loop.

[UPDATE]
Since there are some suggestions (thank you) on how to solve this problem, I'd like to post here what I expect to get. Here is the code and the output:

matches = []
for i, row in df.iterrows():
    match_row = (df['out'] == row['in']) & (df['in'] == row['out'])
    if len(df[match_row]) > 0:
        matches.append((i, df[match_row].index[0],row['in'], row['out'] ))
pd.DataFrame(matches, columns = ['row', 'match row', 'in','out'])
    row matching_row    in  out
0   0   1               10  20
1   1   0               20  10
2   2   3               30  40
3   3   2               40  30
```

I can do some clean up to remove duplication, but this is basically what I'm looking for. Is it an inherently sequential problem and there is nothing I can do about it?

答:
I used the following on your simple sample data, isn't this what you are looking for?

```<code>df['in-in-out'] = df['in'].isin(df['out'])
df['out-in-in'] = df['out'].isin(df['in'])
df['and'] = df['in-in-out'] & df['out-in-in']
df = df.drop(['in-in-out', 'out-in-in'], axis=1)
df = df[df['and']]
df = df.drop(['and'], axis=1)
</code>```

The output is

```<code>    in  out
0   10  20
1   20  10
2   30  40
3   40  30
</code>```

Of course I have added extra columns and dropped them for clarity so you can see how the dataframe is being modified at each step.

Body:
I have a pandas dataframe df with about half a million rows.
The columns are ['in','out'].
I need to find whether for each row i there is another row j that matches it. The condition for the match is:

df.in[i] == df.out[j]  and df.out[i] == df.in[j]

I've implemented it as a for loop:

for i, row in df.iterrows():
    match_row = (d.out == row['in']) & (df.in == row['out'])
    if len(df[match_row].value) > 0:
        #do something

As Nick Becker suggested, here is a small sample data:

df = pd.DataFrame({'in':[10,20,30,40,50,60], 'out':[20,10,40,30,70,80]})

    in  out
0   10  20
1   20  10
2   30  40
3   40  30
4   50  70
5   60  80

I need to match row 0 with row 1 and row 2 with row 3.
I wonder if there is a more efficient way to do it without using a for loop.

[UPDATE]
Since there are some suggestions (thank you) on how to solve this problem, I'd like to post here what I expect to get. Here is the code and the output:

matches = []
for i, row in df.iterrows():
    match_row = (df['out'] == row['in']) & (df['in'] == row['out'])
    if len(df[match_row]) > 0:
        matches.append((i, df[match_row].index[0],row['in'], row['out'] ))
pd.DataFrame(matches, columns = ['row', 'match row', 'in','out'])
    row matching_row    in  out
0   0   1               10  20
1   1   0               20  10
2   2   3               30  40
3   3   2               40  30

I can do some clean up to remove duplication, but this is basically what I'm looking for. Is it an inherently sequential problem and there is nothing I can do about it?

Body:
I used the following on your simple sample data, isn't this what you are looking for?

df['in-in-out'] = df['in'].isin(df['out'])
df['out-in-in'] = df['out'].isin(df['in'])
df['and'] = df['in-in-out'] & df['out-in-in']
df = df.drop(['in-in-out', 'out-in-in'], axis=1)
df = df[df['and']]
df = df.drop(['and'], axis=1)

The output is

    in  out
0   10  20
1   20  10
2   30  40
3   40  30

Of course I have added extra columns and dropped them for clarity so you can see how the dataframe is being modified at each step.


问:
what's wrong with this async wireup of an axios get()?
I had a function in my React component which encapsulated an axios call to return supporting data.  I created a new component named ApiFacade to encapsulate axios calls.  I'm trying to call a function to return data from a function in ApiFacade to the main component.  Here's the code where I'm calling the function in ApiFacade:

```<code>async componentDidMount(){
    const suppliers = await ApiFacade.getSuppliersDropdownData();
    debugger;
}
</code>```

Here's the function in ApiFacade:

```<code>static async getSuppliersDropdownData(){
    let axiosConfig = {
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials':true
        }
      }

    const url = apiFacadeConfig.baseUrl + "suppliers-dropdown";
    axios.get(url, axiosConfig)
      .then(function(response){
          let suppliers = response.data[0];
          let defaultSupplier = [{ SupplierId:0, ContactFirstName:''}];
          suppliers = [...defaultSupplier, ...suppliers];
          return suppliers;
      })
      .catch(function (error) {
          alert('bubble: ' + error.message);
      });
</code>```

The ApiFacade function is getting called without error.  The control flow enters into the then() block indicating success, and the catch block does not get entered.  The "suppliers" variable gets populated with data as expected.  The problem is that suppliers shows as "undefined" on the line after the ApiFacade function call in componentDidMount().  Then the CDT debugger hits a breakpoint within the ApiFacade function call.  What do I need to change with this implementation so that suppliers gets returned to the call from componentDidMount() in the expected sequence?

答:
My guess:

```<code>return axios.get(url, axiosConfig)
</code>```

instead of

```<code>axios.get(url, axiosConfig)
</code>```

in getSuppliersDropdownData()

Body:
I had a function in my React component which encapsulated an axios call to return supporting data.  I created a new component named ApiFacade to encapsulate axios calls.  I'm trying to call a function to return data from a function in ApiFacade to the main component.  Here's the code where I'm calling the function in ApiFacade:

async componentDidMount(){
    const suppliers = await ApiFacade.getSuppliersDropdownData();
    debugger;
}

Here's the function in ApiFacade:

static async getSuppliersDropdownData(){
    let axiosConfig = {
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials':true
        }
      }

    const url = apiFacadeConfig.baseUrl + "suppliers-dropdown";
    axios.get(url, axiosConfig)
      .then(function(response){
          let suppliers = response.data[0];
          let defaultSupplier = [{ SupplierId:0, ContactFirstName:''}];
          suppliers = [...defaultSupplier, ...suppliers];
          return suppliers;
      })
      .catch(function (error) {
          alert('bubble: ' + error.message);
      });

The ApiFacade function is getting called without error.  The control flow enters into the then() block indicating success, and the catch block does not get entered.  The "suppliers" variable gets populated with data as expected.  The problem is that suppliers shows as "undefined" on the line after the ApiFacade function call in componentDidMount().  Then the CDT debugger hits a breakpoint within the ApiFacade function call.  What do I need to change with this implementation so that suppliers gets returned to the call from componentDidMount() in the expected sequence?

Body:
My guess:

return axios.get(url, axiosConfig)

instead of

axios.get(url, axiosConfig)

in getSuppliersDropdownData()


问:
When using AWS EMR Step Spark-Submit how to get it to accept a path with a space
I am trying to use from the AWS Console EMR steps with a space in the path but for some reason spark-submit does something odd and does not work when a space is introduced.

Command

```<code>spark-submit "s3://bucket/prefix with spaces/stepCode.py"
spark-submit 's3://bucket/prefix with spaces/stepCode.py'
spark-submit s3://bucket/prefix%with%spaces/stepCode.py
</code>```

Error from AWS

```<code>python: can't open file '/mnt/var/lib/hadoop/steps/s-3XXXXXXXXXXXX/s3:/bucket/prefix with spaces/stepCode.py': [Errno 2] No such file or directory
</code>```

However this works

```<code>spark-submit s3://bucket/nospaces/stepCode.py
</code>```

and the code is dumped to the below somehow

```<code>/mnt/tmp/spark-XXXXXX-XXXXXXXX-XXXXXXX-XXXXXXX/stepCode.py
</code>```

Any idea on how get spark-submit to accept a path with a space in it?
Thanks

答:
Try by escaping spaces with backslash \

```<code>spark-submit s3://bucket/prefix\ with\ spaces/stepCode.py
</code>```

Body:
I am trying to use from the AWS Console EMR steps with a space in the path but for some reason spark-submit does something odd and does not work when a space is introduced.

Command

spark-submit "s3://bucket/prefix with spaces/stepCode.py"
spark-submit 's3://bucket/prefix with spaces/stepCode.py'
spark-submit s3://bucket/prefix%with%spaces/stepCode.py

Error from AWS

python: can't open file '/mnt/var/lib/hadoop/steps/s-3XXXXXXXXXXXX/s3:/bucket/prefix with spaces/stepCode.py': [Errno 2] No such file or directory

However this works

spark-submit s3://bucket/nospaces/stepCode.py

and the code is dumped to the below somehow

/mnt/tmp/spark-XXXXXX-XXXXXXXX-XXXXXXX-XXXXXXX/stepCode.py

Any idea on how get spark-submit to accept a path with a space in it?
Thanks

Body:
Try by escaping spaces with backslash \

spark-submit s3://bucket/prefix\ with\ spaces/stepCode.py


问:
How to clear text field before sending keys selenium c#
I'm writing a simple selenium test which sends an incorrect string of letters then submits and returns and error. I want to then send a string of letter but this time with the correct string so it is accepted.

The issue i'm facing in my test is as the first set of string is already in the text field, so when i go to the submit the second one it adds it on to the first string that has already been submitted.

So what i essentially need to do is send the first string of letters then need to clear the text field then send the second string of letters.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;

namespace Exercise1
{
    class RunPath
    {

            static void Main()
            {

                IWebDriver webDriver = new ChromeDriver();
                webDriver.Navigate().GoToUrl("https://energy.gocompare.com/gas-electricity");
                webDriver.Manage().Window.Maximize();

            String title = webDriver.Title;

            String expectedTitle = "Utilities from Go Compare";
            if (title.Contains(expectedTitle))
            {
                Console.WriteLine("Tile is matching with expected value");
            }
            else
            {
                Console.WriteLine("Tile is matching with expected value");
            }

            webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

            webDriver.FindElement(By.XPath(".//input[@type = 'text']")).SendKeys("W30PN#");

            webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

            // I need a piece of code here so that before i send the second string of keys the text field is clear

            webDriver.FindElement(By.XPath(".//input[@type = 'text']")).SendKeys("W30PN");

            webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

            // webDriver.Quit();

        }

        }

    }
</code>```

答:
The clear command can be used to clear the element before entering any key in the text field

```<code>webDriver.FindElement(By.XPath("{Locator}")).Clear();
webDriver.FindElement(By.XPath("{Locator}")).SendKeys("{YOUR_KEY}");
</code>```

surround this statement with try catch in order to catch and handle any selenium related exception

Body:
I'm writing a simple selenium test which sends an incorrect string of letters then submits and returns and error. I want to then send a string of letter but this time with the correct string so it is accepted.

The issue i'm facing in my test is as the first set of string is already in the text field, so when i go to the submit the second one it adds it on to the first string that has already been submitted.

So what i essentially need to do is send the first string of letters then need to clear the text field then send the second string of letters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;

namespace Exercise1
{
    class RunPath
    {

            static void Main()
            {

                IWebDriver webDriver = new ChromeDriver();
                webDriver.Navigate().GoToUrl("https://energy.gocompare.com/gas-electricity");
                webDriver.Manage().Window.Maximize();

            String title = webDriver.Title;

            String expectedTitle = "Utilities from Go Compare";
            if (title.Contains(expectedTitle))
            {
                Console.WriteLine("Tile is matching with expected value");
            }
            else
            {
                Console.WriteLine("Tile is matching with expected value");
            }

            webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

            webDriver.FindElement(By.XPath(".//input[@type = 'text']")).SendKeys("W30PN#");

            webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

            // I need a piece of code here so that before i send the second string of keys the text field is clear

            webDriver.FindElement(By.XPath(".//input[@type = 'text']")).SendKeys("W30PN");

            webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

            // webDriver.Quit();

        }

        }

    }

Body:
The clear command can be used to clear the element before entering any key in the text field

webDriver.FindElement(By.XPath("{Locator}")).Clear();
webDriver.FindElement(By.XPath("{Locator}")).SendKeys("{YOUR_KEY}");

surround this statement with try catch in order to catch and handle any selenium related exception


问:
How to add custom action on back button in apple WatchKit app in swift?
In our Apple Watch swift application we have two controllers(Login and dashboard controller). After login user will land to dashboard page and after clicking on back button it is again landing to login page.
So, my requirement is that after clicking on back button on dashboard it should stay on same dashboard page.

So, How can I prevent back action and assign custom action once back button clicked in apple WatchKit application?

答:
I think what you might be looking for is to call reloadRootPageControllers on WKInterfaceController:

https://developer.apple.com/documentation/watchkit/wkinterfacecontroller/2868441-reloadrootpagecontrollers

after successful login, and re-initialise your app's UI with the dashboard screen. This makes it impossible to go back to the login screen, and there will be no back button as the dashboard becomes the new root level app screen.

Hope this helps.


问:
Is there a built-in Python function or module that will sum digits multiplied by their integer weight?
What I need to do is take a 10-digit ISBN number and check if it's valid, according to this rule:

According to the 2001 edition of the International ISBN Agency's official user manual,[47] the ISBN-10 check digit (which is the last digit of the 10-digit ISBN) must range from 0 to 10 (the symbol 'X' is used for 10), and must be such that the sum of the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.

In other words, if the number is 0-306-40615-2, I need to calculate:

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1) mod 11

While suggestions or hints on how to write such a function are welcome, my main question is simply whether Python already has a way of doing this, perhaps in the math module.

This is my attempt, but the for loops don't work because the inner one keeps starting over. Plus it just seems messy!

```<code>    checksum = 0
    for digit in isbn:
        for weight in range(10, 0, -1):
            if digit == 'X':
                checksum += 10 * weight
                break
            checksum += int(digit) * weight
            break
    return checksum % 11```
```

答:
You can use a list comprehension and enunerate() to get the position and value of the first 9 digits.  For each digit, transform the position into its reversed equivalent (10-i) and multiply it by the digit. If you subtract the sum of these multiplications from 990 you will get a value that will make the total a multiple of 11. The result can then be used as an index in a string containing digits 0 to 9 and letter X:

```<code>isbn     = "0-306-40615-2"
numbers  = [int(n) for n in isbn if n.isdigit()]
check    = "0123456789X"[ (990-sum(n*(10-i) for i,n in enumerate(numbers[:9])))%11]
isValid  = isbn[-1] == check

print(check) # "2"
</code>```

Body:
What I need to do is take a 10-digit ISBN number and check if it's valid, according to this rule:

According to the 2001 edition of the International ISBN Agency's official user manual,[47] the ISBN-10 check digit (which is the last digit of the 10-digit ISBN) must range from 0 to 10 (the symbol 'X' is used for 10), and must be such that the sum of the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.

In other words, if the number is 0-306-40615-2, I need to calculate:

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1) mod 11

While suggestions or hints on how to write such a function are welcome, my main question is simply whether Python already has a way of doing this, perhaps in the math module.

This is my attempt, but the for loops don't work because the inner one keeps starting over. Plus it just seems messy!

    checksum = 0
    for digit in isbn:
        for weight in range(10, 0, -1):
            if digit == 'X':
                checksum += 10 * weight
                break
            checksum += int(digit) * weight
            break
    return checksum % 11```

Body:
You can use a list comprehension and enunerate() to get the position and value of the first 9 digits.  For each digit, transform the position into its reversed equivalent (10-i) and multiply it by the digit. If you subtract the sum of these multiplications from 990 you will get a value that will make the total a multiple of 11. The result can then be used as an index in a string containing digits 0 to 9 and letter X:

isbn     = "0-306-40615-2"
numbers  = [int(n) for n in isbn if n.isdigit()]
check    = "0123456789X"[ (990-sum(n*(10-i) for i,n in enumerate(numbers[:9])))%11]
isValid  = isbn[-1] == check

print(check) # "2"


问:
In Python Panda: Best way to reverse dataframe column values where col1 > col2
I have a solution, but it uses a for loop and I am looking for a better/ more elegant way to swap Col1 and Col2 values when Col1 > Col2.

Current Solution:
In 2 for loops:
  Finds Rows where Col1 > Col2
  Then adds row Col2 Col1 Score
Afterwards all rows where Col1 > Col2 are dropped. This only took 2 lines.
Is there a better way to swap the Col1 and Col2 values?

import pandas as pd
def drop_all_revd_in_df(df):
    indexNames = df[ (df['col1'] > df['col2'])].index
    df.drop(indexNames , inplace=True)
    return df

# for loops  to check if col1 > col2 and reverse order
def col1GTcol2CleanUp(df):
    col1A_prev = ''
    for col1A in df['col1'] :
        if col1A != col1A_prev :
            col1A_prev = col1A
            for col1B in df[df['col1'] == col1A]['col2']:
                if (col1A > col1B) :
                    score = (df[ (df['col1'] == col1A) & (df['col2'] == col1B)].score).to_frame()['score'].iloc[0]
                    df =  df.append({'col1' : col1B , 'col2' : col1A ,'score' : score}, ignore_index=True)
    df = drop_all_revd_in_df(df)
    return df

# initialize list of lists
dataShort = [["Andy", "Claude", 15],
             ["Vincent", "Frida", 12],  # NOT OK
             ["Vincent", "Pablo", 11]]  # NOT OK

# Create the pandas DataFrame
df = pd.DataFrame(dataShort, columns = ['col1', 'col2', 'score'])
print(df)

col1GTcol2CleanUp(df).sort_values(['col1','col2']).reset_index(drop='True')
```

```Output:
      col1    col2  score
0     Andy  Claude     15
1  Vincent   Frida     12
2  Vincent   Pablo     11

Out[1]:
    col1    col2    score
0   Andy    Claude  15
1   Frida   Vincent 12
2   Pablo   Vincent 11
```

答:
Is this what you are looking for ?
'May' be done through lambda as well - for simplicity, I have put the logic in a separate function.

```<code>df = pd.DataFrame({'col1':['Andy','Vincent','Vincent'], 'col2':['Claude','Frida','Pablo'], 'score':[15,12,11]})
df
</code>```

Original / input dataframe:

Code to achieve desired o/p:

```<code>def check_row(row):
    if row['col1'] > row['col2']:
        row['col1'],row['col2'] = row['col2'],row['col1']
        return row
    else:
        return row
df = df.apply(check_row, axis =1)
df
</code>```

O/P:

Body:
I have a solution, but it uses a for loop and I am looking for a better/ more elegant way to swap Col1 and Col2 values when Col1 > Col2.

Current Solution:
In 2 for loops:
  Finds Rows where Col1 > Col2
  Then adds row Col2 Col1 Score
Afterwards all rows where Col1 > Col2 are dropped. This only took 2 lines.
Is there a better way to swap the Col1 and Col2 values?

import pandas as pd
def drop_all_revd_in_df(df):
    indexNames = df[ (df['col1'] > df['col2'])].index
    df.drop(indexNames , inplace=True)
    return df

# for loops  to check if col1 > col2 and reverse order
def col1GTcol2CleanUp(df):
    col1A_prev = ''
    for col1A in df['col1'] :
        if col1A != col1A_prev :
            col1A_prev = col1A
            for col1B in df[df['col1'] == col1A]['col2']:
                if (col1A > col1B) :
                    score = (df[ (df['col1'] == col1A) & (df['col2'] == col1B)].score).to_frame()['score'].iloc[0]
                    df =  df.append({'col1' : col1B , 'col2' : col1A ,'score' : score}, ignore_index=True)
    df = drop_all_revd_in_df(df)
    return df

# initialize list of lists
dataShort = [["Andy", "Claude", 15],
             ["Vincent", "Frida", 12],  # NOT OK
             ["Vincent", "Pablo", 11]]  # NOT OK

# Create the pandas DataFrame
df = pd.DataFrame(dataShort, columns = ['col1', 'col2', 'score'])
print(df)

col1GTcol2CleanUp(df).sort_values(['col1','col2']).reset_index(drop='True')

Output:
      col1    col2  score
0     Andy  Claude     15
1  Vincent   Frida     12
2  Vincent   Pablo     11

Out[1]:
    col1    col2    score
0   Andy    Claude  15
1   Frida   Vincent 12
2   Pablo   Vincent 11

Body:
Is this what you are looking for ?
'May' be done through lambda as well - for simplicity, I have put the logic in a separate function.

df = pd.DataFrame({'col1':['Andy','Vincent','Vincent'], 'col2':['Claude','Frida','Pablo'], 'score':[15,12,11]})
df

Original / input dataframe:

Code to achieve desired o/p:

def check_row(row):
    if row['col1'] > row['col2']:
        row['col1'],row['col2'] = row['col2'],row['col1']
        return row
    else:
        return row
df = df.apply(check_row, axis =1)
df

O/P:


问:
Cut out a sequence of files using glob in python
I have a directory with files like img-0001.jpg, img-0005.pg, img-0006.jpg, ... , img-xxxx.jpg.
What I need to do is to get a list with all files starting at 0238, literally img-0238.jpg. The next existing filename is img-0240.jpg

Right now I use glob to get all filenames.

```<code>list_images = glob.glob(path_images + "*.jpg")
</code>```

Thanks in advance

Edit:

-> The last filename is img-0315.jpg

答:
For something like this, you could try the wcmatch library. It's a library that aims to enhance file globbing and wildcard matching.

In this example, we enable brace expansion and demonstrate the pattern by filtering a list of files:

```<code>from wcmatch import glob

files = []
# Generate list of files from img-0000.jpg to img-0315.jpg
for x in range(316):
    files.append('path/img-{:04d}.jpg'.format(x))

print(glob.globfilter(files, 'path/img-{0238..0315}.jpg', flags=glob.BRACE))
</code>```

And we get the following output:

```<code>['path/img-0238.jpg', 'path/img-0239.jpg', 'path/img-0240.jpg', 'path/img-0241.jpg', 'path/img-0242.jpg', 'path/img-0243.jpg', 'path/img-0244.jpg', 'path/img-0245.jpg', 'path/img-0246.jpg', 'path/img-0247.jpg', 'path/img-0248.jpg', 'path/img-0249.jpg', 'path/img-0250.jpg', 'path/img-0251.jpg', 'path/img-0252.jpg', 'path/img-0253.jpg', 'path/img-0254.jpg', 'path/img-0255.jpg', 'path/img-0256.jpg', 'path/img-0257.jpg', 'path/img-0258.jpg', 'path/img-0259.jpg', 'path/img-0260.jpg', 'path/img-0261.jpg', 'path/img-0262.jpg', 'path/img-0263.jpg', 'path/img-0264.jpg', 'path/img-0265.jpg', 'path/img-0266.jpg', 'path/img-0267.jpg', 'path/img-0268.jpg', 'path/img-0269.jpg', 'path/img-0270.jpg', 'path/img-0271.jpg', 'path/img-0272.jpg', 'path/img-0273.jpg', 'path/img-0274.jpg', 'path/img-0275.jpg', 'path/img-0276.jpg', 'path/img-0277.jpg', 'path/img-0278.jpg', 'path/img-0279.jpg', 'path/img-0280.jpg', 'path/img-0281.jpg', 'path/img-0282.jpg', 'path/img-0283.jpg', 'path/img-0284.jpg', 'path/img-0285.jpg', 'path/img-0286.jpg', 'path/img-0287.jpg', 'path/img-0288.jpg', 'path/img-0289.jpg', 'path/img-0290.jpg', 'path/img-0291.jpg', 'path/img-0292.jpg', 'path/img-0293.jpg', 'path/img-0294.jpg', 'path/img-0295.jpg', 'path/img-0296.jpg', 'path/img-0297.jpg', 'path/img-0298.jpg', 'path/img-0299.jpg', 'path/img-0300.jpg', 'path/img-0301.jpg', 'path/img-0302.jpg', 'path/img-0303.jpg', 'path/img-0304.jpg', 'path/img-0305.jpg', 'path/img-0306.jpg', 'path/img-0307.jpg', 'path/img-0308.jpg', 'path/img-0309.jpg', 'path/img-0310.jpg', 'path/img-0311.jpg', 'path/img-0312.jpg', 'path/img-0313.jpg', 'path/img-0314.jpg', 'path/img-0315.jpg']
</code>```

So, we could apply this to a file search:

```<code>from wcmatch import glob

list_images = glob.glob('path/img-{0238..0315}.jpg', flags=glob.BRACE)
</code>```

In this example, we've hard coded the path, but in your example, make sure path_images has a trailing / so that the pattern is constructed correctly. Others have suggested this might be an issue. Print out your pattern to confirm the pattern is correct.

Body:
I have a directory with files like img-0001.jpg, img-0005.pg, img-0006.jpg, ... , img-xxxx.jpg.
What I need to do is to get a list with all files starting at 0238, literally img-0238.jpg. The next existing filename is img-0240.jpg

Right now I use glob to get all filenames.

list_images = glob.glob(path_images + "*.jpg")

Thanks in advance

Edit:

-> The last filename is img-0315.jpg

Body:
For something like this, you could try the wcmatch library. It's a library that aims to enhance file globbing and wildcard matching.

In this example, we enable brace expansion and demonstrate the pattern by filtering a list of files:

from wcmatch import glob

files = []
# Generate list of files from img-0000.jpg to img-0315.jpg
for x in range(316):
    files.append('path/img-{:04d}.jpg'.format(x))

print(glob.globfilter(files, 'path/img-{0238..0315}.jpg', flags=glob.BRACE))

And we get the following output:

['path/img-0238.jpg', 'path/img-0239.jpg', 'path/img-0240.jpg', 'path/img-0241.jpg', 'path/img-0242.jpg', 'path/img-0243.jpg', 'path/img-0244.jpg', 'path/img-0245.jpg', 'path/img-0246.jpg', 'path/img-0247.jpg', 'path/img-0248.jpg', 'path/img-0249.jpg', 'path/img-0250.jpg', 'path/img-0251.jpg', 'path/img-0252.jpg', 'path/img-0253.jpg', 'path/img-0254.jpg', 'path/img-0255.jpg', 'path/img-0256.jpg', 'path/img-0257.jpg', 'path/img-0258.jpg', 'path/img-0259.jpg', 'path/img-0260.jpg', 'path/img-0261.jpg', 'path/img-0262.jpg', 'path/img-0263.jpg', 'path/img-0264.jpg', 'path/img-0265.jpg', 'path/img-0266.jpg', 'path/img-0267.jpg', 'path/img-0268.jpg', 'path/img-0269.jpg', 'path/img-0270.jpg', 'path/img-0271.jpg', 'path/img-0272.jpg', 'path/img-0273.jpg', 'path/img-0274.jpg', 'path/img-0275.jpg', 'path/img-0276.jpg', 'path/img-0277.jpg', 'path/img-0278.jpg', 'path/img-0279.jpg', 'path/img-0280.jpg', 'path/img-0281.jpg', 'path/img-0282.jpg', 'path/img-0283.jpg', 'path/img-0284.jpg', 'path/img-0285.jpg', 'path/img-0286.jpg', 'path/img-0287.jpg', 'path/img-0288.jpg', 'path/img-0289.jpg', 'path/img-0290.jpg', 'path/img-0291.jpg', 'path/img-0292.jpg', 'path/img-0293.jpg', 'path/img-0294.jpg', 'path/img-0295.jpg', 'path/img-0296.jpg', 'path/img-0297.jpg', 'path/img-0298.jpg', 'path/img-0299.jpg', 'path/img-0300.jpg', 'path/img-0301.jpg', 'path/img-0302.jpg', 'path/img-0303.jpg', 'path/img-0304.jpg', 'path/img-0305.jpg', 'path/img-0306.jpg', 'path/img-0307.jpg', 'path/img-0308.jpg', 'path/img-0309.jpg', 'path/img-0310.jpg', 'path/img-0311.jpg', 'path/img-0312.jpg', 'path/img-0313.jpg', 'path/img-0314.jpg', 'path/img-0315.jpg']

So, we could apply this to a file search:

from wcmatch import glob

list_images = glob.glob('path/img-{0238..0315}.jpg', flags=glob.BRACE)

In this example, we've hard coded the path, but in your example, make sure path_images has a trailing / so that the pattern is constructed correctly. Others have suggested this might be an issue. Print out your pattern to confirm the pattern is correct.


问:
npm not working after clearing cache
Before clearing cache

```<code>npm cache clear
</code>```

npm is working fine. After clearing cache, it is not working.
The error log below suggest problem with internet connectivity but internet connection is just fine.
This problem does not only happen for bower but for any modules.

Here's the output of process:

```<code>> sudo npm install -g bower Password: npm http GET
> https://registry.npmjs.org/bower npm http GET
> https://registry.npmjs.org/bower npm http GET
> https://registry.npmjs.org/bower npm ERR! network connect ETIMEDOUT
> npm ERR! network This is most likely not a problem with npm itself npm
> ERR! network and is related to network connectivity. npm ERR! network
> In most cases you are behind a proxy or have bad network settings. npm
> ERR! network npm ERR! network If you are behind a proxy, please make
> sure that the npm ERR! network 'proxy' config is set properly.  See:
> 'npm help config'
>
> npm ERR! System Darwin 12.5.0 npm ERR! command
> "/usr/local/Cellar/node/0.10.16/bin/node" "/usr/local/bin/npm"
> "install" "-g" "bower" npm ERR! cwd /Users/username npm ERR!
> node -v v0.10.16 npm ERR! npm -v 1.3.8 npm ERR! syscall connect npm
> ERR! code ETIMEDOUT npm ERR! errno ETIMEDOUT npm ERR! npm ERR!
> Additional logging details can be found in: npm ERR!
> /Users/username/npm-debug.log npm ERR! not ok code 0
</code>```

答:
Try npm cache clean --force if it doesn't work then manually delete %appdata%\npm-cache folder.

and install npm install npm@latest -g

It worked for me.

visit this link

Title: npm not working after clearing cache

Body:
Before clearing cache

npm cache clear

npm is working fine. After clearing cache, it is not working.
The error log below suggest problem with internet connectivity but internet connection is just fine.
This problem does not only happen for bower but for any modules.

Here's the output of process:

> sudo npm install -g bower Password: npm http GET
> https://registry.npmjs.org/bower npm http GET
> https://registry.npmjs.org/bower npm http GET
> https://registry.npmjs.org/bower npm ERR! network connect ETIMEDOUT
> npm ERR! network This is most likely not a problem with npm itself npm
> ERR! network and is related to network connectivity. npm ERR! network
> In most cases you are behind a proxy or have bad network settings. npm
> ERR! network npm ERR! network If you are behind a proxy, please make
> sure that the npm ERR! network 'proxy' config is set properly.  See:
> 'npm help config'
>
> npm ERR! System Darwin 12.5.0 npm ERR! command
> "/usr/local/Cellar/node/0.10.16/bin/node" "/usr/local/bin/npm"
> "install" "-g" "bower" npm ERR! cwd /Users/username npm ERR!
> node -v v0.10.16 npm ERR! npm -v 1.3.8 npm ERR! syscall connect npm
> ERR! code ETIMEDOUT npm ERR! errno ETIMEDOUT npm ERR! npm ERR!
> Additional logging details can be found in: npm ERR!
> /Users/username/npm-debug.log npm ERR! not ok code 0


问:
How to create a list in Python that will yield the following result []
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

```<code>new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)
</code>```

My output:

```<code>[['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

But here is the expected output:

```<code>['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

Please why am I not getting the expected output?

答:
You need to start indexing at 8 as The 9th element is at index 8.

```<code>new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]

sub_lst=new_lst[8:8+4]
</code>```

Resulting output will be -

```<code>['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

Body:
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)

My output:

[['water', 'air', 'fire', 'earth'], 'games', 2.7]

But here is the expected output:

['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]

Please why am I not getting the expected output?

Body:
You need to start indexing at 8 as The 9th element is at index 8.

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]

sub_lst=new_lst[8:8+4]

Resulting output will be -

['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]


问:
ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist Linux-x86_64 Error: 2: No such file or directory
I am running Oracle 11g on Linux server and one the below Database issues occurred suddenly (every 2 weeks or 3 weeks sometimes):

Some times:
ORA-01034: ORACLE not available ORA-27102: out of memory Linux-x86_64 Error: 12: Cannot allocate memory Additional information: 1 Additional information: 163844 Additional information: 8

And last time:
ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist Linux-x86_64 Error: 2: No such file or directory

When I tried to startup database after setting up SID but I had the below error:
SQL> startup
ORA-00845: MEMORY_TARGET not supported on this system

I rebooted the server then everything is OK

My page size: 4096
kernel.shmall = 4294967296

How can I prevent these issues from happening again? should I update anything in Oracle memory settings?

答:
See, this is what worked for me. My ORACLE_SID, ORACLE_HOME etc., were just fine.

Restart the listener - lsnrctl start

sqlplus /nolog

connect /as sysdba

startup


问:
$(document).ready called inside an external function?
I saw some jquery code on the Net somewhere, that took this form :

```<code><script>
function doSomething(message)
{
    $(document).ready(function(){
        alert(message);
        });
};
</script>
</code>```

i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.

答:
$(document).ready(); essentially registers the function to be executed when the DOM is ready. However in this case, the programmer had nested this in the function. This means that it will not be added to the .ready() until he make an invocation to the function doSomething();

You can try it out with the following:

```<code><script type="text/javascript">
    function doSomething(){
        $(document).ready(function(){
            alert('here');

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

Place this at various parts of your HTML and check it out (:

Cheers!

Body:
I saw some jquery code on the Net somewhere, that took this form :

i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.

Body:
$(document).ready(); essentially registers the function to be executed when the DOM is ready. However in this case, the programmer had nested this in the function. This means that it will not be added to the .ready() until he make an invocation to the function doSomething();

You can try it out with the following:

<script type="text/javascript">
    function doSomething(){
        $(document).ready(function(){
            alert('here');

        });
    }
    doSomething();
</script>

Place this at various parts of your HTML and check it out (:

Cheers!


问:
The Derective has different behavior in hierarchical injectors of different @angualr/cli version(9.0.2 & 8.3.14)
I am learning Hierarchical injectors in Angular doc.

The doc indicates the difference between providers and viewProviders using a <ng-content> example.

The link is enter link description here

But I am confused about adding some content except for component to the <app-child>, just like this:

```<code><app-child>{{flower.emoji}}{{animal.emoji}}<app-inspector></app-inspector></app-child>
</code>```

the result seems that the content just finds ElementInjector in the parent component, although the app-child component has put FlowerService in providers.

why? it's my first question, maybe a small question.

another question occurred when I tried to add a directive in app-child.

I created a new directive and registered FlowerService and AnimalService in its providers.

Just like this:

```<code><app-child appInterceptor>...</app-child>
</code>```

The stackblitz link is enter link description here

Then I couldn't find some rule in the result. I made more experiments with the same code in Angular v9. (the CLI version is v9.0.2.)

The result is different when the code is all the same!

with v9， the result seems that the providers of the directive serve as an interceptor between providers and viewProviders of app-child.

but with v8.3.14...v7.0.0 (CLI version), I found things were different.

Why? (sorry for my poor English...)

答:
For your first question :

<app-child>{{flower.emoji}}{{animal.emoji}}<app-inspector></app-inspector></app-child>
```

You're adding the flower.emoji and animal.emoji code to the app.component.html file, so angular uses the service provided in app.component.ts. As app.component.ts doesn't provide any service and his parent app.module.ts doesn't provide any service either, they use the services provided in root : whale and flower.

In other words: if you displaying a variable in the app.component.ts file he's displaying what was provided to him (whale and flower) he doesn't know what was provided to app-child and should never know (otherwise you're creating coupling between your components which is bad)

For you second question I don't know what to tell you, fork the stackblitz with your directive and I can try to explain what is happening there

Good luck in your learning !

Body:
I am learning Hierarchical injectors in Angular doc.

The doc indicates the difference between providers and viewProviders using a <ng-content> example.

The link is enter link description here

But I am confused about adding some content except for component to the <app-child>, just like this:

<app-child>{{flower.emoji}}{{animal.emoji}}<app-inspector></app-inspector></app-child>

the result seems that the content just finds ElementInjector in the parent component, although the app-child component has put FlowerService in providers.

why? it's my first question, maybe a small question.

another question occurred when I tried to add a directive in app-child.

I created a new directive and registered FlowerService and AnimalService in its providers.

Just like this:

<app-child appInterceptor>...</app-child>

The stackblitz link is enter link description here

Then I couldn't find some rule in the result. I made more experiments with the same code in Angular v9. (the CLI version is v9.0.2.)

The result is different when the code is all the same!

with v9， the result seems that the providers of the directive serve as an interceptor between providers and viewProviders of app-child.

but with v8.3.14...v7.0.0 (CLI version), I found things were different.

Why? (sorry for my poor English...)

Body:
For your first question :

<app-child>{{flower.emoji}}{{animal.emoji}}<app-inspector></app-inspector></app-child>

You're adding the flower.emoji and animal.emoji code to the app.component.html file, so angular uses the service provided in app.component.ts. As app.component.ts doesn't provide any service and his parent app.module.ts doesn't provide any service either, they use the services provided in root : whale and flower.

In other words: if you displaying a variable in the app.component.ts file he's displaying what was provided to him (whale and flower) he doesn't know what was provided to app-child and should never know (otherwise you're creating coupling between your components which is bad)

For you second question I don't know what to tell you, fork the stackblitz with your directive and I can try to explain what is happening there

Good luck in your learning !


问:
How do i call a dictionary value from user input
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

```<code>1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.
</code>```

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

答:
Here, you should do:

```<code>weight = int(input("Enter your Weight: "))

def getScale(weight):
    return {
        1 : 0.5,
        2 : 1.2,
        3 : 1.7,
        4 : 2.4
    }.get(weight, 0.5)

print(getScale(weight))
</code>```

Using the second parameter of get(weight, 0.5), you can define what happens when value entered by user is not in the dict.

Body:
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

Body:
Here, you should do:

weight = int(input("Enter your Weight: "))

def getScale(weight):
    return {
        1 : 0.5,
        2 : 1.2,
        3 : 1.7,
        4 : 2.4
    }.get(weight, 0.5)

print(getScale(weight))

Using the second parameter of get(weight, 0.5), you can define what happens when value entered by user is not in the dict.


问:
Simple validation using JUnit and Hamcrest
I have a map which contains child IDs (childid1, childid2, childid3) and status mapping and I have a list having all the IDs (say childid1, childid2, childid3 etc)

All these childids are mapped to a single parent ID say PID and PID also has some status. When I change status of PID say from A to B then based on condition, status of childids changes like A to B and B remains B and status C remains C.

When I change status of PID say from B to C then based on conditions status of childids changes like A to C and B remains B and status C remains C.

Without writing any complex logic, is there any simple way of validating this using JUnit 5 and Hamcrest. Something like:

```<code>if(updateStatus.equals("A")){
            assertAll("",
                    () -> {
                        childIds.stream().forEach(id -> {
                            assertThat("", idStatusMap.get(id).equals("A"), is("B"));
                            assertThat("", idStatusMap.get(id).equals("B"), is("B"));
                            assertThat("", idStatusMap.get(id).equals("C"), is("B"));
                        });
                    });
        }
</code>```

Any help is appreciated. Thanks

答:
I don't quite understand your logic/control workflow for changing the child Ids. But, I reckon, something like this should work:

if (updateStatus.equals("A") {
  Optional<> result = childIds.stream()
    .filter(id -> idStatusMap.get(id).equals("A") && id.equals("B"))
    .filter(id -> idStatusMap.get(id).equals("B") && id.equals("B"))
    .filter(id -> idStatusMap.get(id).equals("C") && id.equals("B"))
    .findAny();

  assertTrue(result.isPresent());
}
```

Body:
I have a map which contains child IDs (childid1, childid2, childid3) and status mapping and I have a list having all the IDs (say childid1, childid2, childid3 etc)

All these childids are mapped to a single parent ID say PID and PID also has some status. When I change status of PID say from A to B then based on condition, status of childids changes like A to B and B remains B and status C remains C.

When I change status of PID say from B to C then based on conditions status of childids changes like A to C and B remains B and status C remains C.

Without writing any complex logic, is there any simple way of validating this using JUnit 5 and Hamcrest. Something like:

if(updateStatus.equals("A")){
            assertAll("",
                    () -> {
                        childIds.stream().forEach(id -> {
                            assertThat("", idStatusMap.get(id).equals("A"), is("B"));
                            assertThat("", idStatusMap.get(id).equals("B"), is("B"));
                            assertThat("", idStatusMap.get(id).equals("C"), is("B"));
                        });
                    });
        }

Any help is appreciated. Thanks


问:
biggest values indecies by sub-grouping 2D array : argwhere.sort.max.group.sum(axis=1)?
Let say I have 2D array :

```<code>  a = np.random.randint(0,10,(20,5))
</code>```

I want to get the two max row sums row-indexes, but looking at them as groups.

So in this case I want to split the 20 rows in 5 groups, get the .sum(axis=1) and pick the maximum in the group.

After I have the five maximums (for every group), I want to pick the two biggest values row-indexes (based on the original array)

```<code>  a.sum(axis=1)
  ... get max in all 5 groups
  ... pick two biggest
  ... argwhere() of those two
</code>```

```<code>  asum.reshape((4,5))

 array([[18, 27, 23, 18, 26],
   [34, 24, 23, 15, 30],
   [16, 26, 21, 24, 16],
   [21, 24, 29, 23, 23]])

  a.sum(axis=1).reshape((4,5)).argmax(axis=1)
  Out[55]: array([1, 0, 1, 2])
</code>```

now I have to convert those to 1D indexes..

```<code>  idxs = a.sum(axis=1).reshape((4,5)).argmax(axis=1) + np.arange(0,4) * 5
  array([ 1,  5, 11, 17])
</code>```

now I have to pick top two, given those indecies !?

hmm... ugly..

```<code> : asum
 array([18, 27, 23, 18, 26, 34, 24, 23, 15, 30, 16, 26, 21, 24, 16, 21, 24, 29, 23, 23])

idxs[np.argsort(asum[idxs])][::-1][:2]
array([ 5, 17])
</code>```

答:
import numpy as np
a = np.random.randint(0,10,(20,5))
row_sums = a.sum(axis=1)

# array([30, 23, 13, 26, 17, 27, 29, 21, 16, 25, 21, 23, 38, 32, 23, 18, 16,
#        23, 16, 25])
```

<p>This solution avoids a complete sort by using a binary heap:</p>

<pre class="lang-py prettyprint-override"><code>N = 2
import heapq
index_and_max = heapq.nlargest(N, enumerate(row_sums), key=lambda x: x[1])

# list of tuple of index and value at index, of two largest
#[(12, 38), (13, 32)]
</code>```

Otherwise, you can stick with numpy arrays' built in argsort

```<code>row_sums.argsort()[-2:]
# array([13, 12])
</code>```

Body:
Let say I have 2D array :

  a = np.random.randint(0,10,(20,5))

I want to get the two max row sums row-indexes, but looking at them as groups.

So in this case I want to split the 20 rows in 5 groups, get the .sum(axis=1) and pick the maximum in the group.

After I have the five maximums (for every group), I want to pick the two biggest values row-indexes (based on the original array)

  a.sum(axis=1)
  ... get max in all 5 groups
  ... pick two biggest
  ... argwhere() of those two

  asum.reshape((4,5))

 array([[18, 27, 23, 18, 26],
   [34, 24, 23, 15, 30],
   [16, 26, 21, 24, 16],
   [21, 24, 29, 23, 23]])

  a.sum(axis=1).reshape((4,5)).argmax(axis=1)
  Out[55]: array([1, 0, 1, 2])

now I have to convert those to 1D indexes..

  idxs = a.sum(axis=1).reshape((4,5)).argmax(axis=1) + np.arange(0,4) * 5
  array([ 1,  5, 11, 17])

now I have to pick top two, given those indecies !?

hmm... ugly..

 : asum
 array([18, 27, 23, 18, 26, 34, 24, 23, 15, 30, 16, 26, 21, 24, 16, 21, 24, 29, 23, 23])

idxs[np.argsort(asum[idxs])][::-1][:2]
array([ 5, 17])

Body:
import numpy as np
a = np.random.randint(0,10,(20,5))
row_sums = a.sum(axis=1)

# array([30, 23, 13, 26, 17, 27, 29, 21, 16, 25, 21, 23, 38, 32, 23, 18, 16,
#        23, 16, 25])

This solution avoids a complete sort by using a binary heap:

N = 2
import heapq
index_and_max = heapq.nlargest(N, enumerate(row_sums), key=lambda x: x[1])

# list of tuple of index and value at index, of two largest
#[(12, 38), (13, 32)]

Otherwise, you can stick with numpy arrays' built in argsort

row_sums.argsort()[-2:]
# array([13, 12])


问:
Blue Prism - Not able to spy elements - Browser Firefox
I have an issue with spy Browser mode in Firefox.
I have designed a new RPA process on Dev machine where I have spy in Browser mode (in firefox) web page.
On my Dev machine the Browser mode is working good and the process runs very good.
The issue is on production machine where the modeler don't see the elements which have been spied on dev machine.

Actions so far done.
We have set all settings regarding Firefox to the same like on dev machine using the BP guide,
We have installed the same Firefox extension on prod like on dev machine.
We have set the same internet options.

Non of the actions have helped us to be able to spy elements in Firefox on prod machine.

My questions to the experts community:)
What else could have impact on the BP - Browser mode which is stopping BP to see elements?
What virtual machine settings need to be set/or what to check?

We have BP Version 6:
Application Manager 6.4.2.10610
.Net Framework 4.7
Firefox version 72.0.2
Blue Prism Browser Extension version 6.4.2.10610vycoxormiz (updated 30. Jan. 2020)

Thank you for your help!

答:
I found the solution.

During investigation I came on this link

[https://superuser.com/questions/719875/google-chrome-always-says-google-chrome-was-not-shut-down-properly][1]

In the location "%UserProfile%\AppData\Local\Google\Chrome\User Data\Default\Preferences

I have changed the "exit_type": "normal" to "exit_type": "standard" and immediate the

Browser mode on production machine was working and we could run the process.

It seems that the chrome when it wasn't shut down properly has impact on Blue Prism.

Adding update.
I have noticed that each time Chrome opens it changes in the Preferences file the status to Normal.
I have fixed the issue in that way, that I have added additional logic to my solution:
1. I have copied the Preferences file to a different location and changed in the file the status to Standard.
2. I have added additional logic to my process where bot copy the file from the new location and replace the file in the Chrome location each time he runs.

Hope this will help others with similar issue.

Regards!