问:
RSConfig generates a Dsn Connection String doesn't work
TL;DR.

Repro steps, take a backup of your C:\Program Files\Microsoft SQL Server\MSRS13.SSRS\Reporting Services\ReportServer\RsReportServer.config

Run this command to update the connection string in SSRS's config:

```<code>C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn>rsconfig -c -s <ServerName> -i <instanceNameIfNotDefault> -d "reportserver$ssrs" -a SQL -u sa -p "YourSAPassword" -t
</code>```

Now browse to the SSRS website and it doesn't work! To fix it either restore your config file or run through the SSRS GUI tool and it works!

How does the RsConfig utility work?

Background

After I install SSRS on an Windows 2016 Server and restore the 2 databases I need to change the Connection String in SSRS configuration file to point to the new SQL server name/instance.

Problem

When I try to change the encrypted Connection String in C:\Program Files\Microsoft SQL Server\MSRS13.SSRS\Reporting Services\ReportServer\RsReportServer.config file using the RSConfig utility:

```<code>C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn>rsconfig -c -s Server0012 -i SSRS -d "reportserver$ssrs" -a SQL -u sa -p "P@ssw0rd!" -t
</code>```

It changes the Dsn Connection String in the RsReportServer.config.

Before:
<Dsn>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAE+tJc/4Vs0a0fdH0tCY8kgQAAAAiAAAAUgBlAHAAbwByAHQAaQBuAGcAIABTAGUAcgB2AGUAcgAAABBmAAAAAQAAIAAAAC2DBxZFsfVB16r0e3......
*

After:
<Dsn>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAE+tJc/4Vs0a0fdH0tCY8kgQAAAAiAAAAUgBlAHAAbwByAHQAaQBuAGcAIABTAGUAcgB2AGUAcgAAABBmAAAAAQAAIAAAAO2nOjFDJMo........
*

However after this change, browsing to the SSRS Website results in the error:

The report server can’t connect to its database. Make sure the database is running and accessible. You can also check the report server trace log for details.

If I run the SQL Reporting Services Configuration Tool (GUI) and change the Dsn Connection String browsing to the SSRS Website works!

Obviously it changes the Dsn but I can't work out what else it does whilst the GUI tool is running. I've used ProcessMonitor and I've seen that the GUI tool does NOT use   RSConfig.exe utility, it uses itself RsConfigTool.exe! So I can't even capture command-line arguments of what the actual command/connection string should be. Also each time we change the connection string a new random one is generated so not sure how to do comparison's of actual vs expected.

I did a WinDiff of Registry keys and apart from some encrypted hexadecimal diffs, nothing stood out.

I run SQLProfiler and there were a bunch of grants that I have emulated in my PowerShell script, eg:

```<code>$sqls += @"
USE [ReportServer`$SSRSTempDB]
if not exists (select * from sysusers where issqlrole = 1 and name = 'RSExecRole')
BEGIN
 EXEC sp_addrole 'RSExecRole'
END;
GO
</code>```

My hunch is the $ sign in the SQL Database Name and the @ in the "made up/simulated" password are not getting escaped when I run the commands, eg:

```<code>$MachineName = "server0012"
$instanceName = "SSRS"
$saPassword = "P@ssw0rd!"

