问:
Could not be resolved because it has an indirect dependency on the assembly - Azure DevOps Build Pipeline
I have two projects. Project 1 and Project 2. Project 1 refers to Project 2 in its csproj file. I have recently upgraded the Project 2 to a higher version of the .NET. When I did the same for Project 1 and ran my CI Pipeline, I have been getting quite a lot of errors, mostly like below. When I run the CI pipeline for Proj 2 seperately, it is building successfully.

I checked all possible places to see if I have any old references, but I am unable to find where exactly is the problem. Appreciate your help here.

```<code>Done Building Project "D:\a\1\s\dia-praj2\src\Proj-2\Proj-2.csproj" (default targets).
##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3274: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it was built against the ".NETFramework,Version=v4.7.2"

##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3275: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it has an indirect dependency on the assembly "CsvHelper, Version=27.0.0.0, Culture=neutral, PublicKeyToken=8c4959082be5c823" which was built against the ".NETFramework,Version=v4.7" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5".

##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3275: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it has an indirect dependency on the assembly "Azure.Core, Version=1.22.0.0, Culture=neutral, PublicKeyToken=92742159e12e44c8" which was built against the ".NETFramework,Version=v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5".

##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3275: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it has an indirect dependency on the assembly "Microsoft.Bcl.AsyncInterfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" which was built against the ".NETFramework,Version=v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5".
</code>```

My Build Pipeline

```<code> a# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/Proj-1.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

name: $(Build.DefinitionName)_$(SourceBranchName)_$(Date:yyyyMMdd)$(Rev:.r)

resources:
  repositories:
    - repository: Proj-2
      name: Proj-2
      type: git
      ref: feature/Proj-2
# this is being defined in app-ci pipeline

steps:
- script: echo '$(Build.BuildNumber)'
  displayName: "echo build number"

- checkout: Proj-2
  displayName: 'checkout Proj-2'

- checkout: self
  displayName: 'checkout Proj-1'

- task: NuGetToolInstaller@1
  displayName: Install Nuget Package Manager

- task: NuGetCommand@2
  displayName: Restore Nuget packages
  inputs:
    command: 'restore'
    restoreSolution: '$(solution)'
    restoreDirectory: 'c:\packages'

- task: VSBuild@1
  displayName: Build dia-ui solution
  inputs:
    solution: '$(solution)'
    vsVersion: '16.0'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
    clean: true

- task: CopyFiles@2
  displayName: Copy everything to the Binaries dir
  inputs:
    Contents: '**/Prj1/abc/**'
    TargetFolder: $(Build.BinariesDirectory)

- task: ArchiveFiles@2
  displayName: Zip the binaries dir into a file called 'drop.zip'
  inputs:
    rootFolderOrFile: '$(Build.BinariesDirectory)/Prj1/abc/'
    includeRootFolder: false
    archiveType: 'zip'
    archiveFile: '$(Build.ArtifactStagingDirectory)/drop.zip'
    replaceExistingArchive: true

- task: PublishBuildArtifacts@1
  displayName: Publish 'drop.zip' as an artifact
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)/drop.zip'
    ArtifactName: 'drop'
</code>```

答:
The dependencies of your project do not match the .NET version your project is on now. I had the same issue and reinstalled the packages using the method mentioned here. In short: in the package manager console run
update-package <package name> -reinstall

Do this for all packages installed in the project where you changed the .NET version.

Body:
I have two projects. Project 1 and Project 2. Project 1 refers to Project 2 in its csproj file. I have recently upgraded the Project 2 to a higher version of the .NET. When I did the same for Project 1 and ran my CI Pipeline, I have been getting quite a lot of errors, mostly like below. When I run the CI pipeline for Proj 2 seperately, it is building successfully.

I checked all possible places to see if I have any old references, but I am unable to find where exactly is the problem. Appreciate your help here.

Done Building Project "D:\a\1\s\dia-praj2\src\Proj-2\Proj-2.csproj" (default targets).
##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3274: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it was built against the ".NETFramework,Version=v4.7.2"

##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3275: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it has an indirect dependency on the assembly "CsvHelper, Version=27.0.0.0, Culture=neutral, PublicKeyToken=8c4959082be5c823" which was built against the ".NETFramework,Version=v4.7" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5".

##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3275: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it has an indirect dependency on the assembly "Azure.Core, Version=1.22.0.0, Culture=neutral, PublicKeyToken=92742159e12e44c8" which was built against the ".NETFramework,Version=v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5".

##[warning]D:\a\1\s\dia-proj1\proj1.metaproj(0,0): Warning MSB3275: The primary reference "D:\a\1\s\dia-praj2\src\Proj-2\bin\Release\Proj-2.dll" could not be resolved because it has an indirect dependency on the assembly "Microsoft.Bcl.AsyncInterfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" which was built against the ".NETFramework,Version=v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5".

My Build Pipeline

 a# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/Proj-1.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

name: $(Build.DefinitionName)_$(SourceBranchName)_$(Date:yyyyMMdd)$(Rev:.r)

resources:
  repositories:
    - repository: Proj-2
      name: Proj-2
      type: git
      ref: feature/Proj-2
# this is being defined in app-ci pipeline

steps:
- script: echo '$(Build.BuildNumber)'
  displayName: "echo build number"

- checkout: Proj-2
  displayName: 'checkout Proj-2'

- checkout: self
  displayName: 'checkout Proj-1'

- task: NuGetToolInstaller@1
  displayName: Install Nuget Package Manager

- task: NuGetCommand@2
  displayName: Restore Nuget packages
  inputs:
    command: 'restore'
    restoreSolution: '$(solution)'
    restoreDirectory: 'c:\packages'

- task: VSBuild@1
  displayName: Build dia-ui solution
  inputs:
    solution: '$(solution)'
    vsVersion: '16.0'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
    clean: true

- task: CopyFiles@2
  displayName: Copy everything to the Binaries dir
  inputs:
    Contents: '**/Prj1/abc/**'
    TargetFolder: $(Build.BinariesDirectory)

- task: ArchiveFiles@2
  displayName: Zip the binaries dir into a file called 'drop.zip'
  inputs:
    rootFolderOrFile: '$(Build.BinariesDirectory)/Prj1/abc/'
    includeRootFolder: false
    archiveType: 'zip'
    archiveFile: '$(Build.ArtifactStagingDirectory)/drop.zip'
    replaceExistingArchive: true

- task: PublishBuildArtifacts@1
  displayName: Publish 'drop.zip' as an artifact
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)/drop.zip'
    ArtifactName: 'drop'


来源: stackexchange

问:
Sencha Touch - AJAX not working
So this was working up until I made one change, and now it's only working when I access the mobile version of the site through Chrome, but not on any mobile devices anymore. Weird thing is, since it works through the Chrome browser, I can't actually replicate the issue. This is my AJAX call:

```<code>Ext.Ajax.request({
                            url: '/Home/PostMessage',
                            // url to post msg..
                            method: 'POST',
                            params: {
                                message: Ext.getCmp('msgText').getValue(),
                                lat: initialLocation.lat(),
                                lng: initialLocation.lng(),
                                loc: loc,
                                name: '',
                                parentId: 0,
                                FBId: 0
                            },
                            success: function() {
                                //Ext.getCmp('post-bar').hide({type: 'pop'});
                                Ext.getCmp('post-bar').hide();
                                setTimeout(function() {
                                    Ext.getCmp('posts-tab').doComponentLayout();
                                },
                                300);
                                jabsy.stores.Listpost.load();
                            },
                            failure: function() {
                                navigator.notification.alert('Could not post your message', // message
                                'Server Error!', // title
                                'OK' // buttonName
                                );
                            }
                        });
</code>```

The only thing that I added was the addition FBId parameter to the post params. The action method that gets the params looks like this:

```<code>public ActionResult PostMessage(double? lat, double? lng, string message, string loc, string name, int parentId, int FBId)
        {
            var match = Regex.Match(message, @"^\s*(.)(?:\1|\s)*$");
            string ip = string.IsNullOrWhiteSpace(Request.ServerVariables["REMOTE_ADDR"].ToString()) ? "" : Request.ServerVariables["REMOTE_ADDR"];
            if (lat.HasValue && lng.HasValue && (message.Length <= 100) && !match.Success && !string.IsNullOrWhiteSpace(message))
            {
                DAL dal = new DAL();
                bool success = dal.spInsertMessage(message, lat.Value, lng.Value, ip, loc, name, parentId, FBId.ToString());
                return Json(success);
            }
            else
            {
                return Json(false);
            }
        }
</code>```

Like I said, it still works if you access the mobile site from Chrome.

If you want to test it yourself, go to www.jabsy.com/Home/MobileHome in a Chrome or Safari browser (has to be webkit), and try it out and confirm it works, but it doesn't post from mobile devices anymore after this one param was added. I can't for the life of me figure out why. No error pops up, they just won't post it.

Does Sencha Touch have some AJAX param limit or something? But even if they did, that should also prevent it from working through a desktop browser right?? I can't really test if it's making it to the server and THEN something is going wrong, or it's just never making it, b/c I don't know of any way to test this from a mobile device, so I'm in the dark as to what's happening.