$rsConfigPath = "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\rsconfig.exe"
$setupArgs = -join('-c -s "', $MachineName,'" -i "', $instanceName,'" -d ','"ReportServer`$SSRS" -t -a SQL -u "sa" -p "', $saPassword,"""")

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process
Write-Host $rsConfigPath $setupArgs
$args = $setupArgs.Split(" ")
& "$rsConfigPath" $args

Restart-Service -Force "SQL Server ($instanceName)"
</code>```

When I run these vanilla commands in Command Prompt (no need to escape PowerShell characters):

```<code>rsconfig -c -s Server0012 -i SSRS -d "reportserver$ssrs" -a SQL -u sa -p "P@ssw0rd!"
</code>```

It changes the Dsn Connection String but browsing to SSRS Website gives same error (above).

How can I find out what else RsConfigTool.exe does when changing the Current Report Server Database? Or any guesses why the Connection String generated using the RSConfig Utility is out of whack - I've tried many different combinations, seems like only the RSConfigTool can actually do it?

Note 1:

I'm scripting this all up as a DevOps project and we are baking these images with packer, so nothing can be done manually.

Note 2:

The Machine is joined to the domain and renamed after SQL installed. So using a Configuration.ini file I don't think will work.

答:
The trick is you need to use the Powershell Invoke-Expression command, the server name has to include the instance name without quotes server\instance, and you DO need to escape the $ sign in the RsConfig.exe command: -d ','"reportserver<tilda>$ssrs"'

<tilda> = `   The tilda key that escapes the $ sign, see in script below.

If you don't use Invoke-Expression and escape the $ sign the DatabaseName is called ReportServer not ReportServer$SSRS

You can see this in the SSRS Logs:

library!WindowsService_1!30c!05/17/2019-03:56:29:: e ERROR: Throwing
  Microsoft.ReportingServices.Library.ReportServerDatabaseUnavailableException:
  ,
  Microsoft.ReportingServices.Library.ReportServerDatabaseUnavailableException:
  The report server cannot open a connection to the report server
  database. A connection to the database is required for all requests
  and processing. ---> System.Data.SqlClient.SqlException: A
  network-related or instance-specific error occurred while establishing
  a connection to SQL Server. The server was not found or was not
  accessible. Verify that the instance name is correct and that SQL
  Server is configured to allow remote connections. (provider: Named
  Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Here is the script I use to fix a broken SQL install on a server that's been renamed:

```<code>Param(
    [parameter(mandatory=$true,helpmessage="New Machine Name")]
    [string]$MachineName,

    [parameter(mandatory=$false,helpmessage="SQL Instance Name")]
    [string]$instanceName = "SSRS",

    [parameter(mandatory=$false,helpmessage="SQL SA Password")]
    [string]$saPassword = "P@ssword1"  #this is encrypted IRL
)

#1. Start the logging
Start-Transcript -Path "C:\temp\rename-ssrs-computer.txt"

#2. Change the SQL Server's name
Write-Host "Change the SQL Server Instance Name to $MachineName"

$moduleName = "SqlServer"
Import-Module $moduleName -Verbose

$sql = 'select @@SERVERNAME'
$serverNameQry = Invoke-SqlCmd -Serverinstance ".\$instanceName" -Query $sql -username "sa" -password $saPassword  -querytimeout ([int]::MaxValue)
$serverName = $serverNameQry.Column1

$sql = -join('sp_dropserver ''', $serverName,'''
GO
sp_addserver ''', $MachineName, "\", $instanceName,''',''local''
GO
')
Invoke-SqlCmd -Serverinstance ".\$instanceName" -Query $sql -username "sa" -password $saPassword  -querytimeout ([int]::MaxValue)

#3. Change the SSRS database permissions
$sqls = @()
$sqls += @"
USE master

DECLARE @AccountName nvarchar(260)
SET @AccountName = SUSER_SNAME(0x010100000000000514000000)
if not exists (select name from syslogins where name = @AccountName and hasaccess = 1 and isntname = 1)
BEGIN
EXEC sp_grantlogin @AccountName
END;
GO
"@

#..... all the SQL Profile trace outputs...#

Foreach ($sql in $sqls)
{
  Invoke-SqlCmd -Serverinstance ".\$instanceName" -Query $sql -username "sa" -password $saPassword  -querytimeout ([int]::MaxValue)
}

#4. Change all the registry key values with the AMI Original Computer Name
Write-Host "Change the SQL Server Name in the Registry to $MachineName"

$txt = -join('Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\130\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\90\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\140\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\130\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Services\SSIS Server]
"GroupPrefix"="SQLServerDTSUser$',$MachineName,'"
"LName"=""
"Name"="MsDtsServer"
"Type"=dword:00000004

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\Services\SSIS Server]
"GroupPrefix"="SQLServerDTSUser$',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Services\Report Server]
"Name"="ReportServer"
"LName"="ReportServer$"
"Type"=dword:00000006
"GroupPrefix"="SQLServerReportServerUser$',$MachineName,'$"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\Services\Report Server]
"Name"="ReportServer"
"LName"="ReportServer$"
"Type"=dword:00000006
"GroupPrefix"="SQLServerReportServerUser$',$MachineName,'$"'

)

Add-Content "C:\temp\output.reg" $txt
regedit /s "C:\temp\output.reg"

#5. Set the encrypted connection string DONT CHANGE THIS!!!
$rsConfigPath = "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\"
$setupArgs = -join('-c -s ', $MachineName, '\' , $instanceName,' -i ', $instanceName,' -d ','"reportserver`$ssrs"', ' -t -a SQL -u sa -p "', $saPassword,'"')
Write-Host "Setup args for RSConfig $rsConfigPath $setupArgs"
Write-Host "Running RSConfig"
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process
Write-Host $rsConfigPath $setupArgs

Set-Location "$rsConfigPath"
Invoke-Expression $("rsconfig.exe " + $setupArgs)

Write-Host "RSConfig Dsn complete, new Connection string under Dsn saved to rsconfig.config file."

#6. Restart the SQL Service
Write-Host "Restarting $instanceName"
Restart-Service -Force "SQL Server ($instanceName)"
Write-Host "Restarted $instanceName"

#7. Set regional format (date/time etc.) to English (Australia) - this applies to all users
Import-Module International
Set-Culture en-AU
# Check language list for non-US input languages, exit if found
$currentlist = Get-WinUserLanguageList
$currentlist | ForEach-Object {if(($.LanguageTag -ne "en-AU") -and ($.LanguageTag -ne "en-US")){exit}}
# Set the language list for the user, forcing English (Australia) to be the only language
Set-WinUserLanguageList en-AU -Force
Set-TimeZone -Name "AUS Eastern Standard Time"

# Lastly Stop the transcript (before the PC gets rebooted by the calling script).
Stop-Transcript
</code>```

Body:
TL;DR.

Repro steps, take a backup of your C:\Program Files\Microsoft SQL Server\MSRS13.SSRS\Reporting Services\ReportServer\RsReportServer.config

Run this command to update the connection string in SSRS's config:

C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn>rsconfig -c -s <ServerName> -i <instanceNameIfNotDefault> -d "reportserver$ssrs" -a SQL -u sa -p "YourSAPassword" -t

Now browse to the SSRS website and it doesn't work! To fix it either restore your config file or run through the SSRS GUI tool and it works!

How does the RsConfig utility work?

Background

After I install SSRS on an Windows 2016 Server and restore the 2 databases I need to change the Connection String in SSRS configuration file to point to the new SQL server name/instance.

Problem

When I try to change the encrypted Connection String in C:\Program Files\Microsoft SQL Server\MSRS13.SSRS\Reporting Services\ReportServer\RsReportServer.config file using the RSConfig utility:

C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn>rsconfig -c -s Server0012 -i SSRS -d "reportserver$ssrs" -a SQL -u sa -p "P@ssw0rd!" -t

It changes the Dsn Connection String in the RsReportServer.config.

Before:
<Dsn>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAE+tJc/4Vs0a0fdH0tCY8kgQAAAAiAAAAUgBlAHAAbwByAHQAaQBuAGcAIABTAGUAcgB2AGUAcgAAABBmAAAAAQAAIAAAAC2DBxZFsfVB16r0e3......
*

After:
<Dsn>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAE+tJc/4Vs0a0fdH0tCY8kgQAAAAiAAAAUgBlAHAAbwByAHQAaQBuAGcAIABTAGUAcgB2AGUAcgAAABBmAAAAAQAAIAAAAO2nOjFDJMo........
*

However after this change, browsing to the SSRS Website results in the error:

The report server can’t connect to its database. Make sure the database is running and accessible. You can also check the report server trace log for details.

If I run the SQL Reporting Services Configuration Tool (GUI) and change the Dsn Connection String browsing to the SSRS Website works!

Obviously it changes the Dsn but I can't work out what else it does whilst the GUI tool is running. I've used ProcessMonitor and I've seen that the GUI tool does NOT use   RSConfig.exe utility, it uses itself RsConfigTool.exe! So I can't even capture command-line arguments of what the actual command/connection string should be. Also each time we change the connection string a new random one is generated so not sure how to do comparison's of actual vs expected.

I did a WinDiff of Registry keys and apart from some encrypted hexadecimal diffs, nothing stood out.

I run SQLProfiler and there were a bunch of grants that I have emulated in my PowerShell script, eg:

$sqls += @"
USE [ReportServer`$SSRSTempDB]
if not exists (select * from sysusers where issqlrole = 1 and name = 'RSExecRole')
BEGIN
 EXEC sp_addrole 'RSExecRole'
END;
GO

My hunch is the $ sign in the SQL Database Name and the @ in the "made up/simulated" password are not getting escaped when I run the commands, eg:

$MachineName = "server0012"
$instanceName = "SSRS"
$saPassword = "P@ssw0rd!"

$rsConfigPath = "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\rsconfig.exe"
$setupArgs = -join('-c -s "', $MachineName,'" -i "', $instanceName,'" -d ','"ReportServer`$SSRS" -t -a SQL -u "sa" -p "', $saPassword,"""")

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process
Write-Host $rsConfigPath $setupArgs
$args = $setupArgs.Split(" ")
& "$rsConfigPath" $args

Restart-Service -Force "SQL Server ($instanceName)"

When I run these vanilla commands in Command Prompt (no need to escape PowerShell characters):

rsconfig -c -s Server0012 -i SSRS -d "reportserver$ssrs" -a SQL -u sa -p "P@ssw0rd!"

It changes the Dsn Connection String but browsing to SSRS Website gives same error (above).

How can I find out what else RsConfigTool.exe does when changing the Current Report Server Database? Or any guesses why the Connection String generated using the RSConfig Utility is out of whack - I've tried many different combinations, seems like only the RSConfigTool can actually do it?

Note 1:

I'm scripting this all up as a DevOps project and we are baking these images with packer, so nothing can be done manually.

Note 2:

The Machine is joined to the domain and renamed after SQL installed. So using a Configuration.ini file I don't think will work.

Body:
The trick is you need to use the Powershell Invoke-Expression command, the server name has to include the instance name without quotes server\instance, and you DO need to escape the $ sign in the RsConfig.exe command: -d ','"reportserver<tilda>$ssrs"'

<tilda> = `   The tilda key that escapes the $ sign, see in script below.

If you don't use Invoke-Expression and escape the $ sign the DatabaseName is called ReportServer not ReportServer$SSRS

You can see this in the SSRS Logs:

library!WindowsService_1!30c!05/17/2019-03:56:29:: e ERROR: Throwing
  Microsoft.ReportingServices.Library.ReportServerDatabaseUnavailableException:
  ,
  Microsoft.ReportingServices.Library.ReportServerDatabaseUnavailableException:
  The report server cannot open a connection to the report server
  database. A connection to the database is required for all requests
  and processing. ---> System.Data.SqlClient.SqlException: A
  network-related or instance-specific error occurred while establishing
  a connection to SQL Server. The server was not found or was not
  accessible. Verify that the instance name is correct and that SQL
  Server is configured to allow remote connections. (provider: Named
  Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Here is the script I use to fix a broken SQL install on a server that's been renamed:

Param(
    [parameter(mandatory=$true,helpmessage="New Machine Name")]
    [string]$MachineName,

    [parameter(mandatory=$false,helpmessage="SQL Instance Name")]
    [string]$instanceName = "SSRS",

    [parameter(mandatory=$false,helpmessage="SQL SA Password")]
    [string]$saPassword = "P@ssword1"  #this is encrypted IRL
)

#1. Start the logging
Start-Transcript -Path "C:\temp\rename-ssrs-computer.txt"

#2. Change the SQL Server's name
Write-Host "Change the SQL Server Instance Name to $MachineName"

$moduleName = "SqlServer"
Import-Module $moduleName -Verbose

$sql = 'select @@SERVERNAME'
$serverNameQry = Invoke-SqlCmd -Serverinstance ".\$instanceName" -Query $sql -username "sa" -password $saPassword  -querytimeout ([int]::MaxValue)
$serverName = $serverNameQry.Column1

$sql = -join('sp_dropserver ''', $serverName,'''
GO
sp_addserver ''', $MachineName, "\", $instanceName,''',''local''
GO
')
Invoke-SqlCmd -Serverinstance ".\$instanceName" -Query $sql -username "sa" -password $saPassword  -querytimeout ([int]::MaxValue)

#3. Change the SSRS database permissions
$sqls = @()
$sqls += @"
USE master

DECLARE @AccountName nvarchar(260)
SET @AccountName = SUSER_SNAME(0x010100000000000514000000)
if not exists (select name from syslogins where name = @AccountName and hasaccess = 1 and isntname = 1)
BEGIN
EXEC sp_grantlogin @AccountName
END;
GO
"@

#..... all the SQL Profile trace outputs...#

Foreach ($sql in $sqls)
{
  Invoke-SqlCmd -Serverinstance ".\$instanceName" -Query $sql -username "sa" -password $saPassword  -querytimeout ([int]::MaxValue)
}

#4. Change all the registry key values with the AMI Original Computer Name
Write-Host "Change the SQL Server Name in the Registry to $MachineName"

$txt = -join('Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\130\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\90\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\140\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\130\Machines]
"OriginalMachineName"="',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Services\SSIS Server]
"GroupPrefix"="SQLServerDTSUser$',$MachineName,'"
"LName"=""
"Name"="MsDtsServer"
"Type"=dword:00000004

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\Services\SSIS Server]
"GroupPrefix"="SQLServerDTSUser$',$MachineName,'"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Services\Report Server]
"Name"="ReportServer"
"LName"="ReportServer$"
"Type"=dword:00000006
"GroupPrefix"="SQLServerReportServerUser$',$MachineName,'$"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server\Services\Report Server]
"Name"="ReportServer"
"LName"="ReportServer$"
"Type"=dword:00000006
"GroupPrefix"="SQLServerReportServerUser$',$MachineName,'$"'

)

Add-Content "C:\temp\output.reg" $txt
regedit /s "C:\temp\output.reg"

#5. Set the encrypted connection string DONT CHANGE THIS!!!
$rsConfigPath = "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\"
$setupArgs = -join('-c -s ', $MachineName, '\' , $instanceName,' -i ', $instanceName,' -d ','"reportserver`$ssrs"', ' -t -a SQL -u sa -p "', $saPassword,'"')
Write-Host "Setup args for RSConfig $rsConfigPath $setupArgs"
Write-Host "Running RSConfig"
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process
Write-Host $rsConfigPath $setupArgs

Set-Location "$rsConfigPath"
Invoke-Expression $("rsconfig.exe " + $setupArgs)

Write-Host "RSConfig Dsn complete, new Connection string under Dsn saved to rsconfig.config file."

#6. Restart the SQL Service
Write-Host "Restarting $instanceName"
Restart-Service -Force "SQL Server ($instanceName)"
Write-Host "Restarted $instanceName"

#7. Set regional format (date/time etc.) to English (Australia) - this applies to all users
Import-Module International
Set-Culture en-AU
# Check language list for non-US input languages, exit if found
$currentlist = Get-WinUserLanguageList
$currentlist | ForEach-Object {if(($.LanguageTag -ne "en-AU") -and ($.LanguageTag -ne "en-US")){exit}}
# Set the language list for the user, forcing English (Australia) to be the only language
Set-WinUserLanguageList en-AU -Force
Set-TimeZone -Name "AUS Eastern Standard Time"

# Lastly Stop the transcript (before the PC gets rebooted by the calling script).
Stop-Transcript


来源: stackexchange

问:
How to choose random value from array, then choose randomly again excluding the value just chosen?
I am trying to create a combination of unique phrases to make a sentence and want to randomly select a phrase length from S (only needs to happen 1 time), and then randomly select first a J value, and then a random Q value, but I do not want the same value selected from J or S selected. How can I do this?

Here is what some of the sample outputs look like:

I3 and I1
I4 not I5
I5 or I4 and I3 not I3

```<code>Q=("but","why","okay")
J=("J1","J2","J3","J4","J5")
S=[(J), (J,Q,J), (J,Q,J,Q,J),(J,Q,J,Q,J,Q,J)]

' '.join([random.choice(i) for i in random.choice(S)])
</code>```

答:
I hope it helps

```<code>result = []
temp = S
while temp is not empty:
   random1 = random.choice(temp)
   value = random.choice(random1)
   result.append(value)
   temp2 = random1.remove(value)
   temp = temp.remove(random1)
   if temp2 is not empty:
      temp = temp.append(temp2)

print(' '.join(result))
</code>```

The key idea is that we will remove the chosen value before the next random

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a combination of unique phrases to make a sentence and want to randomly select a phrase length from S (only needs to happen 1 time), and then randomly select first a J value, and then a random Q value, but I do not want the same value selected from J or S selected. How can I do this?

Here is what some of the sample outputs look like:

I3 and I1
I4 not I5
I5 or I4 and I3 not I3

Q=("but","why","okay")
J=("J1","J2","J3","J4","J5")
S=[(J), (J,Q,J), (J,Q,J,Q,J),(J,Q,J,Q,J,Q,J)]

' '.join([random.choice(i) for i in random.choice(S)])

Body:
I hope it helps

result = []
temp = S
while temp is not empty:
   random1 = random.choice(temp)
   value = random.choice(random1)
   result.append(value)
   temp2 = random1.remove(value)
   temp = temp.remove(random1)
   if temp2 is not empty:
      temp = temp.append(temp2)

print(' '.join(result))

The key idea is that we will remove the chosen value before the next random


问:
Receiving 404 error when trying to load static urls directly in Django
When I visit the url of my static files (http://127.0.0.1:8000/site_media/static/css/site_base.css) I receive a 404 error message.

404 from the log

```<code>[27/Oct/2012 14:14:54] "GET /site_media/static/js/libs/modernizr-2.5.2.min.js HTTP/1.1" 404 1716
[27/Oct/2012 14:34:20] "GET /site_media/static/css/site_base.css HTTP/1.1" 404 1677
</code>```

Directory Structure

```<code>mysite
    |-- manage.py
    |-- mysite
         |-- settings
             |-- base.py
             |-- dev.py
             |-- prod.py
    |-- site_media
       |-- static
           |-- css
               |-- site_base.css
</code>```

site_base.html

```<code><link rel="stylesheet" href="{{ STATIC_URL }}css/site_base.css" />
</code>```

settings

```<code>TEMPLATE_CONTEXT_PROCESSORS = [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.static",
]

STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
]

STATIC_URL = "/site_media/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
</code>```

Updated:

urls.py

```<code>from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^profile/', include('profiles.urls')),
)

urlpatterns += staticfiles_urlpatterns()
</code>```

答:
use <link rel="stylesheet" href="{{ STATIC_URL }}css/site_base.css" /> instead of

<link href="{%static 'css/style.css'%}" rel="stylesheet">  and make sure your value is
STATIC_URL = '/static/' in the settings.py

ContentLicense: CC BY-SA 3.0

Body:
When I visit the url of my static files (http://127.0.0.1:8000/site_media/static/css/site_base.css) I receive a 404 error message.

404 from the log

[27/Oct/2012 14:14:54] "GET /site_media/static/js/libs/modernizr-2.5.2.min.js HTTP/1.1" 404 1716
[27/Oct/2012 14:34:20] "GET /site_media/static/css/site_base.css HTTP/1.1" 404 1677

Directory Structure

mysite
    |-- manage.py
    |-- mysite
         |-- settings
             |-- base.py
             |-- dev.py
             |-- prod.py
    |-- site_media
       |-- static
           |-- css
               |-- site_base.css

site_base.html

<link rel="stylesheet" href="{{ STATIC_URL }}css/site_base.css" />

settings

TEMPLATE_CONTEXT_PROCESSORS = [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.static",
]

STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
]

STATIC_URL = "/site_media/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")

Updated:

urls.py

from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^profile/', include('profiles.urls')),
)