So confused.

答:
So I figured this out. Just for the hell of it, kind of inspired by Joey's comment - I used my Android phone to clear all cache/cookies/browsing history from it's browser, and tried it again.

It now works. I have no idea why this happened. I've updated the same exact params before, for instance, when I added the parentId parameter right before adding the current new one, and this issue didn't take place.

No idea, but that's what solved it. If anyone has any ideas as to why, or how to prevent this from happening in the future, PLEASE comment.

ContentLicense: CC BY-SA 3.0

Title: Sencha Touch - AJAX not working

Body:
So this was working up until I made one change, and now it's only working when I access the mobile version of the site through Chrome, but not on any mobile devices anymore. Weird thing is, since it works through the Chrome browser, I can't actually replicate the issue. This is my AJAX call:

Ext.Ajax.request({
                            url: '/Home/PostMessage',
                            // url to post msg..
                            method: 'POST',
                            params: {
                                message: Ext.getCmp('msgText').getValue(),
                                lat: initialLocation.lat(),
                                lng: initialLocation.lng(),
                                loc: loc,
                                name: '',
                                parentId: 0,
                                FBId: 0
                            },
                            success: function() {
                                //Ext.getCmp('post-bar').hide({type: 'pop'});
                                Ext.getCmp('post-bar').hide();
                                setTimeout(function() {
                                    Ext.getCmp('posts-tab').doComponentLayout();
                                },
                                300);
                                jabsy.stores.Listpost.load();
                            },
                            failure: function() {
                                navigator.notification.alert('Could not post your message', // message
                                'Server Error!', // title
                                'OK' // buttonName
                                );
                            }
                        });

The only thing that I added was the addition FBId parameter to the post params. The action method that gets the params looks like this:

public ActionResult PostMessage(double? lat, double? lng, string message, string loc, string name, int parentId, int FBId)
        {
            var match = Regex.Match(message, @"^\s*(.)(?:\1|\s)*$");
            string ip = string.IsNullOrWhiteSpace(Request.ServerVariables["REMOTE_ADDR"].ToString()) ? "" : Request.ServerVariables["REMOTE_ADDR"];
            if (lat.HasValue && lng.HasValue && (message.Length <= 100) && !match.Success && !string.IsNullOrWhiteSpace(message))
            {
                DAL dal = new DAL();
                bool success = dal.spInsertMessage(message, lat.Value, lng.Value, ip, loc, name, parentId, FBId.ToString());
                return Json(success);
            }
            else
            {
                return Json(false);
            }
        }

Like I said, it still works if you access the mobile site from Chrome.

If you want to test it yourself, go to www.jabsy.com/Home/MobileHome in a Chrome or Safari browser (has to be webkit), and try it out and confirm it works, but it doesn't post from mobile devices anymore after this one param was added. I can't for the life of me figure out why. No error pops up, they just won't post it.

Does Sencha Touch have some AJAX param limit or something? But even if they did, that should also prevent it from working through a desktop browser right?? I can't really test if it's making it to the server and THEN something is going wrong, or it's just never making it, b/c I don't know of any way to test this from a mobile device, so I'm in the dark as to what's happening.

So confused.


问:
How can I group by index with index +1 in Pandas
```<code>df = pd.DataFrame({'index': [1, 2, 3, 69, 70, 71, 458, 459, 460],
                   'Animals': ['alligator', 'bee', 'falcon', 'lion',
                   'monkey', 'parrot', 'shark', 'whale', 'zebra'],})
df
</code>```

Here is my DataFrame. I would like to groupby "index" column where first 3 animals which have index 1, 2, 3 goes to one group. The animals with numbers 69, 70, 71 goes to next group and so on.

In the end I would like to have 3 groups made by consecutive values in index column.

The good thing is the numbers in column index are always +1 and then a gap larger than 1 but never just +1

It should be exist some function for that I believe.

答:
Solutions for these invariably go for the compare to the previous row and cumsum the trues.

So perhaps something like this:

```<code>df['index'].diff().ne(1).cumsum()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
df = pd.DataFrame({'index': [1, 2, 3, 69, 70, 71, 458, 459, 460],
                   'Animals': ['alligator', 'bee', 'falcon', 'lion',
                   'monkey', 'parrot', 'shark', 'whale', 'zebra'],})
df

Here is my DataFrame. I would like to groupby "index" column where first 3 animals which have index 1, 2, 3 goes to one group. The animals with numbers 69, 70, 71 goes to next group and so on.

In the end I would like to have 3 groups made by consecutive values in index column.

The good thing is the numbers in column index are always +1 and then a gap larger than 1 but never just +1

It should be exist some function for that I believe.

Body:
Solutions for these invariably go for the compare to the previous row and cumsum the trues.

So perhaps something like this:

df['index'].diff().ne(1).cumsum()


问:
Proper .htaccess Method to Redirect a Few Select Pages to use HTTPS, Returning all Others to HTTP?
I've looked through similar questions but not found the exact working solution I'm after.

We have a Joomla site that needs 2-3 specific pages to be forced to use https, while navigating away from these pages needs to return to http for all other pages. All pages 'can' come up with either http or https, but https causes some issues with a few plugins.

We have already setup a few things on the .htaccess file, but I don't know all the syntax to do what I'm after. We have mod_rewrite on, a rule that redirects http:// to http://www., and the default Joomla rules that do the SEF urls.

So our secure pages are usually: /section/category/secure-page, /othersection/othercategory/secure-page 2, etc.

HERE'S OUR ENTIRE HTACCESS AFTER IMPLEMENTING THE FIX (BUT GETTING ERROR):

```<code>##
# @version $Id: htaccess.txt 10492 2008-07-02 06:38:28Z ircmaxell $
# @package Joomla
# @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
# Joomla! is Free Software
##

#####################################################
#  READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################

##  Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
#  mod_rewrite in use

RewriteEngine On

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

########## Begin - SSL Redirects (https/http)
#
RewriteRule %{HTTPS}  off
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cultivate-la-tickets$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-thankyou$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-decline$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-error$  [OR]
RewriteCond %{REQUEST_URI}  ^/how-to-help/donate/make-a-donation/$
RewriteRule (.*)  https://%{HTTP_HOST}/$1  [L]

RewriteRule %{HTTPS}  on
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cultivate-la-tickets$
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-thankyou$
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-decline$
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-error$
RewriteCond %{REQUEST_URI}  ^/how-to-help/donate/make-a-donation/$
RewriteRule (.*)  http://%{HTTP_HOST}/$1  [L]
#
##########

########## Begin - Redirect http:// to http://www. AND /annual subdirectory to annual. subdomain
#
RewriteCond %{HTTP_HOST} ^domainname.org [NC]
RewriteRule ^(.*)$ http://www.domainname.org/$1 [L,R=301]

RedirectMatch 301 ^/annual/(.*)$ http://annual.domainname.org/$1
#
##########

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section

########## Begin - 301 Redirect short URL
#
Redirect 301 /clatickets https://www.domainname.org/news-events/cultivate-la/cultivate-la-tickets
</code>```

答:
note: I deleted my previous answer. it's my new answer:</p>

```<code>##
# @version $Id: htaccess.txt 10492 2008-07-02 06:38:28Z ircmaxell $
# @package Joomla
# @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
# Joomla! is Free Software
##

#####################################################
#  READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################

##  Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
#  mod_rewrite in use

RewriteEngine On

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

########## Begin - SSL Redirects (https/http)
#
RewriteRule %{HTTPS}  off
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cultivate-la-tickets$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-thankyou$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-decline$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-error$  [OR]
RewriteCond %{REQUEST_URI}  ^/how-to-help/donate/make-a-donation/$
RewriteRule (.*)  https://%{HTTP_HOST}/$1  [L]

RewriteRule %{HTTPS}  on
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cultivate-la-tickets$
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cla-tickets-thankyou$
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cla-tickets-decline$
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cla-tickets-error$
RewriteCond %{REQUEST_URI}  !^/how-to-help/donate/make-a-donation/$
RewriteRule (.*)  http://%{HTTP_HOST}/$1  [L]
#
##########

########## Begin - Redirect http:// to http://www. AND /annual subdirectory to annual. subdomain
#
RewriteCond %{HTTP_HOST} ^domainname.org [NC]
RewriteRule ^(.*)$ http://www.domainname.org/$1 [L,R=301]

RedirectMatch 301 ^/annual/(.*)$ http://annual.domainname.org/$1
#
##########

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section