urlpatterns += staticfiles_urlpatterns()


问:
How to Flexbox into a specific way?
I want to seperate my divs into something like the image below using flexbox but i'm not sure how to do it. Do I need to use absolute positions for it or does flexbox have a way to approach it without too much issue?

答:
What you have described is definitely possible. I have provided a rough outline of how it can be achieved below. This link should fill in the blanks for you. Essentially you need a container which has the display: flex and flex-direction: row attributes. Then the children inside the container will need the flex-direction and flex-grow attributes set appropriately.

You should also check this site to see if flexbox is supported by the browsers you are targeting.

edit You will also have to set the order property if you want to reorder the HTML elements - thanks to @BugsArePeopleToo who brought this up in a comment.

Title: How to Flexbox into a specific way?


问:
Problem running PHP temperature converter
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!</p>

```<code><?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

<html>

<head>
    <title>Temperature converter</title>
</head>

<body>
    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    <label>Temperature <input type="text" name="temperature"></label>
    <label>Celcius <input type="radio" name="scale" value="cel"></label>
    <label>Fahrenheit <input type="radio" name="scale" value="fah"></label>
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>
</body>

</html>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>
</code>```

答:
You forgot to use curly braces on the inner if/elseif on line 11. It should look like the following:

```<code>if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah') {
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    }
    elseif ($_POST['scale'] == 'cel') {
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    }
    else
        $output = '';
}
</code>```

Try to avoid the shorthand if-syntax where you can leave off the curly braces.

Body:
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!

<?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

    <title>Temperature converter</title>

    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    Temperature <input type="text" name="temperature">
    Celcius <input type="radio" name="scale" value="cel">
    Fahrenheit <input type="radio" name="scale" value="fah">
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>

Body:
You forgot to use curly braces on the inner if/elseif on line 11. It should look like the following:

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah') {
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    }
    elseif ($_POST['scale'] == 'cel') {
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    }
    else
        $output = '';
}

Try to avoid the shorthand if-syntax where you can leave off the curly braces.


问:
mysql result to multidimensional json array in different structure
I am struggling to achieve the correct json array format from the mysqli resultset. I have googled extensively and tried different things.

I am sql querying e-commerce orders and attempting to output them in JSON format to post to an application, in the JSON format specified by the application developer.

First tried this, outputs each line separately , not what I want:

```<code>while ( $row = $result->fetch_assoc())  {
    $orders[]=$row;
}
echo json_encode($orders, JSON_PRETTY_PRINT);
</code>```

The result was

```<code>[
    {
        "WebOrderNumber_C": "938276",
        "itemName": "B3440S"
    },
    {
        "WebOrderNumber_C": "938276",
        "itemName": "D5035G"
    },
    {
        "WebOrderNumber_C": "938276",
        "itemName": "D6015"
    }
]
</code>```

Second having googled again and read other questions on here, I tried this

```<code>while ( $row = $result->fetch_assoc())  {
$orders[$row['WebOrderNumber_C']][] = $row['itemName'];
}
echo json_encode($orders, JSON_PRETTY_PRINT);
</code>```

The result was

```<code>{
    "938276": [
        "B3440S",
        "D5035G",
        "D6015"
    ]
}
</code>```

The format I am trying to achieve is this. please help

```<code>{
    "WebOrderNumber_C": "938276",
    "shipAddress": {
        "add1": "LONDON"
    },
    "items": [{
            "itemName": "B3440S"
        },
        {
            "itemName": "B3440S"
        },
        {
            "itemName": "B3440S"
        }
    ]
}
</code>```

PS I am Using PHP 5.6.30 if that is relevant.

答:
Since the array you're adding to is nested, you need to create the parent object the first time you encounter a row with that order number. You can use an associative array for that, to make it easy to tell if the object already exists.

Then you add to the nested array, and wrap the item name in the associative array with the itemName key.

```<code>while ( $row = $result->fetch_assoc())  {
    $orderno = $row['WebOrderNumber_C'];
    if (!isset($orders[$orderno])) {
        $orders[$orderno] = [
            "WebOrderNumber_C" => $orderno,
            "shipAddress" => [
                "add1" => $row["add1"],
                // other fields here ...
            ],
            "items" => []
        ];
    }
    $orders[$orderno]["items"][] = ["itemName" => $row['itemName']];
}
$orders = array_values($orders); // Convert from associative array to indexed
echo json_encode($orders, JSON_PRETTY_PRINT);
</code>```

Body:
I am struggling to achieve the correct json array format from the mysqli resultset. I have googled extensively and tried different things.

I am sql querying e-commerce orders and attempting to output them in JSON format to post to an application, in the JSON format specified by the application developer.

First tried this, outputs each line separately , not what I want:

while ( $row = $result->fetch_assoc())  {
    $orders[]=$row;
}
echo json_encode($orders, JSON_PRETTY_PRINT);

The result was

[
    {
        "WebOrderNumber_C": "938276",
        "itemName": "B3440S"
    },
    {
        "WebOrderNumber_C": "938276",
        "itemName": "D5035G"
    },
    {
        "WebOrderNumber_C": "938276",
        "itemName": "D6015"
    }
]

Second having googled again and read other questions on here, I tried this

while ( $row = $result->fetch_assoc())  {
$orders[$row['WebOrderNumber_C']][] = $row['itemName'];
}
echo json_encode($orders, JSON_PRETTY_PRINT);

The result was

{
    "938276": [
        "B3440S",
        "D5035G",
        "D6015"
    ]
}

The format I am trying to achieve is this. please help

{
    "WebOrderNumber_C": "938276",
    "shipAddress": {
        "add1": "LONDON"
    },
    "items": [{
            "itemName": "B3440S"
        },
        {
            "itemName": "B3440S"
        },
        {
            "itemName": "B3440S"
        }
    ]
}

PS I am Using PHP 5.6.30 if that is relevant.

Body:
Since the array you're adding to is nested, you need to create the parent object the first time you encounter a row with that order number. You can use an associative array for that, to make it easy to tell if the object already exists.

Then you add to the nested array, and wrap the item name in the associative array with the itemName key.

while ( $row = $result->fetch_assoc())  {
    $orderno = $row['WebOrderNumber_C'];
    if (!isset($orders[$orderno])) {
        $orders[$orderno] = [
            "WebOrderNumber_C" => $orderno,
            "shipAddress" => [
                "add1" => $row["add1"],
                // other fields here ...
            ],
            "items" => []
        ];
    }
    $orders[$orderno]["items"][] = ["itemName" => $row['itemName']];
}
$orders = array_values($orders); // Convert from associative array to indexed
echo json_encode($orders, JSON_PRETTY_PRINT);


问:
how to get a d3.js graph's value at a particular point?
I've got a group of graphs (using angular 7 and d3.js v5).
with axis x=> date , y values, it's a curve (basis).
I'd like to be able to enter a date and display at this particular date the value. My problem is , i do not see how to retreive the calculated values for a given date.
Is it possible?
I did not find anything.

I add an image to clarify.

thanks for any help :)

答:
What you're looking for is called a bisector, and d3 has built-in functionality for it. You can create a bisect function like this:

const bisectDate = d3.bisector(d=>d.date).right;

Then use it with an inverse of a given x position. Here's the d3 documentation on its bisect methods:

https://github.com/d3/d3-array#bisectLeft

And d3 documentation on inverting scales:

https://github.com/d3/d3-scale#continuous_invert

And a working example of a line chart that bisects the mouse x position to get the value at a given date:

https://bl.ocks.org/alandunning/cfb7dcd7951826b9eacd54f0647f48d3


问:
What is 32-bit integer in JavaScript?
I was doing some coding challenges and encountered something I am not too familiar with. I am more curious to learn what it is and why it is there.

The prompt is pretty straightforward:

Given a 32-bit signed integer, reverse digits of an integer.

```<code>Example:
Input: -123
Output: -321

Example:
Input: 120
Output: 21

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
</code>```

I came up with this.

```<code>var reverse = function(x) {
    var isNegative = false;
    if(x < 0){
        isNegative = true;
        x *= -1;
    };
    var reverseX = parseInt(String(x).split('').reverse((a,b) => a - b).join(''));
    if(reverseX > Math.pow(2,32)){
      return 0;
    }
    if(isNegative){
        return -1 * reverseX
    } else {
        return reverseX;
    }
};
</code>```

However, I am stumped with some of the failing tests:

```<code>Input:
1563847412
Output:
2147483651
Expected: 0
</code>```

To my understanding, 32 bit integer is 2^32. What is its significance in JS and what happen if I started going over? (2^32 + 1)

My second question, if I may ask two, is I "anticipated" if value of reverseX exceeds 2^32, but it is still failing the test.

```<code>if (reverseX > Math.pow(2, 32)) {
  return 0;
}
</code>```

How can I appropriately return 0 when I exceeded 32-bit integer?

答:
const reverse = x => {
    let possible = x.toString().split('').reverse();
    let temp, sign, overflow;
    if(Number.isNaN(parseInt(possible[possible.length -1]))) {
      sign = possible.pop();
    }
    temp = parseInt(possible.join(''));
    overflow = temp > 2**31-1;
    if(sign) {
        if(!overflow) {
            return temp*-1;
        }
    } else {
        if(!overflow){
           return temp;
        }
    }
    return 0;
};
```

Title: What is 32-bit integer in JavaScript?

Body:
I was doing some coding challenges and encountered something I am not too familiar with. I am more curious to learn what it is and why it is there.

The prompt is pretty straightforward:

Given a 32-bit signed integer, reverse digits of an integer.

Example:
Input: -123
Output: -321

Example:
Input: 120
Output: 21

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

I came up with this.

var reverse = function(x) {
    var isNegative = false;
    if(x < 0){
        isNegative = true;
        x *= -1;
    };
    var reverseX = parseInt(String(x).split('').reverse((a,b) => a - b).join(''));
    if(reverseX > Math.pow(2,32)){
      return 0;
    }
    if(isNegative){
        return -1 * reverseX
    } else {
        return reverseX;
    }
};

However, I am stumped with some of the failing tests:

Input:
1563847412
Output:
2147483651
Expected: 0

To my understanding, 32 bit integer is 2^32. What is its significance in JS and what happen if I started going over? (2^32 + 1)

My second question, if I may ask two, is I "anticipated" if value of reverseX exceeds 2^32, but it is still failing the test.

if (reverseX > Math.pow(2, 32)) {
  return 0;
}

How can I appropriately return 0 when I exceeded 32-bit integer?


答:
Shuffle both arrays, then take elements as you need, one by one. Or sample them, if you don't want to have the originals perturbed:

```<code>Q=("but","why","okay")
J=("J1","J2","J3","J4","J5")
S=[(J,), (J,Q,J), (J,Q,J,Q,J), (J,Q,J,Q,J,Q,J)]

from random import sample, choice
from collections import Counter

seq = choice(S)
iters = { s: iter(sample(s, c)) for s, c in Counter(seq).items() }
result = ' '.join(next(iters[s]) for s in seq)
</code>```

So I pick the desired sequence first. Then I count how many times does each list appear in the chosen sequence. Then, for each unique list, I take as many random elements (without repetition) as there are appearances of the list in the sequence, then make an iterator for those choices, so I can get them one by one. The last thing left to do is to iterate over the sequence, and take the next element from the appropriate iterator.

Title: How to choose random value from array, then choose randomly again excluding the value just chosen?

Body:
Shuffle both arrays, then take elements as you need, one by one. Or sample them, if you don't want to have the originals perturbed:

Q=("but","why","okay")
J=("J1","J2","J3","J4","J5")
S=[(J,), (J,Q,J), (J,Q,J,Q,J), (J,Q,J,Q,J,Q,J)]

from random import sample, choice
from collections import Counter

seq = choice(S)
iters = { s: iter(sample(s, c)) for s, c in Counter(seq).items() }
result = ' '.join(next(iters[s]) for s in seq)

So I pick the desired sequence first. Then I count how many times does each list appear in the chosen sequence. Then, for each unique list, I take as many random elements (without repetition) as there are appearances of the list in the sequence, then make an iterator for those choices, so I can get them one by one. The last thing left to do is to iterate over the sequence, and take the next element from the appropriate iterator.


问:
PHP72 MongoDB driver with Homebrew on OSX
I have a question that might point to a misunderstanding I have with Homebrew in relation to MongoDB:

I am running XAMPP (version) with PHP 7.2.1 (which I want to use) on Mac OSX 10.12.6 (Sierra). I installed MongoDB and created configuration and data storage folder. It runs fine on command line (when using mongod and mongodb by terminal).

Now, I want to install the PHP driver for PHP 7.2.1. I followed the instructions on http://php.net/manual/en/mongodb.installation.homebrew.php
and adapted them to version 7.2, therefore:

```<code>$ brew tap homebrew/homebrew-php
$ brew install php72-mongodb
</code>```

this creates a php72 and a php72-mongodb folder in /usr/local/Cellar. However, my original (XAMPP based) PHP is in /Applications/XAMPP/ and the php there is in /Applications/XAMPP/etc/php.ini.

and simply adding:

```<code>extension="/usr/local/opt/php72-mongodb/mongodb.so"
</code>```

won't do the trick. After adding this extension, Apache won't start any more. /Applications/XAMPP/logs/php_error.log shows the following error:

```<code>[27-Feb-2018 13:11:59 UTC] PHP Warning:
PHP Startup: Unable to load dynamic library 'mongodb.so'
(tried: /Applications/XAMPP/xamppfiles/lib/php/extensions
/no-debug-non-zts-20170718/mongodb.so
(dlopen(/Applications/XAMPP/xamppfiles/lib/php/extensions/
no-debug-non-zts-20170718/mongodb.so, 9): image not found),
/Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-non-zts-
20170718/mongodb.so.so
(dlopen(/Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-
non-zts-20170718/mongodb.so.so, 9): image not found)) in Unknown on
line 0
</code>```

What is the correct way to include/connect the driver I just installed with my existing XAMPP installation? Do I need to tell Homebrew somehow where my XAMPP install is?

Given that I also have a php folder in my Homebrew (and my /usr/local/opt folder) indicates that I have a second PHP installation right now. Is this the way it is supposed to be?

答:
The PHP version coming with MAMP is incomplete, you need to get the full version here.

Then, replace your local include folder, with the include folder of that downloaded version.

Go to your terminal and run  ./configure, this will install full copy of your MAMP php.

Now that you have prepared the PHP directory, install the mongodb extension:

```<code>cd /Applications/MAMP/bin/php/php(your version ex: 7.2)/bin
</code>```

and then run pecl to install mongodb extension

```<code>./pecl install mongodb
</code>```

Now you have installed mongodb but your php should know this.

Go to php.ini file and search for ;Extension
Under this add extension=mongodb.so

Then restart your server and you are good to go, I hope this helps!

Body:
I have a question that might point to a misunderstanding I have with Homebrew in relation to MongoDB:

I am running XAMPP (version) with PHP 7.2.1 (which I want to use) on Mac OSX 10.12.6 (Sierra). I installed MongoDB and created configuration and data storage folder. It runs fine on command line (when using mongod and mongodb by terminal).

Now, I want to install the PHP driver for PHP 7.2.1. I followed the instructions on http://php.net/manual/en/mongodb.installation.homebrew.php
and adapted them to version 7.2, therefore:

$ brew tap homebrew/homebrew-php
$ brew install php72-mongodb

this creates a php72 and a php72-mongodb folder in /usr/local/Cellar. However, my original (XAMPP based) PHP is in /Applications/XAMPP/ and the php there is in /Applications/XAMPP/etc/php.ini.

and simply adding:

extension="/usr/local/opt/php72-mongodb/mongodb.so"

won't do the trick. After adding this extension, Apache won't start any more. /Applications/XAMPP/logs/php_error.log shows the following error:

[27-Feb-2018 13:11:59 UTC] PHP Warning:
PHP Startup: Unable to load dynamic library 'mongodb.so'
(tried: /Applications/XAMPP/xamppfiles/lib/php/extensions
/no-debug-non-zts-20170718/mongodb.so
(dlopen(/Applications/XAMPP/xamppfiles/lib/php/extensions/
no-debug-non-zts-20170718/mongodb.so, 9): image not found),
/Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-non-zts-
20170718/mongodb.so.so
(dlopen(/Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-
non-zts-20170718/mongodb.so.so, 9): image not found)) in Unknown on
line 0

What is the correct way to include/connect the driver I just installed with my existing XAMPP installation? Do I need to tell Homebrew somehow where my XAMPP install is?

Given that I also have a php folder in my Homebrew (and my /usr/local/opt folder) indicates that I have a second PHP installation right now. Is this the way it is supposed to be?

Body:
The PHP version coming with MAMP is incomplete, you need to get the full version here.

Then, replace your local include folder, with the include folder of that downloaded version.

Go to your terminal and run  ./configure, this will install full copy of your MAMP php.

Now that you have prepared the PHP directory, install the mongodb extension:

cd /Applications/MAMP/bin/php/php(your version ex: 7.2)/bin

and then run pecl to install mongodb extension

./pecl install mongodb

Now you have installed mongodb but your php should know this.

Go to php.ini file and search for ;Extension
Under this add extension=mongodb.so

Then restart your server and you are good to go, I hope this helps!


问:
How to find the factors of a number given the prime factorization?
If I was given the prime factorization of a number in the form [2, 2, 3, 5, 5] how would I be able to find all of the factors in the form [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

I've attempted to do this through iterated loops, but as far as I was able to figure it out, it isn't clicking on a way to get the numbers as a result more than two numbers multiplying together

```<code>def find_factors(pfacts):
    pfacts = [1] + pfacts
    temp = []
    for i in pfacts:
        for j in pfacts[i+1:]:
            if i * j not in temp:
                temp.append(i * j)
    return [1] + temp
</code>```

I know this isn't the right way to do it because it only finds a small number of the factors

```<code>[1, 2, 3, 5, 6, 10, 15]
</code>```

答:
Multiply all the combinations and add them to a set.

```<code>import itertools

def multiplyList(myList):
    # Multiply elements one by one
    result = 1
    for x in myList:
        result = result * x
    return result

factors=set()

stuff = [2, 2, 3, 5, 5]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        factors.add(multiplyList(subset))

factors=list(sorted(factors))

print(factors)
</code>```

This works as below:

```<code>[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]
</code>```

Body:
If I was given the prime factorization of a number in the form [2, 2, 3, 5, 5] how would I be able to find all of the factors in the form [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

I've attempted to do this through iterated loops, but as far as I was able to figure it out, it isn't clicking on a way to get the numbers as a result more than two numbers multiplying together

def find_factors(pfacts):
    pfacts = [1] + pfacts
    temp = []
    for i in pfacts:
        for j in pfacts[i+1:]:
            if i * j not in temp:
                temp.append(i * j)
    return [1] + temp

I know this isn't the right way to do it because it only finds a small number of the factors

[1, 2, 3, 5, 6, 10, 15]

Body:
Multiply all the combinations and add them to a set.

import itertools

def multiplyList(myList):
    # Multiply elements one by one
    result = 1
    for x in myList:
        result = result * x
    return result

factors=set()

stuff = [2, 2, 3, 5, 5]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        factors.add(multiplyList(subset))

factors=list(sorted(factors))

print(factors)

This works as below:

[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]


问:
aframe switching between mouse and entity controls
I'm having massive problems getting mouse to work after the player has been in VR.

Updating the cursor attributes didn't do anything, so I've tried removing and replacing them

```<code>  getRayCasterAttributes: function(){

    return this.data.isVR ?
      {
        cursorAttributes:{
          fuse: true,
          fuseTimeout: cursorFuseTimeout,
        },
        raycasterAttributes: {
          objects: '[data-raycastable]',
        },

      } :
      {cursorAttributes:{
        fuse: true,
        fuseTimeout: cursorFuseTimeout,
        rayOrigin:  'mouse',
      },
      raycasterAttributes: {
        objects: '[data-raycastable]',
      },
      }
  }

 if(oldData.isVR !== this.data.isVR){
      this._recticle.object3D.visible = this.data.isVR
      this._recticle.removeAttribute('raycaster')
      this._recticle.removeAttribute('cursor')
      setTimeout(() => {
        console.log(this.getRayCasterAttributes().raycasterAttributes, this.getRayCasterAttributes().cursorAttributes)
        this._recticle.setAttribute('raycaster', this.getRayCasterAttributes().raycasterAttributes)
        this._recticle.setAttribute('cursor', this.getRayCasterAttributes().cursorAttributes)
      },100)
</code>```

This kind of works switching from 2D to VR with the timeout, but switching back is another major pain.

What is the best way to do this in aframe?

I've tried this, isn't helping. Works with mouse, does not switch to cursor controls when entering VR.

```<code>  this._recticle.setAttribute('cursor', {fuse: false, rayOrigin: 'mouse'})
else
  this._recticle.setAttribute('cursor', {fuse: true,rayOrigin: 'entity', fuseTimeout: 2000})
</code>```

答:
Have a seperate cursor on the scene and in the camera, then you can have both

how separate the mouse click event and the courser click event in Aframe

https://glitch.com/edit/#!/winter-sagittarius

Body:
I'm having massive problems getting mouse to work after the player has been in VR.

Updating the cursor attributes didn't do anything, so I've tried removing and replacing them

  getRayCasterAttributes: function(){

    return this.data.isVR ?
      {
        cursorAttributes:{
          fuse: true,
          fuseTimeout: cursorFuseTimeout,
        },
        raycasterAttributes: {
          objects: '[data-raycastable]',
        },

      } :
      {cursorAttributes:{
        fuse: true,
        fuseTimeout: cursorFuseTimeout,
        rayOrigin:  'mouse',
      },
      raycasterAttributes: {
        objects: '[data-raycastable]',
      },
      }
  }

 if(oldData.isVR !== this.data.isVR){
      this._recticle.object3D.visible = this.data.isVR
      this._recticle.removeAttribute('raycaster')
      this._recticle.removeAttribute('cursor')
      setTimeout(() => {
        console.log(this.getRayCasterAttributes().raycasterAttributes, this.getRayCasterAttributes().cursorAttributes)
        this._recticle.setAttribute('raycaster', this.getRayCasterAttributes().raycasterAttributes)
        this._recticle.setAttribute('cursor', this.getRayCasterAttributes().cursorAttributes)
      },100)

This kind of works switching from 2D to VR with the timeout, but switching back is another major pain.

What is the best way to do this in aframe?

I've tried this, isn't helping. Works with mouse, does not switch to cursor controls when entering VR.

  this._recticle.setAttribute('cursor', {fuse: false, rayOrigin: 'mouse'})
else
  this._recticle.setAttribute('cursor', {fuse: true,rayOrigin: 'entity', fuseTimeout: 2000})


问:
PHP, variable wont attach to hyperlink
Im trying to send the patient ID through a  hyperlink, tho while it redirects to the correct page it is not sending the information.

><?php echo $row["surname"];?>
```

答:
Please make sure you are going to echo the variable

Echoing a variable:

```<code><?= $echoable_variable_here ?> // Use <?= ?> tags
or
<?php echo $echoable_variable_here ?> // Use echo inside <?php ?> tags
</code>```

Edit: You have placed echo outside the href attribute tag

Therefore,

Change this:

```<code><a href="./patientrecord.php?patient_id="<?php $row["patient_id"]?>><?php echo $row["surname"];?></a>
</code>```

to:

```<code><a href="./patientrecord.php?patient_id=<?php echo $row["patient_id"]?>"><?php echo $row["surname"];?></a>
</code>```

or to:

```<code><a href="./patientrecord.php?patient_id=<?= $row["patient_id"] ?>"><?php echo $row["surname"];?></a>
</code>```

Title: PHP, variable wont attach to hyperlink

Body:
Im trying to send the patient ID through a  hyperlink, tho while it redirects to the correct page it is not sending the information.

<a href="./patientrecord.php?patient_id="<?php $row["patient_id"]?>><?php echo $row["surname"];?>

Body:
Please make sure you are going to echo the variable

Echoing a variable:

<?= $echoable_variable_here ?> // Use <?= ?> tags
or
<?php echo $echoable_variable_here ?> // Use echo inside <?php ?> tags

Edit: You have placed echo outside the href attribute tag

Therefore,

Change this:

<a href="./patientrecord.php?patient_id="<?php $row["patient_id"]?>><?php echo $row["surname"];?></a>

to:

<a href="./patientrecord.php?patient_id=<?php echo $row["patient_id"]?>"><?php echo $row["surname"];?></a>

or to:

<a href="./patientrecord.php?patient_id=<?= $row["patient_id"] ?>"><?php echo $row["surname"];?></a>


问:
Protecting the admin routes using angular 6 and firebase
I am working with Angular6 using Firebase. I am currently new to Angular. I am taking course of Mosh Hamedani from codewithmosh. But the problem is I'm using angular6 and the tutorial I'm watching in Angular4.

Now Im working with protecting admin routes. Where some credentials are define in firebase.

I have to work with show and hide features if the user is admin.

Here is the data define about the user in firebase.

admin-auth-guard.service.ts

Here is the error while working on this amdin-auth file.

auth.service.ts

user.service.ts

app-user.ts

答:
The changes you have made in user.service.ts for still using angular realtime db is ok, you just need to change your canActivate method...
the userService.get(user.uid) returns angularfireobject and you need to convert that to observable by calling .valueChanges(). Thats all.</p>

```<code>canActivate() : Observable<boolean>{
      return this.auth.user$
        .switchMap( user => {
                return this.userService.get(user.uid).valueChanges();
              } )
              .map( appUser => appUser.isAdmin);

    }
</code>```

Body:
The changes you have made in user.service.ts for still using angular realtime db is ok, you just need to change your canActivate method...
the userService.get(user.uid) returns angularfireobject and you need to convert that to observable by calling .valueChanges(). Thats all.

canActivate() : Observable<boolean>{
      return this.auth.user$
        .switchMap( user => {
                return this.userService.get(user.uid).valueChanges();
              } )
              .map( appUser => appUser.isAdmin);

    }


问:
While trying to use the "fill_between" the following error is given" Input passed into argument "'y2'"is not 1-dimensional."
I am going through the Python Crash Course text and am receiving the error "Input passed into argument "'y2'"is not 1-dimensional" when attempting to use the fill_between portion of matplotlib. I am not sure why.

I have tried this in PyCharm and Anaconda, but receive the error in both IDE's. I'm fairly new to programming and so far have not ran into any issues when following the steps provided in the text, until now.
In both instances I am using Python 3.7 and Matplotlib 3.0.1

As a side note, I'm also not sure why all the months are not showing on the x-axis, but that is a separate issue.

```<code>    # Create a program where you import weather data from a csv file

# import the csv file, matplotlib(for visualizing), and datetime
import csv
from matplotlib import pyplot as plt
from datetime import datetime

# Create a variable that states the name of the file
filename = 'sitka_weather_2014.csv'
with open(filename) as file:
    # passes the file as an argument to create a reader object
    reader = csv.reader(file)
    # keeps reading until there are no more rows
    header_row = next(reader)

    # Get high temperatures and their dates from the file
    dates, highs, lows = [],[],[]
    for row in reader:
        current_date = datetime.strptime(row[0], "%Y-%m-%d")
        dates.append(current_date)
        high = int(row[1])
        highs.append(high)
        low = int(row[3])
        lows.append([low])

# Plot Data
fig = plt.figure(dpi=250, figsize=(10,6))
plt.plot(dates, highs, c='red',alpha=0.5)
plt.plot(dates,lows, c='blue', alpha=0.5)
plt.fill_between(dates,highs,lows, facecolor='blue',alpha=0.1)
# Format Plot
plt.title("Monthly High Temperatures-2014", fontsize=24)
plt.xlabel('',fontsize=10)
fig.autofmt_xdate()
plt.ylabel('Temperature (F)',fontsize=16)
plt.tick_params(axis ='both', which='major',labelsize=16)
plt.show()
</code>```

I expect the shade to show between the high and the low lines. However only the high and low line graphs show in Anaconda, and the program errors will not show the graph in PyCharm.

答:
You are treating low as a list when you have already appending it into a list. There is no need to put brackets around low in the process of appending the value into the list. To fix the problem change the line

```<code>lows.append([low])
</code>```

To:

```<code>lows.append(low)
</code>```

Body:
I am going through the Python Crash Course text and am receiving the error "Input passed into argument "'y2'"is not 1-dimensional" when attempting to use the fill_between portion of matplotlib. I am not sure why.

I have tried this in PyCharm and Anaconda, but receive the error in both IDE's. I'm fairly new to programming and so far have not ran into any issues when following the steps provided in the text, until now.
In both instances I am using Python 3.7 and Matplotlib 3.0.1

As a side note, I'm also not sure why all the months are not showing on the x-axis, but that is a separate issue.

    # Create a program where you import weather data from a csv file

# import the csv file, matplotlib(for visualizing), and datetime
import csv
from matplotlib import pyplot as plt
from datetime import datetime

# Create a variable that states the name of the file
filename = 'sitka_weather_2014.csv'
with open(filename) as file:
    # passes the file as an argument to create a reader object
    reader = csv.reader(file)
    # keeps reading until there are no more rows
    header_row = next(reader)

    # Get high temperatures and their dates from the file
    dates, highs, lows = [],[],[]
    for row in reader:
        current_date = datetime.strptime(row[0], "%Y-%m-%d")
        dates.append(current_date)
        high = int(row[1])
        highs.append(high)
        low = int(row[3])
        lows.append([low])

# Plot Data
fig = plt.figure(dpi=250, figsize=(10,6))
plt.plot(dates, highs, c='red',alpha=0.5)
plt.plot(dates,lows, c='blue', alpha=0.5)
plt.fill_between(dates,highs,lows, facecolor='blue',alpha=0.1)
# Format Plot
plt.title("Monthly High Temperatures-2014", fontsize=24)
plt.xlabel('',fontsize=10)
fig.autofmt_xdate()
plt.ylabel('Temperature (F)',fontsize=16)
plt.tick_params(axis ='both', which='major',labelsize=16)
plt.show()

I expect the shade to show between the high and the low lines. However only the high and low line graphs show in Anaconda, and the program errors will not show the graph in PyCharm.

Body:
You are treating low as a list when you have already appending it into a list. There is no need to put brackets around low in the process of appending the value into the list. To fix the problem change the line

lows.append([low])

To:

lows.append(low)


问:
The score is not updating. Can you please tell me what is wrong with the code?
The score is not updating. Please help me make the score update.
When I click the button with the function for 'addScore', the displayed score will not change to a new one.

I have tried a lot of things. Non of which have worked

var score = 0;

function addScore(){ score ++ }

function drawScore() {
 var c = document.getElementById("myCanvas");
 var ctx = c.getContext("2d");
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();
```

I am expecting it to update the score, but it does not. It remains at 0.

The problem has been solved bu the text keeps increasing and over laps it.

答:
HTML elements are not reactive to variables changes. When you created the element with drawScore you informed the current score value and inserted this into DOM, however, updating score will not update this because it is not a reference.

To make this work you will need to updated ctx text on every click.
One simple example would be:

var score = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function addScore(){
 score++;
 setScore();
}

function drawScore() {
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 setScore();
}

function setScore() {
 ctx.clearRect(0, 0, c.width, c.height);
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();

```

Body:
The score is not updating. Please help me make the score update.
When I click the button with the function for 'addScore', the displayed score will not change to a new one.

I have tried a lot of things. Non of which have worked

var score = 0;

function addScore(){ score ++ }

function drawScore() {
 var c = document.getElementById("myCanvas");
 var ctx = c.getContext("2d");
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();

I am expecting it to update the score, but it does not. It remains at 0.

The problem has been solved bu the text keeps increasing and over laps it.


问:
Timezone names for .NET application in LINUX
I have an ASP.NET CORE app.
While this code works in Windows:

```<code> var utcNow = DateTime.UtcNow;
 var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, "US Eastern Standard Time");
</code>```

Will this work when deployed on Linux Kubernetes cluster - given the harcoded timezone name  "US Eastern Standard Time"

Or do I need to configure a different name?

Thanks

Anand

答:
For TimeZoneInfo, it has different ids for Windows and Linux, you could check this issue TimeZoneInfo should have consistent Ids across Windows and Linux #2538.

For a possible workaround, you could try TimeZoneConverter like

```<code>    var utcNow = DateTime.UtcNow;
    TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Eastern Standard Time");
    var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, tzi.Id);
</code>```

Body:
I have an ASP.NET CORE app.
While this code works in Windows:

 var utcNow = DateTime.UtcNow;
 var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, "US Eastern Standard Time");

Will this work when deployed on Linux Kubernetes cluster - given the harcoded timezone name  "US Eastern Standard Time"

Or do I need to configure a different name?

Thanks

Anand

Body:
For TimeZoneInfo, it has different ids for Windows and Linux, you could check this issue TimeZoneInfo should have consistent Ids across Windows and Linux #2538.

For a possible workaround, you could try TimeZoneConverter like

    var utcNow = DateTime.UtcNow;
    TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Eastern Standard Time");
    var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, tzi.Id);


问:
How would I be able to unit test a void method?
I want to test my method which checks for the direction of movement of vehicles. It is a void method and has one parameter - integer.

As far as I know all the if's should be split into different test methods but I am not aware of how to do that.

```<code>/// <summary>
        /// checks the east neighbour of the crossing on a given cell
        /// </summary>
        /// <param name="cellNr">the cell Nr of the crossing whose neighbour ///its checked</param>

    public void CheckEast(int cellNr)
    {
        Crossing cr = Cells[cellNr].Crossing;

        //If there is east neighbour - laneIns of the current crossing with direction east are NOT endLane
        if (cells[cellNr + 1].Taken)
        {
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = false;
                }
            }

            //car should NOT be spawned from east && LaneOut of current crossing with direction east is NOT endLane
            cr.IncomingStreams[3] = "";
            cr.LaneOutList[0].EndLane = false;

            //LaneIn 'east' of the east neighbour is NOT endLane
            foreach (LaneIn laneIn in cells[cellNr + 1].Crossing.LaneInList)
            {
                if (laneIn.Direction == "east")
                {
                    laneIn.EndLane = false;
                }
            }
            //no spawned car in the neighbour from the east laneIns and LaneOut 'west' is not endlane
            cells[cellNr + 1].Crossing.IncomingStreams[1] = "";
            cells[cellNr + 1].Crossing.LaneOutList[1].EndLane = false;
            cr.Neighbours[1] = cells[cellNr + 1].Crossing;
            cells[cellNr + 1].Crossing.Neighbours[3] = cr;
        }
        //if there is NO neighbour on east side, laneIns of the current crossing are endlane(spawning point)
        //laneout is endlane, cars are erased after leaving it
        else
        {
            cr.Neighbours[1] = null;
            cr.IncomingStreams[3] = "west";
            cr.LaneOutList[0].EndLane = true;
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = true;
                }
            }
        }
    }
</code>```

答:
To literally answer your question, if a method has no return value then it must produce some other side effect. (If it doesn't return anything or have a side effect then it doesn't do anything.)

If method changes the state of the class itself you can execute the method and assert for the expected state:

```<code>public class Counter
{
    public int Value { get; private set; }

    public void Increment() => Value++;
}
</code>```

```<code>public void Counter_increments()
{
    var subject = new Counter();
    subject.Increment();
    Assert.AreEqual(1, subject.Value());
}
</code>```

Or perhaps the behavior that you want to test is your class's interaction with some dependency. There are a few ways to do that. One is to check the state of the dependency:

```<code>public class ClassThatIncrementsCounter
{
    public readonly Counter _counter;

    public ClassThatIncrementsCounter(Counter counter)
    {
        _counter = counter;
    }

    public void DoSomething()
    {
        // does something and then increments the counter
        _counter.Increment();
    }
}

[TestMethod]
public void DoSomething_increments_counter()
{
    var counter = new Counter();
    var subject = new ClassThatIncrementsCounter(counter);
    subject.DoSomething();
    Assert.AreEqual(1, counter.Value);
}
</code>```

You can also use a library like Moq to verify that your class interacted with a dependency:

```<code>public class ClassThatIncrementsCounter
{
    public readonly ICounter _counter;

    public ClassThatIncrementsCounter(ICounter counter)
    {
        _counter = counter;
    }

    public void DoSomething()
    {
        // does something and then increments the counter
        _counter.Increment();
    }
}

[TestMethod]
public void DoSomething_increments_counter()
{
    var counter = new Mock<ICounter>();

    // indicate that we want to track whether this method was called.
    counter.Setup(x => x.Increment()).Verifiable();
    var subject = new ClassThatIncrementsCounter(counter.Object);
    subject.DoSomething();

    // verify that the method was called.
    counter.Verify(x => x.Increment());
}
</code>```

In order for this to work well, as you've noted, it's necessary to break methods down into smaller chunks that we can test in isolation. If a method makes lots of decisions then in order to test fully we'd need to test for every applicable combination, or every possible branch along which the code can execute. That's why a method with lots of conditions can be harder to test.

I spent some time looking at your code, but it's not clear enough what it's actually doing to make it easy to suggest how to refactor it.

You can take larger chunks of code which get repeated like these:

```<code>        foreach (LaneIn laneIn in cr.LaneInList)
        {
            if (laneIn.Direction == "west")
            {
                laneIn.EndLane = false;
            }
        }

        foreach (LaneIn laneIn in cr.LaneInList)
        {
            if (laneIn.Direction == "west")
            {
                laneIn.EndLane = true;
            }
        }
</code>```

...and replace them with methods like this, with the exception that you would give them clear, meaningful names. I can't do that since I'm not sure what they do:

```<code>public void SetEndLaneInDirection(List<LaneIn> laneInList, string direction, bool isEnd)
{
    foreach (LaneIn laneIn in laneInList)
    {
        if (laneIn.Direction == direction)
        {
            laneIn.EndLane = isEnd;
        }
    }
}
</code>```

Now that one smaller piece of code is easier to test. Or, if you have a block of methods that all make some related update like this:

```<code>        cells[cellNr + 1].Crossing.IncomingStreams[1] = "";
        cells[cellNr + 1].Crossing.LaneOutList[1].EndLane = false;
        cr.Neighbours[1] = cells[cellNr + 1].Crossing;
        cells[cellNr + 1].Crossing.Neighbours[3] = cr;
</code>```

Then put those in a method, and again, give it a clear name.

Now you can set up the class, call the method, and assert what you expect the state to be.

The side effect is that as you replace chunks of code with well-named method calls, your code becomes easier to read, because the method calls say, in near-English, what each step is doing.

It's much harder to do after the fact. Part of the challenge is learning to write code that's already easier to test. The good news is that as we do so our code naturally becomes simpler and easier to follow. And we have tests.

Here's a great article on how to refactoring existing code to make it easier to test.

Body:
I want to test my method which checks for the direction of movement of vehicles. It is a void method and has one parameter - integer.

As far as I know all the if's should be split into different test methods but I am not aware of how to do that.

///
        /// checks the east neighbour of the crossing on a given cell
        ///
        /// <param name="cellNr">the cell Nr of the crossing whose neighbour ///its checked</param>

    public void CheckEast(int cellNr)
    {
        Crossing cr = Cells[cellNr].Crossing;

        //If there is east neighbour - laneIns of the current crossing with direction east are NOT endLane
        if (cells[cellNr + 1].Taken)
        {
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = false;
                }
            }

            //car should NOT be spawned from east && LaneOut of current crossing with direction east is NOT endLane
            cr.IncomingStreams[3] = "";
            cr.LaneOutList[0].EndLane = false;

            //LaneIn 'east' of the east neighbour is NOT endLane
            foreach (LaneIn laneIn in cells[cellNr + 1].Crossing.LaneInList)
            {
                if (laneIn.Direction == "east")
                {
                    laneIn.EndLane = false;
                }
            }
            //no spawned car in the neighbour from the east laneIns and LaneOut 'west' is not endlane
            cells[cellNr + 1].Crossing.IncomingStreams[1] = "";
            cells[cellNr + 1].Crossing.LaneOutList[1].EndLane = false;
            cr.Neighbours[1] = cells[cellNr + 1].Crossing;
            cells[cellNr + 1].Crossing.Neighbours[3] = cr;
        }
        //if there is NO neighbour on east side, laneIns of the current crossing are endlane(spawning point)
        //laneout is endlane, cars are erased after leaving it
        else
        {
            cr.Neighbours[1] = null;
            cr.IncomingStreams[3] = "west";
            cr.LaneOutList[0].EndLane = true;
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = true;
                }
            }
        }
    }