########## Begin - 301 Redirect short URL
#
Redirect 301 /clatickets https://www.domainname.org/news-events/cultivate-la/cultivate-la-tickets
</code>```

Body:
I've looked through similar questions but not found the exact working solution I'm after.

We have a Joomla site that needs 2-3 specific pages to be forced to use https, while navigating away from these pages needs to return to http for all other pages. All pages 'can' come up with either http or https, but https causes some issues with a few plugins.

We have already setup a few things on the .htaccess file, but I don't know all the syntax to do what I'm after. We have mod_rewrite on, a rule that redirects http:// to http://www., and the default Joomla rules that do the SEF urls.

So our secure pages are usually: /section/category/secure-page, /othersection/othercategory/secure-page 2, etc.

HERE'S OUR ENTIRE HTACCESS AFTER IMPLEMENTING THE FIX (BUT GETTING ERROR):

##
# @version $Id: htaccess.txt 10492 2008-07-02 06:38:28Z ircmaxell $
# @package Joomla
# @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
# Joomla! is Free Software
##

#####################################################
#  READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################

##  Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
#  mod_rewrite in use

RewriteEngine On

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
# Block out any script that includes a

Body:
note: I deleted my previous answer. it's my new answer:

##
# @version $Id: htaccess.txt 10492 2008-07-02 06:38:28Z ircmaxell $
# @package Joomla
# @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
# Joomla! is Free Software
##

#####################################################
#  READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################

##  Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
#  mod_rewrite in use

RewriteEngine On

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

########## Begin - SSL Redirects (https/http)
#
RewriteRule %{HTTPS}  off
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cultivate-la-tickets$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-thankyou$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-decline$  [OR]
RewriteCond %{REQUEST_URI}  ^/news-events/cultivate-la/cla-tickets-error$  [OR]
RewriteCond %{REQUEST_URI}  ^/how-to-help/donate/make-a-donation/$
RewriteRule (.*)  https://%{HTTP_HOST}/$1  [L]

RewriteRule %{HTTPS}  on
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cultivate-la-tickets$
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cla-tickets-thankyou$
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cla-tickets-decline$
RewriteCond %{REQUEST_URI}  !^/news-events/cultivate-la/cla-tickets-error$
RewriteCond %{REQUEST_URI}  !^/how-to-help/donate/make-a-donation/$
RewriteRule (.*)  http://%{HTTP_HOST}/$1  [L]
#
##########

########## Begin - Redirect http:// to http://www. AND /annual subdirectory to annual. subdomain
#
RewriteCond %{HTTP_HOST} ^domainname.org [NC]
RewriteRule ^(.*)$ http://www.domainname.org/$1 [L,R=301]

RedirectMatch 301 ^/annual/(.*)$ http://annual.domainname.org/$1
#
##########

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section

########## Begin - 301 Redirect short URL
#
Redirect 301 /clatickets https://www.domainname.org/news-events/cultivate-la/cultivate-la-tickets


问:
Transparent or Invisible
I'm trying to use an ImageView without any background. I know that I can use

```<code>imageView.setVisibility(INVISIBLE);
</code>```

and

```<code>imageView.setBackgroundColor(Color.TRANSPARENT);
</code>```

I was wondering which one is more efficient? or any extra solution?

答: you can use imageView.setAlpha(127);</p>

Title: Transparent or Invisible

Body:
I'm trying to use an ImageView without any background. I know that I can use

imageView.setVisibility(INVISIBLE);

and

imageView.setBackgroundColor(Color.TRANSPARENT);

I was wondering which one is more efficient? or any extra solution?

Body: you can use imageView.setAlpha(127);


问:
vscode debugger does not launch debug console
I am so frustrated that my vscode debugger does not work on the remote servers suddenly today.
Here is the situation.

When I use the starred interpreter by vscode (the recommended one), it works smoothly. However, when I want to use other interpreters, the ones stored in personal folder on the server, the debugger doesn't launch a debug console and dose not enter the file.

Vscode can find and recognize the interpreters and I can use those interpreters to run scripts but can NOT DEBUG.(on the remote server) However, it works fine on my local machine with multiple python interpreter.

Can anyone give me some help? I have tried uninstall vscode completely on my end but still not work. Thank you so much!!

答:
This workaround might work for you: use the interpreter that works for you but in the launch.json configuration file add a
"python": "/path/to/the/python/you/want",

I share the same experience. It seems that vscode fails to start the remote debugger with the interpreter I want but succeeds with the system interpreter.
For example:

```<code>"configurations": [
         {
            "name": "config_name",
            "type": "python",
            "python": "/path/to/desired/python",
            "request": "launch",
            "program": "/path/to/python/script.py",
            "console": "integratedTerminal",
        },
]
</code>```

Body:
This workaround might work for you: use the interpreter that works for you but in the launch.json configuration file add a
"python": "/path/to/the/python/you/want",

I share the same experience. It seems that vscode fails to start the remote debugger with the interpreter I want but succeeds with the system interpreter.
For example:

"configurations": [
         {
            "name": "config_name",
            "type": "python",
            "python": "/path/to/desired/python",
            "request": "launch",
            "program": "/path/to/python/script.py",
            "console": "integratedTerminal",
        },
]


问:
how to copy data from one xml files in to another using java xslt

I need to replace all ? in file1.xml with element value present in File2.xml.

And also need to remove extra element node present in File1.xml whose value is not present in File2.xml. (i.e. In my sample input need to remove totalDueWithoutTax element from file1.xml as it is not present in File2.xml.

There may be the cases where we have multiple elements in File2 but only one corresponsing element in File1. Like in my below example we have two salesInfo element in File2 but in File1 we have only one. In that case as a expected output we need both salesInfo element of File2.

This is just sample input. In real scenario input xmls can be different means we can get different format of xmls everytime.

Please suggest me how to do that in java. It would be better if we can achieve this using xslt.

```<code>        **File 1 -- input xml**
       <order>
            <orderId>?</orderId>
             <sales>
              <salesInfo>
                <salesChannel>?</salesChannel>
                <senderSystemId>?</senderSystemId>
                <applicationId>?</applicationId>
                <totalDueWithoutTax>?</totalDueWithoutTax>
              </salesInfo>
              <salesid>?</salesid>
           </sales>
        </order>

        **File 2 -- input xml**

        <order>
          <orderId>4567</orderId>
          <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
                <esignatureCaptureMode>INLINE</esignatureCaptureMode>
              </salesInfo>
              <salesInfo>
                <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
                <esignatureCaptureMode>outline</esignatureCaptureMode>
              </salesInfo>
              <salesid>789</salesid>
        </sales>
        </order>

        **Expected output:**

        <order>
            <orderId>4567</orderId>
            <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
              </salesInfo>
              <salesInfo>
               <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
              </salesInfo>
              <salesid>789</salesid>
          </sales>
        </order>
</code>```

答:
You could consider a group/merge problem:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  xmlns:mf="http://example.com/mf"
  expand-text="yes">

  <xsl:param name="doc2" select="doc('file2.xml')"/>>

  <xsl:output method="xml" indent="yes"/>

  <xsl:function name="mf:merge" as="node()*">
    <xsl:param name="nodes1" as="node()*"/>
    <xsl:param name="nodes2" as="node()*"/>
    <xsl:for-each-group select="$nodes1, $nodes2" group-by="node-name()">
      <xsl:choose>
        <xsl:when test="not(*) and . = '?' and current-group()[2]">
          <xsl:apply-templates select="current-group()[2]"/>
        </xsl:when>
        <xsl:when test="current-group()[1][*] and current-group()[2][*]">
          <xsl:copy>
            <xsl:sequence select="mf:merge(*, current-group()[2]/*)"/>
          </xsl:copy>
        </xsl:when>
      </xsl:choose>
    </xsl:for-each-group>
  </xsl:function>

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:sequence select="mf:merge(*, $doc2/*/*)"/>
    </xsl:copy>
  </xsl:template>

  <xsl:mode on-no-match="shallow-copy"/>

</xsl:stylesheet>
</code>```

Depending on the structure or the merging requirements using xsl:for-each-group select="$nodes1, $nodes2" group-by="path(.)" instead of <xsl:for-each-group select="$nodes1, $nodes2" group-by="node-name()"> might be more suitable, for instance if an element can have several child elements of the same name.

Body:
I need to replace all ? in file1.xml with element value present in File2.xml.