Body:
To literally answer your question, if a method has no return value then it must produce some other side effect. (If it doesn't return anything or have a side effect then it doesn't do anything.)

If method changes the state of the class itself you can execute the method and assert for the expected state:

public class Counter
{
    public int Value { get; private set; }

    public void Increment() => Value++;
}

public void Counter_increments()
{
    var subject = new Counter();
    subject.Increment();
    Assert.AreEqual(1, subject.Value());
}

Or perhaps the behavior that you want to test is your class's interaction with some dependency. There are a few ways to do that. One is to check the state of the dependency:

public class ClassThatIncrementsCounter
{
    public readonly Counter _counter;

    public ClassThatIncrementsCounter(Counter counter)
    {
        _counter = counter;
    }

    public void DoSomething()
    {
        // does something and then increments the counter
        _counter.Increment();
    }
}

[TestMethod]
public void DoSomething_increments_counter()
{
    var counter = new Counter();
    var subject = new ClassThatIncrementsCounter(counter);
    subject.DoSomething();
    Assert.AreEqual(1, counter.Value);
}

You can also use a library like Moq to verify that your class interacted with a dependency:

public class ClassThatIncrementsCounter
{
    public readonly ICounter _counter;

    public ClassThatIncrementsCounter(ICounter counter)
    {
        _counter = counter;
    }

    public void DoSomething()
    {
        // does something and then increments the counter
        _counter.Increment();
    }
}

[TestMethod]
public void DoSomething_increments_counter()
{
    var counter = new Mock<ICounter>();

    // indicate that we want to track whether this method was called.
    counter.Setup(x => x.Increment()).Verifiable();
    var subject = new ClassThatIncrementsCounter(counter.Object);
    subject.DoSomething();

    // verify that the method was called.
    counter.Verify(x => x.Increment());
}

In order for this to work well, as you've noted, it's necessary to break methods down into smaller chunks that we can test in isolation. If a method makes lots of decisions then in order to test fully we'd need to test for every applicable combination, or every possible branch along which the code can execute. That's why a method with lots of conditions can be harder to test.

I spent some time looking at your code, but it's not clear enough what it's actually doing to make it easy to suggest how to refactor it.

You can take larger chunks of code which get repeated like these:

        foreach (LaneIn laneIn in cr.LaneInList)
        {
            if (laneIn.Direction == "west")
            {
                laneIn.EndLane = false;
            }
        }

        foreach (LaneIn laneIn in cr.LaneInList)
        {
            if (laneIn.Direction == "west")
            {
                laneIn.EndLane = true;
            }
        }

...and replace them with methods like this, with the exception that you would give them clear, meaningful names. I can't do that since I'm not sure what they do:

public void SetEndLaneInDirection(List<LaneIn> laneInList, string direction, bool isEnd)
{
    foreach (LaneIn laneIn in laneInList)
    {
        if (laneIn.Direction == direction)
        {
            laneIn.EndLane = isEnd;
        }
    }
}

Now that one smaller piece of code is easier to test. Or, if you have a block of methods that all make some related update like this:

        cells[cellNr + 1].Crossing.IncomingStreams[1] = "";
        cells[cellNr + 1].Crossing.LaneOutList[1].EndLane = false;
        cr.Neighbours[1] = cells[cellNr + 1].Crossing;
        cells[cellNr + 1].Crossing.Neighbours[3] = cr;

Then put those in a method, and again, give it a clear name.

Now you can set up the class, call the method, and assert what you expect the state to be.

The side effect is that as you replace chunks of code with well-named method calls, your code becomes easier to read, because the method calls say, in near-English, what each step is doing.

It's much harder to do after the fact. Part of the challenge is learning to write code that's already easier to test. The good news is that as we do so our code naturally becomes simpler and easier to follow. And we have tests.

Here's a great article on how to refactoring existing code to make it easier to test.


问:
Launching a Viewmodel inside a Timer elapsed not working
I am trying to launch another view model inside a timer event. When I skipped this timer event, it seems that the launcher is being used fine. However, if the launch is done during within the event it doesn't. Can someone please see where the problem is?

```<code>using System.Timers;
using Caliburn.Micro.Xamarin.Forms;
using MyProject.Resources;
using System.Windows.Input;
using Xamarin.Forms;
using System.Diagnostics;

namespace MyProject.ViewModels
{
    public class PairingDeviceViewModel : BaseScreen {
    public INavigationService NavigationService { get; set; }

    private Timer timer;
    private const float MAX = 20;
    private string percentage;
    private float rate;

    public float Rate { get => rate; set => Set(ref rate, value); }
    public string Percentage { get => percentage; set => Set(ref percentage, value); }

    protected override void OnInitialize()
    {
        base.OnInitialize();

        timer = new Timer
        {
            Interval = MAX,
        };
    }

    protected override void OnActivate()
    {
        base.OnActivate();
        timer.Elapsed += Timer_Elapsed;
        timer.Start();
    }

    protected override void OnDeactivate(bool close)
    {
        base.OnDeactivate(close);
        timer.Elapsed -= Timer_Elapsed;
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Debug.WriteLine($"Timer_Elapsed");
        Debug.WriteLine($"Rate {Rate}");
        Rate++;
        Percentage = string.Format(StringResources.PercentageNumber, Rate);
        NotifyOfPropertyChange(() => Percentage);
        if (Rate == MAX)
        {
            timer.Stop();
            Debug.WriteLine($"navigation begins");
            NavigationService.NavigateToViewModelAsync<ConfigurationListViewModel>();
        }
        Debug.WriteLine($"Timer_Elapsed END");
    }

    public ICommand SkipBluetoothScanning => new Command(() => {
        timer.Stop();
        NavigationService.NavigateToViewModelAsync<ConfigurationListViewModel>();
    });
}
</code>```

So on my Timer_elapsed method, I am calling the NavigationService.NavigateToViewModelAsync<>.. once the Rate is equal to MAX. The problem with this one is that this condition Rate==MAX has been called more than once.

Please see the log file.

```<code>Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Timer_Elapsed END
Timer_Elapsed
Rate 11
Timer_Elapsed END
Timer_Elapsed
Rate 12
Timer_Elapsed END
Timer_Elapsed
Rate 13
Timer_Elapsed END
Timer_Elapsed
Rate 14
Timer_Elapsed END
Timer_Elapsed
Rate 15
Timer_Elapsed END
Timer_Elapsed
Rate 16
Timer_Elapsed END
Timer_Elapsed
Timer_Elapsed END
Rate 17
Timer_Elapsed
Rate 18
Timer_Elapsed END
Timer_Elapsed
Rate 19
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END
</code>```

Is DispatcherTimer a better solution for this or another feature if ever?

Thanks a lot.

答:
you could lock the thread to avoid duplicate execution like this:</p>

```<code>private void Timer_Elapsed(object sender, ElapsedEventArgs e)
  {
     lock (this)
        {
         if (Math.Abs(Rate - MAX) < double.Epsilon){
             //something you want to do
               ...
            }
        }
  }
</code>```

Body:
I am trying to launch another view model inside a timer event. When I skipped this timer event, it seems that the launcher is being used fine. However, if the launch is done during within the event it doesn't. Can someone please see where the problem is?

using System.Timers;
using Caliburn.Micro.Xamarin.Forms;
using MyProject.Resources;
using System.Windows.Input;
using Xamarin.Forms;
using System.Diagnostics;

namespace MyProject.ViewModels
{
    public class PairingDeviceViewModel : BaseScreen {
    public INavigationService NavigationService { get; set; }

    private Timer timer;
    private const float MAX = 20;
    private string percentage;
    private float rate;

    public float Rate { get => rate; set => Set(ref rate, value); }
    public string Percentage { get => percentage; set => Set(ref percentage, value); }

    protected override void OnInitialize()
    {
        base.OnInitialize();

        timer = new Timer
        {
            Interval = MAX,
        };
    }

    protected override void OnActivate()
    {
        base.OnActivate();
        timer.Elapsed += Timer_Elapsed;
        timer.Start();
    }