And also need to remove extra element node present in File1.xml whose value is not present in File2.xml. (i.e. In my sample input need to remove totalDueWithoutTax element from file1.xml as it is not present in File2.xml.

There may be the cases where we have multiple elements in File2 but only one corresponsing element in File1. Like in my below example we have two salesInfo element in File2 but in File1 we have only one. In that case as a expected output we need both salesInfo element of File2.

This is just sample input. In real scenario input xmls can be different means we can get different format of xmls everytime.

Please suggest me how to do that in java. It would be better if we can achieve this using xslt.

        **File 1 -- input xml**
       <order>
            <orderId>?</orderId>
             <sales>
              <salesInfo>
                <salesChannel>?</salesChannel>
                <senderSystemId>?</senderSystemId>
                <applicationId>?</applicationId>
                <totalDueWithoutTax>?</totalDueWithoutTax>
              </salesInfo>
              <salesid>?</salesid>
           </sales>
        </order>

        **File 2 -- input xml**

        <order>
          <orderId>4567</orderId>
          <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
                <esignatureCaptureMode>INLINE</esignatureCaptureMode>
              </salesInfo>
              <salesInfo>
                <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
                <esignatureCaptureMode>outline</esignatureCaptureMode>
              </salesInfo>
              <salesid>789</salesid>
        </sales>
        </order>

        **Expected output:**

        <order>
            <orderId>4567</orderId>
            <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
              </salesInfo>
              <salesInfo>
               <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
              </salesInfo>
              <salesid>789</salesid>
          </sales>
        </order>

Body:
You could consider a group/merge problem:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  xmlns:mf="http://example.com/mf"
  expand-text="yes">

  <xsl:param name="doc2" select="doc('file2.xml')"/>>

  <xsl:output method="xml" indent="yes"/>

  <xsl:function name="mf:merge" as="node()*">
    <xsl:param name="nodes1" as="node()*"/>
    <xsl:param name="nodes2" as="node()*"/>
    <xsl:for-each-group select="$nodes1, $nodes2" group-by="node-name()">
      <xsl:choose>
        <xsl:when test="not(*) and . = '?' and current-group()[2]">
          <xsl:apply-templates select="current-group()[2]"/>
        </xsl:when>
        <xsl:when test="current-group()[1][*] and current-group()[2][*]">
          <xsl:copy>
            <xsl:sequence select="mf:merge(*, current-group()[2]/*)"/>
          </xsl:copy>
        </xsl:when>
      </xsl:choose>
    </xsl:for-each-group>
  </xsl:function>

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:sequence select="mf:merge(*, $doc2/*/*)"/>
    </xsl:copy>
  </xsl:template>

  <xsl:mode on-no-match="shallow-copy"/>

</xsl:stylesheet>

Depending on the structure or the merging requirements using xsl:for-each-group select="$nodes1, $nodes2" group-by="path(.)" instead of <xsl:for-each-group select="$nodes1, $nodes2" group-by="node-name()"> might be more suitable, for instance if an element can have several child elements of the same name.


问:
Reading variable length binary values from a file in python
I have three text values that I am encrypting and then writing to a file. Later I want to read the values back (in another script) and decrypt them.

I've successfully encrypted the values:

```<code>cenc = rsa.encrypt(client_name.encode('utf8'), publicKey)
denc = rsa.encrypt(expiry_date.encode('utf8'), publicKey)
fenc = rsa.encrypt(features.encode('utf8'), publicKey)
</code>```

and written to a binary file:

```<code>licensefh = open("license.sfb", "wb")
licensefh.write(cenc)
licensefh.write(denc)
licensefh.write(fenc)

licensefh.close()
</code>```

The three values cenc, denc and fenc are all of different lengths so when I read the file back:

```<code>licensefh = open("license.sfb", "rb")
encMessage = licensefh.read()
</code>```

encMessage contains the entire file and I don't know how to get the three values back again.

I've tried using a separator between the values:

```<code>SEP = bytes(chr(0x02).encode('utf8'))
...
licensefh.write(cenc)
licensefh.write(SEP)
...
</code>```

and then using encMessage.partition(SEP) or encMessage.split(SEP) but the data invariably contains the SEP value in it somewhere (I've tried a few different characters) so that didn't work.

I tried getting the length of the bytes objects cenc, denc and fenc, but this returned 256 for each value even though the contents of the variables are all different lengths.

My question is this. How do I write these three variable length values to a binary file and then separate them when I read them back again?

Here's an example of the 3 binary values:

```<code>b'tX\x10Fo\x89\x10~\x83Pok\xd1\xfb\xbe\x0e<a\xe5\x11md:\xe6\x84@\xfa\xf8\xe5\xeb\xf8\xdc{\xc0Z\xa0\xc0^\xc1\xd9\x820\xec\xec\xb0R\x99/\xa2l\x88\xa9\xa6g\xa3\x01m\xf9\x7f\x91\xb9\xe1\x80\xccs|\xb7_\xa9Fp\x11yvG\xdc\x02d\x8aK2\x92t\x0e\x1f\xca\x19\xbb&\xaf{\xc0y>\t|\x86\xab\x16.\xa5kZ"\xab6\xaaV\xf4w\x7f\xc5q\x07\xef\xa9\xa5\xa3\xf3 6\xdb\x03\x19S\xbd\x81\xf9\xc8\xc5\x90\x1e\x19\x86\xa4q\xe3?i\xc4\xac\t\xd5=3C\x9b#\xc3IuAN,\xeat\xc6\x96VFL\x1eFWZ\xa4\xd73\x92P@\x1d\xb9\x12\x15\xc9\xd4~\x8aWm^\xb8\x8b\x9d\x88\n)\xeb#\xe3\x93\xb1\\\xd6^\xe0\xce\xa2(\x05\xf5\xe6\x8b\xd1\x15\xd8v\xf0\xae\x90\xd8?\x01\r\x00\xf4\xa5\xadM|%\x98\xa9SR\xc6\xd0K\x9e&\xc3\xe0M\x81\x87\xdea\xcc\xd5\x9c\xcd\xfd1l\x1f\xb9?\xed\xd1\x95\xbc\x11\x85U9'

b'l\xd3S\xcc\x03\x9a\xf2\xfdr\xca\xbbA\x06\xfb\xd8\xbbWi\xdc\xb1\xf6&\x97T\x81Kl\r\x86\x9b\x95?\x94}\x8a\xd3\xa1V\x81\xd3]*B\x1f\x96`\xa3\xd1\xf2|B\x84?\xa0\ns\xb7\xcf\x18Y\x87\xcfR\x87!\x14\x81!\xf7\xf2\xe5x|=O\xe3\xba2\xf2!\x93\x0fT7\x0c~4\xa3\xe5\xb7\xf9wy\xb5\x12FM\x96\xd9\xfd\xedn\x9c\xacw\x1b\xc2\x17+\xb6\x05`\x10\xf8\xe4\x01\xde\xc7\xa2\xa0\x80\xd8\x15\xb1+<s\xc7\x19\x9c\x14\xb0\x1a"\x10\xbb\x0f\xe1\x05\x93\xd2?xX\xd9\x93\x8an\x8d\xcd\xbd!c\xd0,\xa45\xbai\xe3\xccx\x08\xaa,\xd1\xe5\'t\x91\xb8\xf2n$\x0c\xf9-\xb4\xc2\x07\x81\xe1\xe7\x8e\xb3\x98\x11\xf3\xa6\xd9wz\x9a3\xc9\x9c?z\xd8\xaa\x08}\xa2\x9c[\xf2\x9d\xe4\xcdb\xddl\xceV\x7f\xf1\x81\xb3\x88\x1e\x9c5?k\x0f\xc9\x86\x86&\xedV.\xa7\x8d\x13&V\xad\xca\xe5\x93\xfe\xa5\x94\xbc\xf5\xd1{Cl\xc0\x030\x92\x03\xc9'

b'#\xbdd7\xe9\xa0{\t\xb9\x87B\x9e\xf9\x97P^\xf3V\xb6\x93\x1f(J\x0b\xa3\xbf\xd8\x04\x86T\xa4\xca\xf3\xe8%\xddC\x11\xdb5\xff,\xf7\x13\xd7\xd2\xbc\xf3\x893\x83\xdcmJ\xc8p\xdf\x07V\x7fb\xeb\xa9\x8b\x0f\xca\xf9\x05\xfc\xdfS\x94b\x90\xcd\xfcn?/]\x11\xaf\xe606\xfb\\U59\xa0>\xbd\xd8\x1c\xa8\xca\x83\xf4C\x95v7\xc6\xe00\xe4,d_/\x83\xa0\xb9mO\x0e\xc4\x97J\x15\xf0\xca-\xa0\xafT\xe4\x82\x03\n\x14:\xa1\xdcL\x98\x9d,1\xfa\x10\xf4\xfd\xa0\x0b\xc7\x13!\xf7\xdb/\xda\x1a\x9df\x1cQ\xc0\x99H\x08\xa0c\x8f9/4\xc4\x05\xc6\x9eM\x8e\xe5V\xf8D\xc3\xfd\xad4\x94A\xb9[\x80\xb9\xcf\xe6\xd9\xb3M2\xd9N\xfbA\x18\x84/W\x9b\x92\xfe\xbb\xd6C\x85\xa3\xc6\xd2T\xd0\xb2\xb9\xf7R\xb4(s\xda\xbcX,9w\x17\x1c\xfb|\xa0\x87\xba\xca6>y\xba\\L4wc\x94\xe7$Y\x89\x07\x9b\xfe\x9b?{\x85'
</code>```

Body:
I have three text values that I am encrypting and then writing to a file. Later I want to read the values back (in another script) and decrypt them.

I've successfully encrypted the values:

cenc = rsa.encrypt(client_name.encode('utf8'), publicKey)
denc = rsa.encrypt(expiry_date.encode('utf8'), publicKey)
fenc = rsa.encrypt(features.encode('utf8'), publicKey)

and written to a binary file:

licensefh = open("license.sfb", "wb")
licensefh.write(cenc)
licensefh.write(denc)
licensefh.write(fenc)

licensefh.close()

The three values cenc, denc and fenc are all of different lengths so when I read the file back:

licensefh = open("license.sfb", "rb")
encMessage = licensefh.read()

encMessage contains the entire file and I don't know how to get the three values back again.

I've tried using a separator between the values:

SEP = bytes(chr(0x02).encode('utf8'))
...
licensefh.write(cenc)
licensefh.write(SEP)
...

and then using encMessage.partition(SEP) or encMessage.split(SEP) but the data invariably contains the SEP value in it somewhere (I've tried a few different characters) so that didn't work.

I tried getting the length of the bytes objects cenc, denc and fenc, but this returned 256 for each value even though the contents of the variables are all different lengths.

My question is this. How do I write these three variable length values to a binary file and then separate them when I read them back again?

Here's an example of the 3 binary values:

b'tX\x10Fo\x89\x10~\x83Pok\xd1\xfb\xbe\x0e\t|\x86\xab\x16.\xa5kZ"\xab6\xaaV\xf4w\x7f\xc5q\x07\xef\xa9\xa5\xa3\xf3 6\xdb\x03\x19S\xbd\x81\xf9\xc8\xc5\x90\x1e\x19\x86\xa4q\xe3?i\xc4\xac\t\xd5=3C\x9b#\xc3IuAN,\xeat\xc6\x96VFL\x1eFWZ\xa4\xd73\x92P@\x1d\xb9\x12\x15\xc9\xd4~\x8aWm^\xb8\x8b\x9d\x88\n)\xeb#\xe3\x93\xb1\\\xd6^\xe0\xce\xa2(\x05\xf5\xe6\x8b\xd1\x15\xd8v\xf0\xae\x90\xd8?\x01\r\x00\xf4\xa5\xadM|%\x98\xa9SR\xc6\xd0K\x9e&\xc3\xe0M\x81\x87\xdea\xcc\xd5\x9c\xcd\xfd1l\x1f\xb9?\xed\xd1\x95\xbc\x11\x85U9'

b'l\xd3S\xcc\x03\x9a\xf2\xfdr\xca\xbbA\x06\xfb\xd8\xbbWi\xdc\xb1\xf6&\x97T\x81Kl\r\x86\x9b\x95?\x94}\x8a\xd3\xa1V\x81\xd3]*B\x1f\x96`\xa3\xd1\xf2|B\x84?\xa0\ns\xb7\xcf\x18Y\x87\xcfR\x87!\x14\x81!\xf7\xf2\xe5x|=O\xe3\xba2\xf2!\x93\x0fT7\x0c~4\xa3\xe5\xb7\xf9wy\xb5\x12FM\x96\xd9\xfd\xedn\x9c\xacw\x1b\xc2\x17+\xb6\x05`\x10\xf8\xe4\x01\xde\xc7\xa2\xa0\x80\xd8\x15\xb1+<s\xc7\x19\x9c\x14\xb0\x1a"\x10\xbb\x0f\xe1\x05\x93\xd2?xX\xd9\x93\x8an\x8d\xcd\xbd!c\xd0,\xa45\xbai\xe3\xccx\x08\xaa,\xd1\xe5\'t\x91\xb8\xf2n$\x0c\xf9-\xb4\xc2\x07\x81\xe1\xe7\x8e\xb3\x98\x11\xf3\xa6\xd9wz\x9a3\xc9\x9c?z\xd8\xaa\x08}\xa2\x9c[\xf2\x9d\xe4\xcdb\xddl\xceV\x7f\xf1\x81\xb3\x88\x1e\x9c5?k\x0f\xc9\x86\x86&\xedV.\xa7\x8d\x13&V\xad\xca\xe5\x93\xfe\xa5\x94\xbc\xf5\xd1{Cl\xc0\x030\x92\x03\xc9'

b'#\xbdd7\xe9\xa0{\t\xb9\x87B\x9e\xf9\x97P^\xf3V\xb6\x93\x1f(J\x0b\xa3\xbf\xd8\x04\x86T\xa4\xca\xf3\xe8%\xddC\x11\xdb5\xff,\xf7\x13\xd7\xd2\xbc\xf3\x893\x83\xdcmJ\xc8p\xdf\x07V\x7fb\xeb\xa9\x8b\x0f\xca\xf9\x05\xfc\xdfS\x94b\x90\xcd\xfcn?/]\x11\xaf\xe606\xfb\\U59\xa0>\xbd\xd8\x1c\xa8\xca\x83\xf4C\x95v7\xc6\xe00\xe4,d_/\x83\xa0\xb9mO\x0e\xc4\x97J\x15\xf0\xca-\xa0\xafT\xe4\x82\x03\n\x14:\xa1\xdcL\x98\x9d,1\xfa\x10\xf4\xfd\xa0\x0b\xc7\x13!\xf7\xdb/\xda\x1a\x9df\x1cQ\xc0\x99H\x08\xa0c\x8f9/4\xc4\x05\xc6\x9eM\x8e\xe5V\xf8D\xc3\xfd\xad4\x94A\xb9[\x80\xb9\xcf\xe6\xd9\xb3M2\xd9N\xfbA\x18\x84/W\x9b\x92\xfe\xbb\xd6C\x85\xa3\xc6\xd2T\xd0\xb2\xb9\xf7R\xb4(s\xda\xbcX,9w\x17\x1c\xfb|\xa0\x87\xba\xca6>y\xba\\L4wc\x94\xe7$Y\x89\x07\x9b\xfe\x9b?{\x85'


问:
ajax woes. Submitting without refreshing. I need help
I'm having problems submitting my ajax form. I am used to the old fashioned way with refresh but this new stuff is beyond me for the time being. It's time to start learning new technolohies.

I have an autosuggest box that is getting my results from a database and populating the textbox just fine. When I designed this about 6 months ago, I was searching the database on the value rather than the key value. This is a problem today and needs to be fixed.

WHat the ajax has returned to my script is the key/value pair. Now that I have the id, I need to pass that into my php method so I can process it from there.

Can somone please give me a hand with this? It seems simple enough but again, javascript was never my thing so I am lost.

Here is all of the relevant code. Also, I don't think, at least from the code samples I have seen so far that I even need a form tag. Am I correct on this? Ideally, I want to submit the found ajax value with the enter button and NOT using a button.

So, just to clarify, this is what happens. The user types 2 or 3 letters. The ajax queries the db on a "LIKE" operator and returns the matches. The user chooses the one he wants and then the id goes out to my method and returns the exact record in a different window.

```<code><form method="post" class="hdrForm" id="search" action="../../index.php?cer=2" target="_top">
<input type="text" name="string" class="hdrInput" id="string" value="Quick Search"><div id="acDiv"></div>

</form>
</code>```

Note.. I need the "id" in this function to be submitted. Right now, I am getting the POST val off the form tag and that's not correct but how?

```<code>  AC.chooseFunc = function(id,label)
  {
    document.forms.search.submit();
  }
</code>```

Thanks for any help that you guys can give me on this.

答:
You have two problems. One is that you are telling the form to submit:

```<code>document.forms.search.submit();
</code>```

That is what is causing your form to submit in the standard, non-xhr way - causing a refresh. Also, because your form does not contain an input element for the id, that is not being sent to the server even with a regular form submission.

I agree with the posters that it would be a good idea to use jQuery or something to do your ajax based submission. Something like this could be used inside of your "AC.chooseFunc" function instead of the form submit.

And yes, if you go ajax entirely, you don't even need a form tag.

OwnerDisplayName: Jim

ContentLicense: CC BY-SA 2.5

Body:
I'm having problems submitting my ajax form. I am used to the old fashioned way with refresh but this new stuff is beyond me for the time being. It's time to start learning new technolohies.

I have an autosuggest box that is getting my results from a database and populating the textbox just fine. When I designed this about 6 months ago, I was searching the database on the value rather than the key value. This is a problem today and needs to be fixed.

WHat the ajax has returned to my script is the key/value pair. Now that I have the id, I need to pass that into my php method so I can process it from there.

Can somone please give me a hand with this? It seems simple enough but again, javascript was never my thing so I am lost.

Here is all of the relevant code. Also, I don't think, at least from the code samples I have seen so far that I even need a form tag. Am I correct on this? Ideally, I want to submit the found ajax value with the enter button and NOT using a button.

So, just to clarify, this is what happens. The user types 2 or 3 letters. The ajax queries the db on a "LIKE" operator and returns the matches. The user chooses the one he wants and then the id goes out to my method and returns the exact record in a different window.

<form method="post" class="hdrForm" id="search" action="../../index.php?cer=2" target="_top">
<input type="text" name="string" class="hdrInput" id="string" value="Quick Search">

</form>

Note.. I need the "id" in this function to be submitted. Right now, I am getting the POST val off the form tag and that's not correct but how?

  AC.chooseFunc = function(id,label)
  {
    document.forms.search.submit();
  }

Thanks for any help that you guys can give me on this.

Body:
You have two problems. One is that you are telling the form to submit:

document.forms.search.submit();

That is what is causing your form to submit in the standard, non-xhr way - causing a refresh. Also, because your form does not contain an input element for the id, that is not being sent to the server even with a regular form submission.

I agree with the posters that it would be a good idea to use jQuery or something to do your ajax based submission. Something like this could be used inside of your "AC.chooseFunc" function instead of the form submit.

And yes, if you go ajax entirely, you don't even need a form tag.

OwnerDisplayName: genericallyloud


问:
Why is memset() incorrectly initializing int?
Why is the output of the following program 84215045?

```<code>int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}
</code>```

答:
Since the memset writes bytes,I usually use it to set an int array to zero like:

```<code>int a[100];
memset(a,0,sizeof(a));
</code>```

or you can use it to set a char array,since a char is exactly a byte:

```<code>char a[100];
memset(a,'*',sizeof(a));
</code>```

what's more,an int array can also be set to -1 by memset:

```<code>memset(a,-1,sizeof(a));
</code>```

This is because -1 is 0xffffffff in int,and is 0xff in char(a byte).

Body:
Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}

Body:
Since the memset writes bytes,I usually use it to set an int array to zero like:

int a[100];
memset(a,0,sizeof(a));

or you can use it to set a char array,since a char is exactly a byte:

char a[100];
memset(a,'*',sizeof(a));

what's more,an int array can also be set to -1 by memset:

memset(a,-1,sizeof(a));

This is because -1 is 0xffffffff in int,and is 0xff in char(a byte).


问:
pattern validator accept everything without word characters
i am trying to create a pattern that accept everything without word characters (a-z or A-Z) in angular.

```<code>  phone: new FormControl(null, [
    Validators.required,
    Validators.pattern("^-?[0-9]\\d*(\\.\\d{1,2})?$"),
  ]),
</code>```

i try this patter but not work fine because my goal is:

pattern must accept :

```<code>()*#%&#@64582 (example 1)
3796592#$#@$%^&$&/ (exapmle 2)
34242+5334?@^#$#%4242 (example 3)
</code>```

That mean everything without (a-z or A-Z)

Pattern must not accept  :

```<code>$%$@#423URVB
t3653$^%#&#%&
</code>```

Any idea ?

答:
Your suggested pattern allows positive or negative floats and is not relevant to your wishes

Normally we use a negated class

```<code>/^[^a-zA-Z]$/g
</code>```

but that will allow öää for example

```<code>/^[^a-zA-Z\p{L}]$/gu
</code>```

will also block unicode characters but allow special characters

https://regex101.com/r/WxARn2/1

I can however not find how to add the flag to Angular PatternValidator so you will need to test it

Body:
i am trying to create a pattern that accept everything without word characters (a-z or A-Z) in angular.

  phone: new FormControl(null, [
    Validators.required,
    Validators.pattern("^-?[0-9]\\d*(\\.\\d{1,2})?$"),
  ]),

i try this patter but not work fine because my goal is:

pattern must accept :

()*#%&#@64582 (example 1)
3796592#$#@$%^&$&/ (exapmle 2)
34242+5334?@^#$#%4242 (example 3)

That mean everything without (a-z or A-Z)

Pattern must not accept  :

$%$@#423URVB
t3653$^%#&#%&

Any idea ?

Body:
Your suggested pattern allows positive or negative floats and is not relevant to your wishes

Normally we use a negated class

/^[^a-zA-Z]$/g

but that will allow öää for example

/^[^a-zA-Z\p{L}]$/gu

will also block unicode characters but allow special characters

https://regex101.com/r/WxARn2/1

I can however not find how to add the flag to Angular PatternValidator so you will need to test it


问:
Parallel tree traversal in C#
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

```<code>   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }
</code>```

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).

答:
I might be missing something, but I don't see the need for a while at all.  The while is just ensuring that you iterate over every node.

Instead just call your function recursively for each node in the tree.

```<code>public void Traverse(Node root)
{
    if (root.Property = someValue) DoSomething(node);
    Parallel.ForEach<Node>(root.Children, node => Traverse(node));
}
</code>```

edit: of course the alternative, if you prefer to process horizontally rather than vertically and your expensive operation is DoSomething, is to do the Traverse first.

```<code>public IEnumerable<Node> Traverse(Node root)
{
    // return all the nodes on this level first, before recurring
    foreach (var node in root.Children)
    {
        if (node.Property == someValue)
            yield return node;
    }

    // next check children of each node
    foreach (var node in root.Children)
    {
        var children = Traverse(node);
        foreach (var child in children)
        {
            yield return child;
        }
    }
}

Parallel.ForEach<Node>(Traverse(n), n => DoSomething(n));
</code>```

Title: Parallel tree traversal in C#

Body:
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).