    protected override void OnDeactivate(bool close)
    {
        base.OnDeactivate(close);
        timer.Elapsed -= Timer_Elapsed;
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Debug.WriteLine($"Timer_Elapsed");
        Debug.WriteLine($"Rate {Rate}");
        Rate++;
        Percentage = string.Format(StringResources.PercentageNumber, Rate);
        NotifyOfPropertyChange(() => Percentage);
        if (Rate == MAX)
        {
            timer.Stop();
            Debug.WriteLine($"navigation begins");
            NavigationService.NavigateToViewModelAsync<ConfigurationListViewModel>();
        }
        Debug.WriteLine($"Timer_Elapsed END");
    }

    public ICommand SkipBluetoothScanning => new Command(() => {
        timer.Stop();
        NavigationService.NavigateToViewModelAsync<ConfigurationListViewModel>();
    });
}

So on my Timer_elapsed method, I am calling the NavigationService.NavigateToViewModelAsync<>.. once the Rate is equal to MAX. The problem with this one is that this condition Rate==MAX has been called more than once.

Please see the log file.

Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Timer_Elapsed
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Rate 0
Timer_Elapsed END
Timer_Elapsed
Rate 11
Timer_Elapsed END
Timer_Elapsed
Rate 12
Timer_Elapsed END
Timer_Elapsed
Rate 13
Timer_Elapsed END
Timer_Elapsed
Rate 14
Timer_Elapsed END
Timer_Elapsed
Rate 15
Timer_Elapsed END
Timer_Elapsed
Rate 16
Timer_Elapsed END
Timer_Elapsed
Timer_Elapsed END
Rate 17
Timer_Elapsed
Rate 18
Timer_Elapsed END
Timer_Elapsed
Rate 19
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
navigation begins
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END
Timer_Elapsed END
[InputMethodManager] HSIFW - flag : 0 Pid : 6116
Timer_Elapsed END

Is DispatcherTimer a better solution for this or another feature if ever?

Thanks a lot.

Body:
you could lock the thread to avoid duplicate execution like this:

private void Timer_Elapsed(object sender, ElapsedEventArgs e)
  {
     lock (this)
        {
         if (Math.Abs(Rate - MAX) < double.Epsilon){
             //something you want to do
               ...
            }
        }
  }


问:
Permanently Redirect http to https on Google App Engine Flexible with Django
I'm working on a project that uses Google Cloud Platform's App Engine in the Python 3 Flexible Environment using Django, and I'm trying to permanently redirect all requests over http to https for all routes, but so far have not been successful. I can access the site over https, but only if explicitly written in the address bar.

I've looked at this post: How to permanently redirect `http://` and `www.` URLs to `https://`? but did not find the answer useful.

The app works properly in every sense except for the redirecting. Here is my app.yaml file:

```<code># [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT myproject.wsgi

runtime_config:
  python_version: 3
# [END runtime]
</code>```

In myproject/settings.py I have these variables defined:

```<code>SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP-X-FORWARDED-PROTO', 'https')
</code>```

On my local machine, when I set SECURE_SSL_REDIRECT to True, I was redirected to https properly, even though SSL is not supported on localhost. In production, I am still able to access the site using just http.

Is there something I'm missing or doing wrong to cause the redirect not to happen?

答:
I had a similar problem and tried a number changes both in the app.yaml and also in settings.py for a custom domain (with the default ssl cert supplied by GAE).

Through trial and error I found that in settings.py updating the allowed hosts to the appropriate domains had the desired result:

```<code>ALLOWED_HOSTS = ['https://{your-project-name}.appspot.com','https://www.yourcustomdomain.com']
</code>```

Update: I am no longer sure the above is the reason as on a subsequent deploy the above was rejected and I was getting a hosts error. However the redirect is still in place... :(

Before this change I was able to switch between http:// and https:// manually in the address bar now it redirects automaticlly.

Body:
I'm working on a project that uses Google Cloud Platform's App Engine in the Python 3 Flexible Environment using Django, and I'm trying to permanently redirect all requests over http to https for all routes, but so far have not been successful. I can access the site over https, but only if explicitly written in the address bar.

I've looked at this post: How to permanently redirect `http://` and `www.` URLs to `https://`? but did not find the answer useful.

The app works properly in every sense except for the redirecting. Here is my app.yaml file:

# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT myproject.wsgi

runtime_config:
  python_version: 3
# [END runtime]

In myproject/settings.py I have these variables defined:

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP-X-FORWARDED-PROTO', 'https')

On my local machine, when I set SECURE_SSL_REDIRECT to True, I was redirected to https properly, even though SSL is not supported on localhost. In production, I am still able to access the site using just http.

Is there something I'm missing or doing wrong to cause the redirect not to happen?

Body:
I had a similar problem and tried a number changes both in the app.yaml and also in settings.py for a custom domain (with the default ssl cert supplied by GAE).

Through trial and error I found that in settings.py updating the allowed hosts to the appropriate domains had the desired result:

ALLOWED_HOSTS = ['https://{your-project-name}.appspot.com','https://www.yourcustomdomain.com']

Update: I am no longer sure the above is the reason as on a subsequent deploy the above was rejected and I was getting a hosts error. However the redirect is still in place... :(

Before this change I was able to switch between http:// and https:// manually in the address bar now it redirects automaticlly.


问:
Testing function that returns an interface
I'm having difficulty writing test for the case below.

I'm able to write test for "helper" with a mock object that only implements the functions that used by myself.

How do I write test code for the function 'new' using a mock object without mocking functions C(), D()?

It could be that the other package is written poorly that it should not return an Interface but rather the actual struct?

```<code>package main

import (
    "fmt"
)

func main() {
    New()
}

func New() {
    new(NewFromEnvironment)
}

type newTopology func()(Interface,error)

// new is non-exposed simply used for testing purpose.
func new(newTopology newTopology) {
  t,_ :=  newTopology()
  helper(t)
}

// I need to call only A and B
type topologyInterface interface {
    A() string
    B() string
}

func helper(topology topologyInterface) {
    s1 := topology.A()
    s2 := topology.B()
    fmt.Println(s1 + "," + s2)
}

// Below are from other package named "topology".
// I have no control to the code below.

type Interface interface {
    A() string
    B() string
    C() string
    D() string
    //... more
}

func NewFromEnvironment() (Interface, error) {
    return P{}, nil
}

type P struct{}

func (p P) A() string {
    return "A"
}

func (p P) B() string {
    return "B"
}

func (p P) C() string {
    return "C"
}

func (p P) D() string {
    return "D"
}

// more...
</code>```

答:
You can try creating a struct MockP which embeds P. Then MockP inherits all the methods of P, but you can shadow A() and B() with your own mock implementations. Here's an example:

```<code>package main

import (
    "fmt"
)

type Interface interface {
    A()
    B()
}

type P struct {
}

func (p P) A() {
    fmt.Println("A")
}

func (p P) B() {
    fmt.Println("B")
}

type MockP struct {
    P
}

// Shadow P's B() method
func (p MockP) B() {
    fmt.Println("Mock B")
}

func main() {
    var p Interface = MockP{}
    p.A()
    p.B()
}
</code>```

Output:

A
Mock B
```

Body:
I'm having difficulty writing test for the case below.

I'm able to write test for "helper" with a mock object that only implements the functions that used by myself.

How do I write test code for the function 'new' using a mock object without mocking functions C(), D()?

It could be that the other package is written poorly that it should not return an Interface but rather the actual struct?

package main

import (
    "fmt"
)

func main() {
    New()
}

func New() {
    new(NewFromEnvironment)
}

type newTopology func()(Interface,error)

// new is non-exposed simply used for testing purpose.
func new(newTopology newTopology) {
  t,_ :=  newTopology()
  helper(t)
}

// I need to call only A and B
type topologyInterface interface {
    A() string
    B() string
}

func helper(topology topologyInterface) {
    s1 := topology.A()
    s2 := topology.B()
    fmt.Println(s1 + "," + s2)
}

// Below are from other package named "topology".
// I have no control to the code below.

type Interface interface {
    A() string
    B() string
    C() string
    D() string
    //... more
}

func NewFromEnvironment() (Interface, error) {
    return P{}, nil
}

type P struct{}

func (p P) A() string {
    return "A"
}

func (p P) B() string {
    return "B"
}

func (p P) C() string {
    return "C"
}

func (p P) D() string {
    return "D"
}

// more...

Body:
You can try creating a struct MockP which embeds P. Then MockP inherits all the methods of P, but you can shadow A() and B() with your own mock implementations. Here's an example:

package main

import (
    "fmt"
)

type Interface interface {
    A()
    B()
}

type P struct {
}

func (p P) A() {
    fmt.Println("A")
}

func (p P) B() {
    fmt.Println("B")
}

type MockP struct {
    P
}

// Shadow P's B() method
func (p MockP) B() {
    fmt.Println("Mock B")
}

func main() {
    var p Interface = MockP{}
    p.A()
    p.B()
}

Output:

A
Mock B


答:
I am a touch newer to python so I have trouble understanding some of the things already posted. Here is my answer, it is longer but may be easier for a beginner to follow.

```<code>import numpy as np
import itertools

factors = [2, 2, 3, 5, 5]

al = []
for i in range(len(factors)):
    for combo in itertools.combinations(factors,i):
        al.append(np.prod(combo))

print(np.unique(al))
</code>```

output:

```<code>[  1.   2.   3.   4.   5.   6.  10.  12.  15.  20.  25.  30.  50.  60.
  75. 100. 150.]
</code>```

Title: How to find the factors of a number given the prime factorization?

Body:
If I was given the prime factorization of a number in the form [2, 2, 3, 5, 5] how would I be able to find all of the factors in the form [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

I've attempted to do this through iterated loops, but as far as I was able to figure it out, it isn't clicking on a way to get the numbers as a result more than two numbers multiplying together

def find_factors(pfacts):
    pfacts = [1] + pfacts
    temp = []
    for i in pfacts:
        for j in pfacts[i+1:]:
            if i * j not in temp:
                temp.append(i * j)
    return [1] + temp

I know this isn't the right way to do it because it only finds a small number of the factors

[1, 2, 3, 5, 6, 10, 15]

Body:
I am a touch newer to python so I have trouble understanding some of the things already posted. Here is my answer, it is longer but may be easier for a beginner to follow.

import numpy as np
import itertools

factors = [2, 2, 3, 5, 5]

al = []
for i in range(len(factors)):
    for combo in itertools.combinations(factors,i):
        al.append(np.prod(combo))

print(np.unique(al))

output:

[  1.   2.   3.   4.   5.   6.  10.  12.  15.  20.  25.  30.  50.  60.
  75. 100. 150.]