Body:
I might be missing something, but I don't see the need for a while at all.  The while is just ensuring that you iterate over every node.

Instead just call your function recursively for each node in the tree.

public void Traverse(Node root)
{
    if (root.Property = someValue) DoSomething(node);
    Parallel.ForEach<Node>(root.Children, node => Traverse(node));
}

edit: of course the alternative, if you prefer to process horizontally rather than vertically and your expensive operation is DoSomething, is to do the Traverse first.

public IEnumerable<Node> Traverse(Node root)
{
    // return all the nodes on this level first, before recurring
    foreach (var node in root.Children)
    {
        if (node.Property == someValue)
            yield return node;
    }

    // next check children of each node
    foreach (var node in root.Children)
    {
        var children = Traverse(node);
        foreach (var child in children)
        {
            yield return child;
        }
    }
}

Parallel.ForEach<Node>(Traverse(n), n => DoSomething(n));


问:
ValueError: could not convert string to float: 'Default'
I am getting a Value Error, when fitting Logistic Regression model onto Corporate Default dataset.
Error is:

```<code>ValueError: could not convert string to float: 'Default'
</code>```

Can someone advise the reason for such an error and how to resolve it?
Here is my code for reference.

```<code>features = data_select_new.drop('Default', axis=1)
df['Label'] = 'Default'

X_train, X_test, Y_train, Y_test = train_test_split(features, df['Label'], test_size=0.30, random_state=42)

lr = LogisticRegression()
lr.fit(X_train, Y_train)
</code>```

答:
df['Label']= 'Default' creates a column with 'Default' on each row.
As you You probably want to predict the column 'Default' from the original daset, you can write instead:

```<code>df['Label'] = data_select_new['Default']
</code>```

Body:
I am getting a Value Error, when fitting Logistic Regression model onto Corporate Default dataset.
Error is:

ValueError: could not convert string to float: 'Default'

Can someone advise the reason for such an error and how to resolve it?
Here is my code for reference.

features = data_select_new.drop('Default', axis=1)
df['Label'] = 'Default'

X_train, X_test, Y_train, Y_test = train_test_split(features, df['Label'], test_size=0.30, random_state=42)

lr = LogisticRegression()
lr.fit(X_train, Y_train)

Body:
df['Label']= 'Default' creates a column with 'Default' on each row.
As you You probably want to predict the column 'Default' from the original daset, you can write instead:

df['Label'] = data_select_new['Default']


问:
Rails console does not autoload all directories under /app
In my Rails 5 project, I have added a new subdirectory to the app directory, app/services, which contains a simple Company service module for looking up company information that may change over time (such as contact phone number):

```<code>- project
  - app
    - services
      - company.rb
</code>```

The Company module runs fine on the development server, and the tests for the module all run without a problem. This is expected, since all subdirectories of app are included in autoload_paths by default.

However, I cannot access this module from the Rails console. From the console, app/services is not included in autoload_paths.

From the server runtime (near the bottom in both query results):

```<code>>> ActiveSupport::Dependencies.autoload_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns",
     "project/app/services",
     "project/test/mailers/previews"]

>> Rails.application.config.eager_load_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns",
     "project/app/services"]

>> Company
 => Company
</code>```

But from the console:

```<code>>> ActiveSupport::Dependencies.autoload_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns",
     "project/test/mailers/previews"]

>> Rails.application.config.eager_load_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns"]

>> Company
 => NameError: uninitialized constant Company
</code>```

(Rails.application.config.autoload_paths is empty in both cases.)

What gives? I can't seem to find this documented anywhere. All documentation takes it for granted that all subdirectories of app are always autoloaded.

Thanks in advance for any help.

Edit: Here is a duplicate question that seems to point in the right direction but leaves the actual resolution tantalizingly out of reach. I am a bit wary of going down the Rails guts rabbit hole, which is where this question leads, but perhaps that is necessary.

答:
Restart spring.

```<code>$ spring stop
$ rails console
</code>```

This solved the same problem for me.

Body:
In my Rails 5 project, I have added a new subdirectory to the app directory, app/services, which contains a simple Company service module for looking up company information that may change over time (such as contact phone number):

- project
  - app
    - services
      - company.rb

The Company module runs fine on the development server, and the tests for the module all run without a problem. This is expected, since all subdirectories of app are included in autoload_paths by default.

However, I cannot access this module from the Rails console. From the console, app/services is not included in autoload_paths.

From the server runtime (near the bottom in both query results):

>> ActiveSupport::Dependencies.autoload_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns",
     "project/app/services",
     "project/test/mailers/previews"]

>> Rails.application.config.eager_load_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns",
     "project/app/services"]

>> Company
 => Company

But from the console:

>> ActiveSupport::Dependencies.autoload_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns",
     "project/test/mailers/previews"]

>> Rails.application.config.eager_load_paths
 => ["project/app/assets",
     "project/app/channels",
     "project/app/controllers",
     "project/app/controllers/concerns",
     "project/app/helpers",
     "project/app/jobs",
     "project/app/mailers",
     "project/app/models",
     "project/app/models/concerns"]

>> Company
 => NameError: uninitialized constant Company

(Rails.application.config.autoload_paths is empty in both cases.)

What gives? I can't seem to find this documented anywhere. All documentation takes it for granted that all subdirectories of app are always autoloaded.

Thanks in advance for any help.

Edit: Here is a duplicate question that seems to point in the right direction but leaves the actual resolution tantalizingly out of reach. I am a bit wary of going down the Rails guts rabbit hole, which is where this question leads, but perhaps that is necessary.

Body:
Restart spring.

$ spring stop
$ rails console

This solved the same problem for me.


问:
"Invalid use of non-static data member" when initializing static member from global variable
```<code>class A {
    int x;
    static int i;
};

int x = 10;
int A::i = x;
</code>```

When I compile the code above, it get the error

```<code><source>:8:12: error: invalid use of non-static data member 'A::x'
    8 | int A::i = x;
      |            ^
<source>:2:9: note: declared here
    2 |     int x;
      |         ^
</code>```

What's causing this error?

答:
This is a peculiar language quirk - the scope resolution on the left, in int A::i, affects the lookup scope on the right, so that actually refers to the x member of A.

Either rename one of the variables, or specify the scope of the desired x explicitly:

```<code>int A::i = ::x;
</code>```

Body:
class A {
    int x;
    static int i;
};

int x = 10;
int A::i = x;

When I compile the code above, it get the error

<source>:8:12: error: invalid use of non-static data member 'A::x'
    8 | int A::i = x;
      |            ^
<source>:2:9: note: declared here
    2 |     int x;
      |         ^

What's causing this error?

Body:
This is a peculiar language quirk - the scope resolution on the left, in int A::i, affects the lookup scope on the right, so that actually refers to the x member of A.

Either rename one of the variables, or specify the scope of the desired x explicitly:

int A::i = ::x;


问:
Why am I getting an error with this multidimensional array?
I'm still new to Javascript and trying to understand multi-dimensional arrays. Why does the following code work?

```<code>var occupied = [[],[]];
occupied[1][0] = 0;
console.log(occupied[1][0]);
</code>```

Yet, this code does not work.

```<code>var occupied = [[],[]];
occupied[2][0] = 0;
console.log(occupied[2][0]);
</code>```

It also works with occupied[0][0]. Just not anything above 1.

答:
That's because you have defined only two items in your array (index 0 and index 1). So there is no index 2.

//      index:   0   1
var occupied = [ [], [] ];
occupied[1][0] = 0;
// works, index 1 exists
console.log(occupied[1][0]);
// error, index 2 doesn't exist
console.log(occupied[2][0]);```

Body:
I'm still new to Javascript and trying to understand multi-dimensional arrays. Why does the following code work?

var occupied = [[],[]];
occupied[1][0] = 0;
console.log(occupied[1][0]);

Yet, this code does not work.

var occupied = [[],[]];
occupied[2][0] = 0;
console.log(occupied[2][0]);

It also works with occupied[0][0]. Just not anything above 1.


问:
Zip array of structs with array of ints into array of structs column
I have a dataframe that looks like this:

```<code>val sourceData = Seq(
  Row(List(Row("a"), Row("b"), Row("c")), List(1, 2, 3)),
  Row(List(Row("d"), Row("e")), List(4, 5))
)

val sourceSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(StructField("structField", StringType))))),
  StructField("ints", ArrayType(IntegerType))
))

val sourceDF = sparkSession.createDataFrame(sourceData, sourceSchema)
</code>```

I want to transform it into a dataframe that looks like this:

```<code>val targetData = Seq(
  Row(List(Row("a", 1), Row("b", 2), Row("c", 3))),
  Row(List(Row("d", 4), Row("e", 5)))
)

val targetSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(
    StructField("structField", StringType),
    StructField("value", IntegerType)))))
))

val targetDF = sparkSession.createDataFrame(targetData, targetSchema)
</code>```

My best idea so far is to zip the two columns then run a UDF that puts the int value into the struct.

Is there an elegant way to do this, namely without UDFs?

Body:
I have a dataframe that looks like this:

val sourceData = Seq(
  Row(List(Row("a"), Row("b"), Row("c")), List(1, 2, 3)),
  Row(List(Row("d"), Row("e")), List(4, 5))
)

val sourceSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(StructField("structField", StringType))))),
  StructField("ints", ArrayType(IntegerType))
))

val sourceDF = sparkSession.createDataFrame(sourceData, sourceSchema)

I want to transform it into a dataframe that looks like this:

val targetData = Seq(
  Row(List(Row("a", 1), Row("b", 2), Row("c", 3))),
  Row(List(Row("d", 4), Row("e", 5)))
)

val targetSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(
    StructField("structField", StringType),
    StructField("value", IntegerType)))))
))

val targetDF = sparkSession.createDataFrame(targetData, targetSchema)

My best idea so far is to zip the two columns then run a UDF that puts the int value into the struct.

Is there an elegant way to do this, namely without UDFs?

Body:
Using zip_with function:

sourceDF.selectExpr(
  "zip_with(structs, ints, (x, y) -> (x.structField as structField, y as value)) as structs"
).show(false)

//+------------------------+
//|structs                 |
//+------------------------+
//|[[a, 1], [b, 2], [c, 3]]|
//|[[d, 4], [e, 5]]        |
//+------------------------+


问:
How to extend X axis datetime in Highchart
Hi I am new to HighChart, I was trying to extend the x-axis of my graph which is a datatime showing date and month.

The issue here is I am getting dates on intervals of 1 day because of tickInterval: 24 * 3600 * 1000. My last entry of data point plotted on the graph is of 3rd Feb but the tickInterval skipping the date how can Is this possible to display +1 day before the data?
In short how can I show 4th February here?

My second concern is about the tickInterval of one day which is 86400000 milliseconds. How can I show days without skipping or giving interval?
Like Showing 1Feb, 2Feb, 3Feb 4Feb without skipping any day?

Below is my code for the following chart.

```<code>Highcharts.chart('container', {
                chart: {
                    type: 'spline'
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    type: 'datetime',
                    dateTimeLabelFormats: {
                        minute: '%H:%M',
                        hour: '%H:%M',
                        day: '%e. %b',
                        week: '%e. %b',
                        month: '%b \'%y',
                        year: '%Y'

                    },
                    tickInterval: 24 * 3600 * 1000,
                    title: {
                        text: 'By Date'
                    },
                    labels: {
                        style: {
                            color: 'black',
                            fontSize: '11px'
                        }
                    }
                },
}
</code>```

答:
For showing the last tick you can use
xAxis.endOnTick, it will force to end on this one.

```<code>    xAxis: {
      endOnTick: true,
      showLastLabel: true,
      startOnTick: true
    },
</code>```

To set the tick you have the possibility to use xAxis.tickPositioner or xAxis.tickPositions to define an array with every tick.

Demo: https://jsfiddle.net/BlackLabel/n3o6uwck/

Body:
Hi I am new to HighChart, I was trying to extend the x-axis of my graph which is a datatime showing date and month.

The issue here is I am getting dates on intervals of 1 day because of tickInterval: 24 * 3600 * 1000. My last entry of data point plotted on the graph is of 3rd Feb but the tickInterval skipping the date how can Is this possible to display +1 day before the data?
In short how can I show 4th February here?

My second concern is about the tickInterval of one day which is 86400000 milliseconds. How can I show days without skipping or giving interval?
Like Showing 1Feb, 2Feb, 3Feb 4Feb without skipping any day?

Below is my code for the following chart.

Highcharts.chart('container', {
                chart: {
                    type: 'spline'
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    type: 'datetime',
                    dateTimeLabelFormats: {
                        minute: '%H:%M',
                        hour: '%H:%M',
                        day: '%e. %b',
                        week: '%e. %b',
                        month: '%b \'%y',
                        year: '%Y'

                    },
                    tickInterval: 24 * 3600 * 1000,
                    title: {
                        text: 'By Date'
                    },
                    labels: {
                        style: {
                            color: 'black',
                            fontSize: '11px'
                        }
                    }
                },
}

Body:
For showing the last tick you can use
xAxis.endOnTick, it will force to end on this one.

    xAxis: {
      endOnTick: true,
      showLastLabel: true,
      startOnTick: true
    },

To set the tick you have the possibility to use xAxis.tickPositioner or xAxis.tickPositions to define an array with every tick.

Demo: https://jsfiddle.net/BlackLabel/n3o6uwck/


答:
Size of your occupied array is 2 .
So the maximum index you can access is 1.
If you try to access any index above 1 it means that you are accessing undefined.

Now , as line 2 is,
occupied[2][0] = 0 ;
here occupied[2][0] is undefined and you cannot store anything inside undefined , which is causing you an error :)

Title: Why am I getting an error with this multidimensional array?


问:
Creating irregular shapes for a jigsaw puzzle game in flash
I want to make a jigsaw puzzle in flash. I know how to create square kind of shapes. But I want to create this kind of irregular shapes. See the live demo of puzzles in the links shown

http://www.flashcomponents.net/component/jigsawpuzzle/preview/4952.html
http://www.gamedesign.jp/flash/whitejigsaw/whitejigsaw.html

I just want to how to create the irregular shapes.

Does anyone know or can anybody give useful links as to how this can be done.

答: That's done using masking: http://www.flash-here.com/tutorials/flash_masking.html</p>


问:
Why show me different result when use coroutines in Android
I starting work with Coroutines and show some tutorials from Youtube!

I write below codes, I thins print 10 times Log message every 1 sec.

But not shown me 10 times!

Sometimes show me 6 times, sometimes 3 times, sometime 8 times and more ...

Why show me different result in LogCat ?

My Codes :

```<code>        CoroutineScope(Main).launch {
        val job = CoroutineScope(Main).launch {
            repeat(10){
                delay(1000)
                Log.e("Join", "Show")
            }
        }
        job.join()
        Log.e("Join", "Done")
    }
</code>```

Logcat logs :

```<code>2022-02-03 20:27:13.289 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:14.289 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:16.292 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:17.293 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:18.294 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:22.298 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:22.299 21152-21152/my.app.coroutines E/Join: Done
</code>```

答: You are running coroutine on the main dispatcher which is the IO thread as well. try using a different dispatcher like IO etc.</p>

Body:
I starting work with Coroutines and show some tutorials from Youtube!

I write below codes, I thins print 10 times Log message every 1 sec.

But not shown me 10 times!

Sometimes show me 6 times, sometimes 3 times, sometime 8 times and more ...

Why show me different result in LogCat ?

My Codes :

        CoroutineScope(Main).launch {
        val job = CoroutineScope(Main).launch {
            repeat(10){
                delay(1000)
                Log.e("Join", "Show")
            }
        }
        job.join()
        Log.e("Join", "Done")
    }

Logcat logs :

2022-02-03 20:27:13.289 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:14.289 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:16.292 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:17.293 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:18.294 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:22.298 21152-21152/my.app.coroutines E/Join: Show
2022-02-03 20:27:22.299 21152-21152/my.app.coroutines E/Join: Done


问:
How to push all the selected values of checkbox in an array in React-Bootstrap
I am using a react-bootstrap component Checkbox to create a general form . The component name is AdminPage, I wanted tp pass all the selected values of the checkboxes into an state (which is initialised as a state ). I am unable to do so.

Here below is the code

```<code>
import React, { useState } from "react";
import { Button, Row, Col, Dropdown, Form } from "react-bootstrap";

export const AdminPage = () => {

const [name, setName] = useState('');
const [operations, setOperation] = useState([]);

const handleSubmit = () => {
  alert("Selected Checkboxes -" + operations);
}

return (
                <>
                    <div className="p-3 border border-dark bg-light ">
                        <h3 className="text-center">Add Roles Here</h3>
                        <Form className="p-3">
                            <Form.Group as={Row} className="mb-3" controlId="formBasicText">
                                <Form.Label column sm="3">
                                    Name
                                </Form.Label>
                                <Col sm="9">
                                    <Form.Control type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter Name here..." />
                                </Col>
                            </Form.Group>
                            <Form.Group as={Row} className="mb-3" controlId="formBasicText">
                                <Form.Label column sm="3">
                                    Opeations
                                </Form.Label>
                                {/* <Col sm="9">
                                    <Form.Control type="text" value={rolecredentials.operations} onChange={(e) => onChange(e, "operations")} placeholder='Eg: GETitems, GETstocks, GETpinfences, GETinventory, ADDinventory' />
                                    <Form.Text className="text-muted mx-2">
                                        Mention multiple values using comma seperator like given in placeholder
                                    </Form.Text>
                                </Col> */}
                                <Col sm="8">
                                    <Form value={operations} >
                                    <div key={`inline-checkbox`} className="mb-3">
                                        <Form.Check
                                            inline
                                            label="GETitem"
                                            name="group1"
                                            type="checkbox"
                                            value="GETitem"

                                            id={`inline-checkbox-1`}
                                        />
                                        <Form.Check
                                            inline
                                            label="GETstocks"
                                            name="group1"
                                            type="checkbox"
                                            value="GETstocks"

                                            id={`inline-checkbox-2`}
                                        />
                                        <Form.Check
                                            inline
                                            label="GETpinfences"
                                            name="group1"
                                            type="checkbox"
                                            value="GETpinfences"

                                            id={`inline-checkbox-3`}
                                        />
                                        <Form.Check
                                            inline
                                            label="GETinventory"
                                            name="group1"
                                            type="checkbox"
                                            value="GETinventory"

                                            id={`inline-checkbox-4`}
                                        />
                                        <Form.Check
                                            inline
                                            label="ADDinventory"
                                            name="group1"
                                            type="checkbox"
                                            value="ADDinventory"

                                            id={`inline-checkbox-5`}
                                        />
                                    </div>
                                    </Form>
                                </Col>
                            </Form.Group>

                            <div className="w-25 m-auto mt-5 mb-3">
                                <Button variant="primary" type="submit" onClick={handleSubmit}>
                                    Add Role
                                </Button>
                            </div>
                        </Form>
                    </div>
                </>
            )
}
</code>```

I had tried onSelect but still not able to do so.

答:
Have you given the :checked pseudo selector a try?

```<code>const checkedElements = document.querySelectorAll(":checked");
</code>```

Edit

Oh, and the event you're looking for is onChange.

Edit*

const handleSubmit = () => {
  alert("Selected Checkboxes -" + operations);

  const checkedElements = documents.querySelectorAll(":checked");

  checkedElements.forEach((entry) => {
    /*Here we have access to each checked element.
     *So maybe define an array, push each value you want to that array
     *and finally update the state after the forEach.
     */
  });
}
```

Body:
I am using a react-bootstrap component Checkbox to create a general form . The component name is AdminPage, I wanted tp pass all the selected values of the checkboxes into an state (which is initialised as a state ). I am unable to do so.

Here below is the code

import React, { useState } from "react";
import { Button, Row, Col, Dropdown, Form } from "react-bootstrap";

export const AdminPage = () => {

const [name, setName] = useState('');
const [operations, setOperation] = useState([]);

const handleSubmit = () => {
  alert("Selected Checkboxes -" + operations);
}

return (
                <>

Add Roles Here

                        <Form className="p-3">
                            <Form.Group as={Row} className="mb-3" controlId="formBasicText">
                                <Form.Label column sm="3">
                                    Name
                                </Form.Label>
                                <Col sm="9">
                                    <Form.Control type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter Name here..." />
                                </Col>
                            </Form.Group>
                            <Form.Group as={Row} className="mb-3" controlId="formBasicText">
                                <Form.Label column sm="3">
                                    Opeations
                                </Form.Label>
                                {/* <Col sm="9">
                                    <Form.Control type="text" value={rolecredentials.operations} onChange={(e) => onChange(e, "operations")} placeholder='Eg: GETitems, GETstocks, GETpinfences, GETinventory, ADDinventory' />
                                    <Form.Text className="text-muted mx-2">
                                        Mention multiple values using comma seperator like given in placeholder
                                    </Form.Text>
                                </Col> */}
                                <Col sm="8">
                                    <Form value={operations} >
                                    <div key={`inline-checkbox`} className="mb-3">
                                        <Form.Check
                                            inline
                                            label="GETitem"
                                            name="group1"
                                            type="checkbox"
                                            value="GETitem"

                                            id={`inline-checkbox-1`}
                                        />
                                        <Form.Check
                                            inline
                                            label="GETstocks"
                                            name="group1"
                                            type="checkbox"
                                            value="GETstocks"

                                            id={`inline-checkbox-2`}
                                        />
                                        <Form.Check
                                            inline
                                            label="GETpinfences"
                                            name="group1"
                                            type="checkbox"
                                            value="GETpinfences"

                                            id={`inline-checkbox-3`}
                                        />
                                        <Form.Check
                                            inline
                                            label="GETinventory"
                                            name="group1"
                                            type="checkbox"
                                            value="GETinventory"

                                            id={`inline-checkbox-4`}
                                        />
                                        <Form.Check
                                            inline
                                            label="ADDinventory"
                                            name="group1"
                                            type="checkbox"
                                            value="ADDinventory"

                                            id={`inline-checkbox-5`}
                                        />

                                    </Form>
                                </Col>
                            </Form.Group>

                                <Button variant="primary" type="submit" onClick={handleSubmit}>
                                    Add Role
                                </Button>

                        </Form>

                </>
            )
}

I had tried onSelect but still not able to do so.

Body:
Have you given the :checked pseudo selector a try?

const checkedElements = document.querySelectorAll(":checked");

Edit

Oh, and the event you're looking for is onChange.

Edit*

const handleSubmit = () => {
  alert("Selected Checkboxes -" + operations);

  const checkedElements = documents.querySelectorAll(":checked");

  checkedElements.forEach((entry) => {
    /*Here we have access to each checked element.
     *So maybe define an array, push each value you want to that array
     *and finally update the state after the forEach.
     */
  });
}