问:
Installing GitHub for Windows
I'm trying to install GitHub for Windows.  I tried installing it the normal way and got this error:

Application installation did not succeed.  Cannot locate application files on the server.  Contact the application vendor or your administrator for assistance.

Clicking on Details... gave me this:

```<code>PLATFORM VERSION INFO
    Windows             : 6.1.7601.65536 (Win32NT)
    Common Language Runtime     : 4.0.30319.18034
    System.Deployment.dll       : 4.0.30319.17929 built by: FX45RTMREL
    clr.dll             : 4.0.30319.18034 built by: FX45RTMGDR
    dfdll.dll           : 4.0.30319.17929 built by: FX45RTMREL
    dfshim.dll          : 4.0.41209.0 (Main.041209-0000)

SOURCES
    Deployment url          : http://github-windows.s3.amazonaws.com/GitHub.application
                        Server      : AmazonS3
    Application url         : http://github-windows.s3.amazonaws.com/Application%20Files/GitHub_1_0_47_0/GitHub.exe.manifest
                        Server      : AmazonS3

IDENTITIES
    Deployment Identity     : GitHub.application, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86
    Application Identity        : GitHub.exe, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86, type=win32

APPLICATION SUMMARY
    * Installable application.
    * Trust url parameter is set.
ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of http://github-windows.s3.amazonaws.com/GitHub.application resulted in exception. Following failure messages were detected:
        + Downloading http://github-windows.s3.amazonaws.com/Application Files/GitHub_1_0_47_0/msvcp100.dll.deploy did not succeed.
        + The remote server returned an error: (403) Forbidden.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [5/21/2013 8:19:19 AM] : Activation of http://github-windows.s3.amazonaws.com/GitHub.application has started.
    * [5/21/2013 8:19:19 AM] : Processing of deployment manifest has successfully completed.
    * [5/21/2013 8:19:19 AM] : Installation of the application has started.
    * [5/21/2013 8:19:20 AM] : Processing of application manifest has successfully completed.
    * [5/21/2013 8:19:24 AM] : Found compatible runtime version 4.0.30319.
    * [5/21/2013 8:19:24 AM] : Request of trust and detection of platform is complete.

ERROR DETAILS
    Following errors were detected during this operation.
    * [5/21/2013 8:19:25 AM] System.Deployment.Application.DeploymentDownloadException (Unknown subtype)
        - Downloading http://github-windows.s3.amazonaws.com/Application Files/GitHub_1_0_47_0/msvcp100.dll.deploy did not succeed.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
            at System.Deployment.Application.SystemNetDownloader.DownloadAllFiles()
            at System.Deployment.Application.FileDownloader.Download(SubscriptionState subState)
            at System.Deployment.Application.DownloadManager.DownloadDependencies(SubscriptionState subState, AssemblyManifest deployManifest, AssemblyManifest appManifest, Uri sourceUriBase, String targetDirectory, String group, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
        --- Inner Exception ---
        System.Net.WebException
        - The remote server returned an error: (403) Forbidden.
        - Source: System
        - Stack trace:
            at System.Net.HttpWebRequest.GetResponse()
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.
</code>```

I followed the advice on this post and downloaded github-windows.s3.amazonaws.com/GitHub.application with the latest version of Chrome.  When I tried to run it, I got this error:

Application cannot be started.  Contact the application vendor.

With this detail:

```<code>PLATFORM VERSION INFO
    Windows             : 6.1.7601.65536 (Win32NT)
    Common Language Runtime     : 4.0.30319.18034
    System.Deployment.dll       : 4.0.30319.17929 built by: FX45RTMREL
    clr.dll             : 4.0.30319.18034 built by: FX45RTMGDR
    dfdll.dll           : 4.0.30319.17929 built by: FX45RTMREL
    dfshim.dll          : 4.0.41209.0 (Main.041209-0000)

SOURCES
    Deployment url          : file:///C:/Users/SESA277661/Downloads/GitHub.application

IDENTITIES
    Deployment Identity     : GitHub.application, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86

APPLICATION SUMMARY
    * Installable application.
    * Trust url parameter is set.
ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of C:\Users\SESA277661\Downloads\GitHub.application resulted in exception. Following failure messages were detected:
        + Deployment and application do not have matching security zones.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [5/21/2013 8:29:33 AM] : Activation of C:\Users\SESA277661\Downloads\GitHub.application has started.
    * [5/21/2013 8:29:33 AM] : Processing of deployment manifest has successfully completed.
    * [5/21/2013 8:29:33 AM] : Installation of the application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [5/21/2013 8:29:33 AM] System.Deployment.Application.InvalidDeploymentException (Zone)
        - Deployment and application do not have matching security zones.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, IDownloadNotification notification, DownloadOptions options, Uri& appSourceUri, String& appManifestPath)
            at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, Uri& appSourceUri, String& appManifestPath)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.
</code>```

From here I'm stuck.  Any advice would be much appreciated.

I'm on a work computer, so there may be some security settings blocking something, but I don't know about all that.

Thanks,
Chris

答:
A little more elaboration on the previous answers:

1- Open Windows Explorer (press "Windows+E")

2- Type %LocalAppData%\Apps in its address bar and press Enter.

3- It should find a folder "2". Delete the Folder "2".

4- Open Task Manager (Start menu, then type Task manager and select it.
Alternatively press Ctrl+Alt+Delete and select Task Manager).

5- Click on "Details" tab.

6- Kill all the files named dfsvc.exe (for me there were two).

7- Open Internet Explorer (IE)

8- Paste this address in the address bar and press Enter:

https://github-windows.s3.amazonaws.com/GitHub.application

9- It will start installing Github for Wiindows.

Title: Installing GitHub for Windows

Body:
I'm trying to install GitHub for Windows.  I tried installing it the normal way and got this error:

Application installation did not succeed.  Cannot locate application files on the server.  Contact the application vendor or your administrator for assistance.

Clicking on Details... gave me this:

PLATFORM VERSION INFO
    Windows             : 6.1.7601.65536 (Win32NT)
    Common Language Runtime     : 4.0.30319.18034
    System.Deployment.dll       : 4.0.30319.17929 built by: FX45RTMREL
    clr.dll             : 4.0.30319.18034 built by: FX45RTMGDR
    dfdll.dll           : 4.0.30319.17929 built by: FX45RTMREL
    dfshim.dll          : 4.0.41209.0 (Main.041209-0000)

SOURCES
    Deployment url          : http://github-windows.s3.amazonaws.com/GitHub.application
                        Server      : AmazonS3
    Application url         : http://github-windows.s3.amazonaws.com/Application%20Files/GitHub_1_0_47_0/GitHub.exe.manifest
                        Server      : AmazonS3

IDENTITIES
    Deployment Identity     : GitHub.application, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86
    Application Identity        : GitHub.exe, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86, type=win32

APPLICATION SUMMARY
    * Installable application.
    * Trust url parameter is set.
ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of http://github-windows.s3.amazonaws.com/GitHub.application resulted in exception. Following failure messages were detected:
        + Downloading http://github-windows.s3.amazonaws.com/Application Files/GitHub_1_0_47_0/msvcp100.dll.deploy did not succeed.
        + The remote server returned an error: (403) Forbidden.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [5/21/2013 8:19:19 AM] : Activation of http://github-windows.s3.amazonaws.com/GitHub.application has started.
    * [5/21/2013 8:19:19 AM] : Processing of deployment manifest has successfully completed.
    * [5/21/2013 8:19:19 AM] : Installation of the application has started.
    * [5/21/2013 8:19:20 AM] : Processing of application manifest has successfully completed.
    * [5/21/2013 8:19:24 AM] : Found compatible runtime version 4.0.30319.
    * [5/21/2013 8:19:24 AM] : Request of trust and detection of platform is complete.

ERROR DETAILS
    Following errors were detected during this operation.
    * [5/21/2013 8:19:25 AM] System.Deployment.Application.DeploymentDownloadException (Unknown subtype)
        - Downloading http://github-windows.s3.amazonaws.com/Application Files/GitHub_1_0_47_0/msvcp100.dll.deploy did not succeed.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
            at System.Deployment.Application.SystemNetDownloader.DownloadAllFiles()
            at System.Deployment.Application.FileDownloader.Download(SubscriptionState subState)
            at System.Deployment.Application.DownloadManager.DownloadDependencies(SubscriptionState subState, AssemblyManifest deployManifest, AssemblyManifest appManifest, Uri sourceUriBase, String targetDirectory, String group, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
        --- Inner Exception ---
        System.Net.WebException
        - The remote server returned an error: (403) Forbidden.
        - Source: System
        - Stack trace:
            at System.Net.HttpWebRequest.GetResponse()
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

I followed the advice on this post and downloaded github-windows.s3.amazonaws.com/GitHub.application with the latest version of Chrome.  When I tried to run it, I got this error:

Application cannot be started.  Contact the application vendor.

With this detail:

PLATFORM VERSION INFO
    Windows             : 6.1.7601.65536 (Win32NT)
    Common Language Runtime     : 4.0.30319.18034
    System.Deployment.dll       : 4.0.30319.17929 built by: FX45RTMREL
    clr.dll             : 4.0.30319.18034 built by: FX45RTMGDR
    dfdll.dll           : 4.0.30319.17929 built by: FX45RTMREL
    dfshim.dll          : 4.0.41209.0 (Main.041209-0000)

SOURCES
    Deployment url          : file:///C:/Users/SESA277661/Downloads/GitHub.application

IDENTITIES
    Deployment Identity     : GitHub.application, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86

APPLICATION SUMMARY
    * Installable application.
    * Trust url parameter is set.
ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of C:\Users\SESA277661\Downloads\GitHub.application resulted in exception. Following failure messages were detected:
        + Deployment and application do not have matching security zones.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [5/21/2013 8:29:33 AM] : Activation of C:\Users\SESA277661\Downloads\GitHub.application has started.
    * [5/21/2013 8:29:33 AM] : Processing of deployment manifest has successfully completed.
    * [5/21/2013 8:29:33 AM] : Installation of the application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [5/21/2013 8:29:33 AM] System.Deployment.Application.InvalidDeploymentException (Zone)
        - Deployment and application do not have matching security zones.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, IDownloadNotification notification, DownloadOptions options, Uri& appSourceUri, String& appManifestPath)
            at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, Uri& appSourceUri, String& appManifestPath)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

From here I'm stuck.  Any advice would be much appreciated.

I'm on a work computer, so there may be some security settings blocking something, but I don't know about all that.

Thanks,
Chris


来源: stackexchange

问:
Conditional inner join statement (VBA/SQL) to generate multiple values
I'm quite new to VBA/SQL and I'm trying to execute a conditional inner join.

I have two tables with a column in common ("CRM" and "CodeCRM") and I would like to obtain an email adress from table2 ("Desks") when something is triggered (CodeBlocage = 101) in table1 ("Flux") in order to add it to an automatic email.

```<code>Dim StrDestinataire As String
Select Case Strtable
   Case "Flux", "GAFIJOUR"

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = CurrentProject.Connection

    sSql = "Select AddMailCRM from Desks Inner Join Flux on Desks.CODECRM = Flux.CRM WHERE Flux.CODEBLOCAGE = '101'"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("AddMailCRM").Value
    End If

    StrDestinataire =  Y

    cn.Close
</code>```

Everything works great except that it should be returning more than one value for the email adress. Any leads?

Thank you

答:
There are three keywords that may cause confusion:

SELECT in sql

SELECT determines the columns in the resulting recordset. If your sql statement is SELECT Name, Number FROM Employees, the SELECT part tells you that the resulting recordset will have two columns named Name and Number.

Select Case in VBA

Select Case is a programming construct for conditionals. You'd use it when you don't want to use a bunch of If..ElseIf..Else statements, but anything you can do with If you can do with Select Case.

```<code>Select Case A
    Case "Flux"
        Execute these VBA statements when the variable A = Flux
    Case "Capacitor"
        Execute these statements when A = Capacitor
    Case Else
        Execute these statements when A is neither Flux nor Capacitor
End Select
</code>```

CASE in sql

The CASE keyword in sql is like Select Case in VBA, but it's used in the field list of a SELECT sql statement (for one).

```<code>SELECT Name, CASE WHEN Number = 1 THEN 'One' ELSE 'Two' END MyNum FROM Employees
</code>```

If you execute this recordset, you get two columns (Name, MyNum). The MyNum field will contains the text One when Number is 1 for that record and the text Two if Number is anything but 1.

Recordsets

You have both Excel and Access tags, so I'm going to assume you're using ADO in either one of those.  Your statement

```<code>Y = Select email from table2 Inner Join table1 on table2.Crm = table1.Crm WHERE table1.Code = 1
</code>```

Doesn't do anything - it wouldn't compile. Let's assume you want a variable, Y, to contain the email that would be returned if you executed that sql statement.

```<code>Sub GetEmail()

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = New ADODB.Connection
    cn.Open "MyConnectionStringGoesHere"

    sSql = "Select email from table2 Inner Join table1 on table2.Crm = table1.Crm WHERE table1.Code = 1"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("email").Value
    End If

End Sub
</code>```

In this case I have to create a recordset and execute that recordset for a certain connection. Presumably the join and the WHERE clause ensures that it will only return one record. But if it returns more, this example will only use the email from the first record.

Before I grab the Value of the email field, I make sure that the recordset returned at least one record. If it's at the beginning of the file (BOF) and at the end of the file (EOF) at the same time, that means there are no records in the recordset.

ContentLicense: CC BY-SA 3.0

Body:
I'm quite new to VBA/SQL and I'm trying to execute a conditional inner join.

I have two tables with a column in common ("CRM" and "CodeCRM") and I would like to obtain an email adress from table2 ("Desks") when something is triggered (CodeBlocage = 101) in table1 ("Flux") in order to add it to an automatic email.

Dim StrDestinataire As String
Select Case Strtable
   Case "Flux", "GAFIJOUR"

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = CurrentProject.Connection

    sSql = "Select AddMailCRM from Desks Inner Join Flux on Desks.CODECRM = Flux.CRM WHERE Flux.CODEBLOCAGE = '101'"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("AddMailCRM").Value
    End If

    StrDestinataire =  Y

    cn.Close

Everything works great except that it should be returning more than one value for the email adress. Any leads?

Thank you

Body:
There are three keywords that may cause confusion:

SELECT in sql

SELECT determines the columns in the resulting recordset. If your sql statement is SELECT Name, Number FROM Employees, the SELECT part tells you that the resulting recordset will have two columns named Name and Number.

Select Case in VBA

Select Case is a programming construct for conditionals. You'd use it when you don't want to use a bunch of If..ElseIf..Else statements, but anything you can do with If you can do with Select Case.

Select Case A
    Case "Flux"
        Execute these VBA statements when the variable A = Flux
    Case "Capacitor"
        Execute these statements when A = Capacitor
    Case Else
        Execute these statements when A is neither Flux nor Capacitor
End Select

CASE in sql

The CASE keyword in sql is like Select Case in VBA, but it's used in the field list of a SELECT sql statement (for one).

SELECT Name, CASE WHEN Number = 1 THEN 'One' ELSE 'Two' END MyNum FROM Employees

If you execute this recordset, you get two columns (Name, MyNum). The MyNum field will contains the text One when Number is 1 for that record and the text Two if Number is anything but 1.

Recordsets

You have both Excel and Access tags, so I'm going to assume you're using ADO in either one of those.  Your statement

Y = Select email from table2 Inner Join table1 on table2.Crm = table1.Crm WHERE table1.Code = 1

Doesn't do anything - it wouldn't compile. Let's assume you want a variable, Y, to contain the email that would be returned if you executed that sql statement.

Sub GetEmail()

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = New ADODB.Connection
    cn.Open "MyConnectionStringGoesHere"

    sSql = "Select email from table2 Inner Join table1 on table2.Crm = table1.Crm WHERE table1.Code = 1"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("email").Value
    End If

End Sub

In this case I have to create a recordset and execute that recordset for a certain connection. Presumably the join and the WHERE clause ensures that it will only return one record. But if it returns more, this example will only use the email from the first record.

Before I grab the Value of the email field, I make sure that the recordset returned at least one record. If it's at the beginning of the file (BOF) and at the end of the file (EOF) at the same time, that means there are no records in the recordset.


问:
Shell script to execute pgsql commands in files
I am trying to automate a set of procedures that create TEMPLATE databases.

I have a set of files (file1, file2, ... fileN), each of which contains a set of pgsql commands required for creating a TEMPLATE database.

The contents of the file (createdbtemplate1.sql) looks roughly like this:

```<code>CREATE DATABASE mytemplate1 WITH ENCODING 'UTF8';

\c mytemplate1

CREATE TABLE first_table (
 --- fields here ..
);

-- Add C language extension + functions
\i db_funcs.sql
</code>```

I want to be able to write a shell script that will execute the commands in the file, so that I can write a script like this:

```<code># run commands to create TEMPLATE db mytemplate1
# ./groksqlcommands.sh createdbtemplate1.sql

for dbname in foo foofoo foobar barbar
do
    # Need to simply create a database based on an existing template in this script
    psql CREATE DATABASE $dbname TEMPLATE mytemplate1
done
</code>```

Any suggestions on how to do this? (As you may have guessed, I'm a shell scripting newbie.)

Edit

To clarify the question further, I want to know:

How to write groksqlcommands.sh (a bash script that will run a set of pgsql cmds from file)

How to create a database based on an existing template at the command line

答:
Store your sql scripts under a root dir
Use dev,tst,prd parametrized dbs
Use find to run all your pgsql scripts as shown here
Exit on errors

Or just git clone the whole tool from here

Body:
I am trying to automate a set of procedures that create TEMPLATE databases.

I have a set of files (file1, file2, ... fileN), each of which contains a set of pgsql commands required for creating a TEMPLATE database.

The contents of the file (createdbtemplate1.sql) looks roughly like this:

CREATE DATABASE mytemplate1 WITH ENCODING 'UTF8';

\c mytemplate1

CREATE TABLE first_table (
 --- fields here ..
);

-- Add C language extension + functions
\i db_funcs.sql

I want to be able to write a shell script that will execute the commands in the file, so that I can write a script like this:

# run commands to create TEMPLATE db mytemplate1
# ./groksqlcommands.sh createdbtemplate1.sql

for dbname in foo foofoo foobar barbar
do
    # Need to simply create a database based on an existing template in this script
    psql CREATE DATABASE $dbname TEMPLATE mytemplate1
done

Any suggestions on how to do this? (As you may have guessed, I'm a shell scripting newbie.)

Edit

To clarify the question further, I want to know:

How to write groksqlcommands.sh (a bash script that will run a set of pgsql cmds from file)

How to create a database based on an existing template at the command line


问:
datatable symbols (greater, less than) in search/filter
Hello i would like to ask, im just looking on DataTables.net and its look good but i didnt find a possibility of filtering single columns with symbols.
example:
filter textarea of version column: > 1.14
im sure its possible but i didnt find it in documentation ?:-)

I find this
http://www.datatables.net/release-datatables/examples/api/multi_filter.html
thats exactly what im looking for but i cant use > or < in search textareas ?:-)

答:
I know that this is old question but I had same problem and:
1) I add additional dropdown to select operator (< > =)
2) Merge select and text values in Json array
3) Posting this array to server as column search value
4) On server side I parsed this and search...</p>


问:
Can't upgrade iPad to the latest build of iOS4.2
I have upgraded my iPad to iOS4.2 (gold master 8C134) but I didn't upgrade to the second gold master 8C134b.
Now that iOS4.2 has been made available on iTune, the gold master image has been removed off the developer account, but I am stuck in the 8C134 build of iOS4.2
iTune check for update doesn't recognize that I don't have the latest build.

Any idea how to upgrade to 8C134b, thx

答: You can download the 4.2.1 image directly from Apple.  They just don't make the link easy to find for some reason.  I expected it to be in the developer portal.  Silly me!</p>

ContentLicense: CC BY-SA 2.5


问:
How to Create a Broken Shortcut in Windows?
Suppose there's a file/directory I want to make a shortcut to, but doesn't exist yet. I would anyhow like to make a desktop shortcut to it in advance (a quick testing device for when it does exist). Is it possible?

I right click, trying to create a (broken) shortcut, and I give it the absolute path of what I'm trying to link; however, it notifies me that this path does not exist and refuses to create it.

答:
Open your cmd (maybe you need administrator permission) and type:

```<code>cd %USERPROFILE%\Desktop (choose a folder to create the shortcut)
mklink linkName targetFolderOrFile
</code>```

Examples:

```<code>mklink myShortcut C:\GhostFolder
mklink myShortcut C:\FakeFile.exe
mklink myShortcut %userprofile%\Desktop2
</code>```

You can use mklink /? for help

Body:
Open your cmd (maybe you need administrator permission) and type:

cd %USERPROFILE%\Desktop (choose a folder to create the shortcut)
mklink linkName targetFolderOrFile

Examples:

mklink myShortcut C:\GhostFolder
mklink myShortcut C:\FakeFile.exe
mklink myShortcut %userprofile%\Desktop2

You can use mklink /? for help


问:
Showing posts sorted by month in LARAVEL
I am writing an application using Laravel Framework

I want a whole post about a year for the tenth Monthly View Categories
(Not a large number of posts per month)

View created a division into 12 parts, each part of a month

I want to know how I can write entries from an array of choices each month and the same month in my box,
  Some months dont have any posts

```<code>    public function index()
{
    $histories = \App\history::where('DATE','>=',$date1)->where('DATE','<=',$date2)->get();
    return view ('year_posts',compact('histories'));
}
</code>```

this is the page that i want to show post of each month in the box

答:
You can group posts by month and then, in the blade, iterate over each group in each month.

Controller:

```<code>public function index()
{
    $histories = \App\history::selectRaw("history.*, DATE_FORMAT(DATE, '%m-%Y') year_month")->whereBetween("DATE", [$date1, $date2])->get();

    $groupedHistories = $histories->groupBy("year_month");

    return view ('year_posts',compact("groupedHistories"));
}
</code>```

year_posts.blade.php:

```<code>@foreach($groupedHistories as $yearMonth => $posts)
    @foreach($posts as $post)
        {{-- TO DO --}}
    @endforeach
@endforeach
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing an application using Laravel Framework

I want a whole post about a year for the tenth Monthly View Categories
(Not a large number of posts per month)

View created a division into 12 parts, each part of a month

I want to know how I can write entries from an array of choices each month and the same month in my box,
  Some months dont have any posts

    public function index()
{
    $histories = \App\history::where('DATE','>=',$date1)->where('DATE','<=',$date2)->get();
    return view ('year_posts',compact('histories'));
}

this is the page that i want to show post of each month in the box

Body:
You can group posts by month and then, in the blade, iterate over each group in each month.

Controller:

public function index()
{
    $histories = \App\history::selectRaw("history.*, DATE_FORMAT(DATE, '%m-%Y') year_month")->whereBetween("DATE", [$date1, $date2])->get();

    $groupedHistories = $histories->groupBy("year_month");

    return view ('year_posts',compact("groupedHistories"));
}

year_posts.blade.php:

@foreach($groupedHistories as $yearMonth => $posts)
    @foreach($posts as $post)
        {{-- TO DO --}}
    @endforeach
@endforeach


问:
Creating a DPI-Aware Application
I have a form application in C#. When I change the monitor's DPI, all the controls move.
I used the code this.AutoScaleMode = AutoScaleMode.Dpi, but it didn't avoid the problem.

Does anyone have an idea?

答:
It looks like this is a problem with Windows.  Taking out these two lines fixed everything.

```<code>this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
</code>```

This is where I got the solution:

Anchor not work during changing text size to 125% @ Telerik forums

Title: Creating a DPI-Aware Application

Body:
It looks like this is a problem with Windows.  Taking out these two lines fixed everything.

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

This is where I got the solution:

Anchor not work during changing text size to 125% @ Telerik forums


问:
Angular project did not work after ng build
My first attempt on Angularjs 2, after an ng build, it compiled to the dist folder but the index.html in the folder has all the scripts having missing reference despite it all exist in the same folder.
Has anyone encountered this before? What do you suggest?
Attached herewith is the snapshot of the error in chrome.

答:
I guess you are opening index.html just from the file system using the file:// protocol. That doesn't work, because the application is built with  tag, which says, that all relative paths should be prefixed by "/". With the file protocol, it means in the root of your file system.

You can build the application specifying a different base path:

```<code>ng build --base-href=/path/to/your/application/dist/
</code>```

You can also consider deploying it to a web server which can map all paths to your index.html (e.g. Apache + mod_rewrite), so when you hit the reload button in your browser, the application will load not matter what route.

Body:
I guess you are opening index.html just from the file system using the file:// protocol. That doesn't work, because the application is built with  tag, which says, that all relative paths should be prefixed by "/". With the file protocol, it means in the root of your file system.

You can build the application specifying a different base path:

ng build --base-href=/path/to/your/application/dist/

You can also consider deploying it to a web server which can map all paths to your index.html (e.g. Apache + mod_rewrite), so when you hit the reload button in your browser, the application will load not matter what route.


问:
Gradient opacity on borders of image
I'd like to make gradient opacity from 100% to 0% only on borders of image.

I can for example make gradient opacity on one direction of image like here( bottom has gradient)

  .opacitygradient{
  -webkit-mask-image: -webkit-gradient(linear, left top,
    left bottom, from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://placehold.it/300x300" class="opacitygradient"></code>```

But i'd like to have 10px gradient going on each side (all borders), not just one direction like in snippet above.

Any ideas?

答:
To mask off an image, you can do this.
The trick is to use two linear-gradients for the background of the container of the image, one horizontal and one vertical, that are transparent in the middle and fully white at the edges.

(Note that you will have to use another value than 255,255,255 for the rgbas if the background of the page is not white.)

.container {
  display: inline-block;
  background:
    linear-gradient(0deg, rgba(255,255,255,1), rgba(255,255,255,0) 5%,
      rgba(255,255,255,0) 95%, rgba(255,255,255,1)),
    linear-gradient(90deg, rgba(255,255,255,1), rgba(255,255,255,0) 5%,
      rgba(255,255,255,0) 95%, rgba(255,255,255,1));
}

.opacitygradient {
  vertical-align: top;
  position: relative;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="http://placehold.it/300x300" class="opacitygradient">
</div></code>```

As a bonus, it works in all browsers, not just the ones that understand mask-image.

Title: Gradient opacity on borders of image

Body:
I'd like to make gradient opacity from 100% to 0% only on borders of image.

I can for example make gradient opacity on one direction of image like here( bottom has gradient)

  .opacitygradient{
  -webkit-mask-image: -webkit-gradient(linear, left top,
    left bottom, from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
    }

But i'd like to have 10px gradient going on each side (all borders), not just one direction like in snippet above.

Any ideas?

Body:
To mask off an image, you can do this.
The trick is to use two linear-gradients for the background of the container of the image, one horizontal and one vertical, that are transparent in the middle and fully white at the edges.

(Note that you will have to use another value than 255,255,255 for the rgbas if the background of the page is not white.)

.container {
  display: inline-block;
  background:
    linear-gradient(0deg, rgba(255,255,255,1), rgba(255,255,255,0) 5%,
      rgba(255,255,255,0) 95%, rgba(255,255,255,1)),
    linear-gradient(90deg, rgba(255,255,255,1), rgba(255,255,255,0) 5%,
      rgba(255,255,255,0) 95%, rgba(255,255,255,1));
}

.opacitygradient {
  vertical-align: top;
  position: relative;
  z-index: -1;
}

<div class="container">
  <img src="http://placehold.it/300x300" class="opacitygradient">
</div>

As a bonus, it works in all browsers, not just the ones that understand mask-image.


问:
Angular component relative templateUrl
I'm developing a  modular angular application with I defined I folder path (constant : BASE_PATH : "path/to/folder") in angular-module-1 module. I want to re-used this constant in a angular component located in another module (angular-module-2)of my application. I want to use this constant many time in my project.

```<code>module.component("relationshipSearch", {
templateUrl: BASE_PATH +'/link/to/other/folder',
</code>```

witch is the best way to define this constant as a global variable visible in all the solution project
Here is my project structure:

```<code>project
|-- angular-module-1
|   |-- angular-module-1.js
|   |-- angular-module-1.html
|-- angular-module-2
|   |-- angular-module-2.js
|   |-- angular-module-2.html
</code>```

答:
Sorry, for posting on an old thread with an accepted answer, but I wanted to say that the accepted answer is not minification safe. The minification safe way to write this is:</p>

```<code>app.component('myComponent', {
  templateUrl: function($injector){
    var commmonSetting = $injector.get('namespace.CommmonSetting');
    return commmonSetting.BASE_PATH +'/link/to/other/folder';
  },
  ....
});
</code>```

Title: Angular component relative templateUrl

Body:
I'm developing a  modular angular application with I defined I folder path (constant : BASE_PATH : "path/to/folder") in angular-module-1 module. I want to re-used this constant in a angular component located in another module (angular-module-2)of my application. I want to use this constant many time in my project.

module.component("relationshipSearch", {
templateUrl: BASE_PATH +'/link/to/other/folder',

witch is the best way to define this constant as a global variable visible in all the solution project
Here is my project structure:

project
|-- angular-module-1
|   |-- angular-module-1.js
|   |-- angular-module-1.html
|-- angular-module-2
|   |-- angular-module-2.js
|   |-- angular-module-2.html

Body:
Sorry, for posting on an old thread with an accepted answer, but I wanted to say that the accepted answer is not minification safe. The minification safe way to write this is:

app.component('myComponent', {
  templateUrl: function($injector){
    var commmonSetting = $injector.get('namespace.CommmonSetting');
    return commmonSetting.BASE_PATH +'/link/to/other/folder';
  },
  ....
});


问:
Difference between recursion and iteration
What is the difference? Are these the same? If not, can someone please give me an example?

MW:
Iteration - 1 : the action or a process of iterating or repeating: as a : a procedure in which repetition of a sequence of operations yields results successively closer to a desired result b : the repetition of a sequence of computer instructions a specified number of times or until a condition is met

Recursion - 3 : a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself one or more times until a specified condition is met at which time the rest of each repetition is processed from the last one called to the first

答:
Recursion:
Eg: Take fibonacci series for example. to get any fibonacci number we have to know the previous one. So u will berform the operation (same one) on every number lesser than the given and each of this inturn calling the same method.

fib(5) = Fib (4) + 5

fib(4) = Fib (3) + 4
.
.
i.e reusing the method fib

Iteration is looping like you add 1+1+1+1+1(iteratively adding) to get 5 or 3*3*3*3*3 (iteratively multiplying)to get 3^5.


问:
TimeoutException for CloseableHttpAsyncClient
i am trying to connect consume api using CloseableHttpAsyncClient. I making call to the api with connection pool of 45 and timeout of 5 minutes. However, i get the following error:

```<code>java.util.concurrent.TimeoutException: null
    at org.apache.http.nio.pool.AbstractNIOConnPool.processPendingRequest(AbstractNIOConnPool.java:364)
    at org.apache.http.nio.pool.AbstractNIOConnPool.processNextPendingRequest(AbstractNIOConnPool.java:344)
    at org.apache.http.nio.pool.AbstractNIOConnPool.release(AbstractNIOConnPool.java:318)
    at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.releaseConnection(PoolingNHttpClientConnectionManager.java:303)
    at org.apache.http.impl.nio.client.AbstractClientExchangeHandler.releaseConnection(AbstractClientExchangeHandler.java:239)
    at org.apache.http.impl.nio.client.MainClientExec.responseCompleted(MainClientExec.java:387)
    at org.apache.http.impl.nio.client.DefaultClientExchangeHandlerImpl.responseCompleted(DefaultClientExchangeHandlerImpl.java:168)
    at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.processResponse(HttpAsyncRequestExecutor.java:436)
    at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.inputReady(HttpAsyncRequestExecutor.java:326)
    at org.apache.http.impl.nio.DefaultNHttpClientConnection.consumeInput(DefaultNHttpClientConnection.java:265)
    at org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)
    at org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:39)
    at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:114)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
    at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:588)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Then on reducing the connection pool size to 10, the number of times error is thrown is down.

i am using singleton instance of CloseableHttpAsyncClient, and do not close it for faster call.

This is how i am calling it:

```<code>httpclient.execute(post, new FutureCallback<HttpResponse>(....));
</code>```

i think, it is NOT from the api side.
any idea which this exception occurs and does it has any connection from connection pool?

答:
By looking at the source code, this happens when you set connectionRequestTimeout to a value different than the default (-1) in the connection manager (e.g. PoolingNHttpClientConnectionManager). If the pool is very busy and timeout is not enough, it will throw this exception.

To solve it, either increase the connectionRequestTimeout of the connection manager pool or set it to -1 (for indefinite wait).

Body:
i am trying to connect consume api using CloseableHttpAsyncClient. I making call to the api with connection pool of 45 and timeout of 5 minutes. However, i get the following error:

java.util.concurrent.TimeoutException: null
    at org.apache.http.nio.pool.AbstractNIOConnPool.processPendingRequest(AbstractNIOConnPool.java:364)
    at org.apache.http.nio.pool.AbstractNIOConnPool.processNextPendingRequest(AbstractNIOConnPool.java:344)
    at org.apache.http.nio.pool.AbstractNIOConnPool.release(AbstractNIOConnPool.java:318)
    at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.releaseConnection(PoolingNHttpClientConnectionManager.java:303)
    at org.apache.http.impl.nio.client.AbstractClientExchangeHandler.releaseConnection(AbstractClientExchangeHandler.java:239)
    at org.apache.http.impl.nio.client.MainClientExec.responseCompleted(MainClientExec.java:387)
    at org.apache.http.impl.nio.client.DefaultClientExchangeHandlerImpl.responseCompleted(DefaultClientExchangeHandlerImpl.java:168)
    at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.processResponse(HttpAsyncRequestExecutor.java:436)
    at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.inputReady(HttpAsyncRequestExecutor.java:326)
    at org.apache.http.impl.nio.DefaultNHttpClientConnection.consumeInput(DefaultNHttpClientConnection.java:265)
    at org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)
    at org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:39)
    at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:114)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
    at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:588)
    at java.lang.Thread.run(Thread.java:745)

Then on reducing the connection pool size to 10, the number of times error is thrown is down.

i am using singleton instance of CloseableHttpAsyncClient, and do not close it for faster call.

This is how i am calling it:

httpclient.execute(post, new FutureCallback<HttpResponse>(....));

i think, it is NOT from the api side.
any idea which this exception occurs and does it has any connection from connection pool?


问:
How to join YEARS from 2 tables with different format
I am trying to create a custom view in excel for a pivot,  I cant join the YEARSF because the tb1 format is 2016-17 and tb2 is 2016/17, how can i join these, see code below... what is the appropriate way of doing this

```<code>TB1.YEARF = TB2.YEARF
</code>```

Seems to be the issue

```<code>     SELECT TB1.YEARF,
TB1.MC,
TB1.CATEG,
TB1.ID,
TB1.TY,
TB1.CAT,
TB1.LOC,
TB2.HD0_NAME,
TB2.HD1_NAME,
TB2.HD2_NAME,
TB2.HD3_NAME,
TB2.HD4_NAME
FROM DB.TB2 TB2, DB.TB1 TB1
WHERE TB2.CAT = TB1.CAT AND TB2.LOC = TB1.LOC AND TB1.TY = TB2.TY AND TB1.YEARF = TB2.YEARF AND TB1.ID = TB2.ID
</code>```

答:
It happens that both Oracle and MySQL have REPLACE() functions.

If you change the part of your query that reads

```<code> AND TB1.YEARF = TB2.YEARF AND
</code>```

to

```<code> AND TB1.YEARF = REPLACE(TB2.YEARF, '/', '-') AND
</code>```

you may be able to join these tables.  It's not going to be fast.

In general, to do this kind of inexact matching, you have to

figure out the rules for matching. For example, if you want abcd/ef to match abcd-ef then you can use what I wrote above.  If you want abcd/ef to match abcd, that's a different rule.

Write a SQL expression to implement your rules.

But, you know, step 1 must come before step 2.

If all you care about is matching the abcd parts of abcd/ef and abcd-ef you can write a rule for that.

```<code> AND SUBSTR(TB1.YEARF, 1, 4) = SUBSTR(TB2.YEARF, 1, 4) AND
</code>```

Body:
I am trying to create a custom view in excel for a pivot,  I cant join the YEARSF because the tb1 format is 2016-17 and tb2 is 2016/17, how can i join these, see code below... what is the appropriate way of doing this

TB1.YEARF = TB2.YEARF

Seems to be the issue

     SELECT TB1.YEARF,
TB1.MC,
TB1.CATEG,
TB1.ID,
TB1.TY,
TB1.CAT,
TB1.LOC,
TB2.HD0_NAME,
TB2.HD1_NAME,
TB2.HD2_NAME,
TB2.HD3_NAME,
TB2.HD4_NAME
FROM DB.TB2 TB2, DB.TB1 TB1
WHERE TB2.CAT = TB1.CAT AND TB2.LOC = TB1.LOC AND TB1.TY = TB2.TY AND TB1.YEARF = TB2.YEARF AND TB1.ID = TB2.ID

Body:
It happens that both Oracle and MySQL have REPLACE() functions.

If you change the part of your query that reads

 AND TB1.YEARF = TB2.YEARF AND

to

 AND TB1.YEARF = REPLACE(TB2.YEARF, '/', '-') AND

you may be able to join these tables.  It's not going to be fast.

In general, to do this kind of inexact matching, you have to

figure out the rules for matching. For example, if you want abcd/ef to match abcd-ef then you can use what I wrote above.  If you want abcd/ef to match abcd, that's a different rule.

Write a SQL expression to implement your rules.

But, you know, step 1 must come before step 2.

If all you care about is matching the abcd parts of abcd/ef and abcd-ef you can write a rule for that.

 AND SUBSTR(TB1.YEARF, 1, 4) = SUBSTR(TB2.YEARF, 1, 4) AND


问:
Splitting values and assigning keys
I have a json array with long and lat values combined, and fields are empty. I am trying to figure out a python script to loop through the array and separate them into long and lat keys.

```<code>[
  {
    "Shape": "(47.630880207000075, -122.37391463199998)"
  },
  {
    "Shape": ""
  },
  {
    "Shape": "(47.70118823100006, -122.38447021399998)"
  }
]
</code>```

output desired:

```<code>[
  {
    "Long": "47.630880207000075",
    "Lat": "-122.37391463199998"

  },
  {
     "Long": "",
    "Lat": ""
  },
  {
   "Long": "47.70118823100006",
    "Lat": "-122.38447021399998"
  }
]
</code>```

So far I have converted the CSV into JSON and in the process of figuring out the regex to loop through it.. code so far:

import csv

```<code>import json

csvfile = open('geoloc.csv', 'r')
jsonfile = open('file.json', 'w')

# fieldnames = ("S")
reader = csv.DictReader( csvfile)
out = json.dumps( [ row for row in reader ], sort_keys=True, indent=4 )
jsonfile.write(out)
</code>```

Title: Splitting values and assigning keys

Body:
I have a json array with long and lat values combined, and fields are empty. I am trying to figure out a python script to loop through the array and separate them into long and lat keys.

[
  {
    "Shape": "(47.630880207000075, -122.37391463199998)"
  },
  {
    "Shape": ""
  },
  {
    "Shape": "(47.70118823100006, -122.38447021399998)"
  }
]

output desired:

[
  {
    "Long": "47.630880207000075",
    "Lat": "-122.37391463199998"

  },
  {
     "Long": "",
    "Lat": ""
  },
  {
   "Long": "47.70118823100006",
    "Lat": "-122.38447021399998"
  }
]

So far I have converted the CSV into JSON and in the process of figuring out the regex to loop through it.. code so far:

import csv

import json

csvfile = open('geoloc.csv', 'r')
jsonfile = open('file.json', 'w')

# fieldnames = ("S")
reader = csv.DictReader( csvfile)
out = json.dumps( [ row for row in reader ], sort_keys=True, indent=4 )
jsonfile.write(out)

Body:
Assuming your json is loaded to d

>>> l = [{"Long": c['Shape'][1:-1].split(',')[0].strip() if len(c['Shape']) > 0 else '',
"Lat": c['Shape'][1:-1].split(',')[1].strip() if len(c['Shape']) > 0 else ''} for c in d]
>>> l
[{'Lat': '-122.37391463199998', 'Long': '47.630880207000075'},
 {'Lat': '', 'Long': ''},
 {'Lat': '-122.38447021399998', 'Long': '47.70118823100006'}]

EDIT:
To make it more readable:

l = [ dict(zip(['Long', 'Lat'],c['Shape'][1:-1].split(',') if len(c['Shape'])>0 else ['',''] ))  for c in d]


问:
Regex pattern for underscore or hyphen but not both
I have a regular expression that is allowing a string to be standalone, separated by hyphen and underscore.

I need help so the string only takes hyphen or underscore, but not both.

This is what I have so far.

```<code>^([a-z][a-z0-9]*)([-_]{1}[a-z0-9]+)*$

foo             = passed
foo-bar         = passed
foo_bar         = passed
foo-bar-baz     = passed
foo_bar_baz     = passed
foo-bar_baz_qux = passed # but I don't want it to
foo_bar-baz-quz = passed # but I don't want it to
</code>```

答:
You may expand the pattern a bit and use a backreference to only match the same delimiter:

```<code>^[a-z][a-z0-9]*(?:([-_])[a-z0-9]+(?:\1[a-z0-9]+)*)?$
</code>```

See the regex demo

Details:

^ - start of string

[a-z][a-z0-9]*  - a letter followed with 0+ lowercase letters or digits

(?:([-_])[a-z0-9]+(?:\1[a-z0-9]+)*)? - an optional sequence of:

([-_]) - Capture group 1 matching either - or _

[a-z0-9]+ - 1+ lowercase letters or digits

(?:\1[a-z0-9]+)* - 0+ sequences of:

\1 - the same value as in Group 1

[a-z0-9]+ - 1 or more lowercase letters or digits

$ -  end of string.

Body:
I have a regular expression that is allowing a string to be standalone, separated by hyphen and underscore.

I need help so the string only takes hyphen or underscore, but not both.

This is what I have so far.

^([a-z][a-z0-9]*)([-_]{1}[a-z0-9]+)*$

foo             = passed
foo-bar         = passed
foo_bar         = passed
foo-bar-baz     = passed
foo_bar_baz     = passed
foo-bar_baz_qux = passed # but I don't want it to
foo_bar-baz-quz = passed # but I don't want it to

Body:
You may expand the pattern a bit and use a backreference to only match the same delimiter:

^[a-z][a-z0-9]*(?:([-_])[a-z0-9]+(?:\1[a-z0-9]+)*)?$

See the regex demo

Details:

^ - start of string

[a-z][a-z0-9]*  - a letter followed with 0+ lowercase letters or digits

(?:([-_])[a-z0-9]+(?:\1[a-z0-9]+)*)? - an optional sequence of:

([-_]) - Capture group 1 matching either - or _

[a-z0-9]+ - 1+ lowercase letters or digits

(?:\1[a-z0-9]+)* - 0+ sequences of:

\1 - the same value as in Group 1

[a-z0-9]+ - 1 or more lowercase letters or digits

$ -  end of string.


问:
How do I smoothly and simultaneously expand/compress a parent div and reveal an inner child on hover with CSS only?
CODE SAMPLE HERE: http://codepen.io/colbisaurusrex/pen/YZdKyO?editors=1100

First problem:
I am trying to smoothly expand and compress a div (class: event) on hover. It expands smoothly, but it snaps back quickly when user is no longer hovering on div. I'd like to transition back at the same ease as it expands

Second problem:
Simultaneously, I'd like to reveal an inner, hidden child(class: hidden) when I hover over its parent(class: event). Ideally, I'd like to reveal it when the parent is fully expanded. And ease it back to hidden as the parent compresses. Right now, it is revealed immediately, before the parent div is fully expanded. I have tried to add a delay.

Basically, there is a beginning and ending transition that exact mirrors of each other. I'd like to do this with no Javascript

Bonus Question: If the entire transition was set off by a button click(say the Show Details button), do I have to use JS? Is there a way to do this with CSS only?

```<code>/* This is the CSS I am working with */

.event {
  margin-top: 2%;
  width: 960px;
  border-color:#496DD9;
  border-style: dotted;
  font-size: 0.5em;
  height: 250px;
  transform: height 300ms ease-out;
}

.event:hover {
   height: 300px;
   transition: height 500ms ease-in;
}

.event:hover .hidden {
  display: block;
  transition: display 300ms ease-in 1s;
}

.hidden {
  font-size: 30px;
  display: none;
}

/* End of css */
</code>```

答:
problem 1: transform should be transition

```<code>.event {
  margin-top: 2%;
  width: 960px;
  border-color:#496DD9;
  border-style: dotted;
  font-size: 0.5em;
  height: 250px;
  transform: height 300ms ease-out; // change this to transition
}
</code>```

Problem 2: try using opacity instead of display:

```<code>.event:hover .hidden {
/*   display: block; */
/*   transition: display 500ms ease-in 1s;   */
  -webkit-transition: opacity 2s ease-in-out;
   opacity: 1;
}

.hidden {
  font-size: 30px;
/*   display: none;  */
  opacity: 0;
}
</code>```

demo: http://codepen.io/anon/pen/NpeWZz?editors=1100

Body:
CODE SAMPLE HERE: http://codepen.io/colbisaurusrex/pen/YZdKyO?editors=1100

First problem:
I am trying to smoothly expand and compress a div (class: event) on hover. It expands smoothly, but it snaps back quickly when user is no longer hovering on div. I'd like to transition back at the same ease as it expands

Second problem:
Simultaneously, I'd like to reveal an inner, hidden child(class: hidden) when I hover over its parent(class: event). Ideally, I'd like to reveal it when the parent is fully expanded. And ease it back to hidden as the parent compresses. Right now, it is revealed immediately, before the parent div is fully expanded. I have tried to add a delay.

Basically, there is a beginning and ending transition that exact mirrors of each other. I'd like to do this with no Javascript

Bonus Question: If the entire transition was set off by a button click(say the Show Details button), do I have to use JS? Is there a way to do this with CSS only?

/* This is the CSS I am working with */

.event {
  margin-top: 2%;
  width: 960px;
  border-color:#496DD9;
  border-style: dotted;
  font-size: 0.5em;
  height: 250px;
  transform: height 300ms ease-out;
}

.event:hover {
   height: 300px;
   transition: height 500ms ease-in;
}

.event:hover .hidden {
  display: block;
  transition: display 300ms ease-in 1s;
}

.hidden {
  font-size: 30px;
  display: none;
}

/* End of css */

Body:
problem 1: transform should be transition

.event {
  margin-top: 2%;
  width: 960px;
  border-color:#496DD9;
  border-style: dotted;
  font-size: 0.5em;
  height: 250px;
  transform: height 300ms ease-out; // change this to transition
}

Problem 2: try using opacity instead of display:

.event:hover .hidden {
/*   display: block; */
/*   transition: display 500ms ease-in 1s;   */
  -webkit-transition: opacity 2s ease-in-out;
   opacity: 1;
}

.hidden {
  font-size: 30px;
/*   display: none;  */
  opacity: 0;
}

demo: http://codepen.io/anon/pen/NpeWZz?editors=1100


问:
Android: In which file store a connection string
I have a connection string containing the IP of the server. Now I want to put this connection string in an external file, so that when someone clones my project, can easily change it before compiling it with the new connection string.

Then of course I have to read my connection string from this file when the app is running on the android device.

Which file is used for this purpose?

答:
You can put it in your gradle script, like this:

```<code> defaultConfig {
    resValue "string", "ip", "someIP"
 }
</code>```

and then access like normal string resource

```<code>getString(R.string.ip);
</code>```

Body:
You can put it in your gradle script, like this:

 defaultConfig {
    resValue "string", "ip", "someIP"
 }

and then access like normal string resource

getString(R.string.ip);


问:
How to include data files with the app's APK?
I want to create some pre-created files when my Android application is installed.

I would like to create the file in both the internal memory (data/data//files/) and in a newly created sdcard directories (/sdcard//data1/).

How can I do this?

答:
If you have a larger number of files and a directory structure you should use /assets. These are not given any R-constants and can be scanned by your application

To open an asset-file:

```<code>InputStream is = getAssets().open("path/file.ext");
</code>```

To list a directory:

```<code>String[] files = getAssets().list("");
</code>```

Body:
If you have a larger number of files and a directory structure you should use /assets. These are not given any R-constants and can be scanned by your application

To open an asset-file:

InputStream is = getAssets().open("path/file.ext");

To list a directory:

String[] files = getAssets().list("");


问:
Scope to get users older then 18 years old by birthday field (Rails 3.2)
I need to write scope that will help me get users where age will be > 18 years, but I don't have age field in database.
My solutions doesn't works =(</p>

```<code> 1. scope :adult, -> { where('Time.now.utc.to_date.year - birthday.to_date.year >= 18') }

 2. scope :adults, -> { where('birthday >= ?', age) }

    def age
      Date.today - 18.years
    end
</code>```

答:
try this</p>
```<code>scope :adults, -> { where('birthday <= ?', 18.years.from_now) }
</code>```

Body:
I need to write scope that will help me get users where age will be > 18 years, but I don't have age field in database.
My solutions doesn't works =(

 1. scope :adult, -> { where('Time.now.utc.to_date.year - birthday.to_date.year >= 18') }

 2. scope :adults, -> { where('birthday >= ?', age) }

    def age
      Date.today - 18.years
    end

Body:
try this

scope :adults, -> { where('birthday <= ?', 18.years.from_now) }


问:
iOS - How to make the tableview use paginated API output?
An API I am writing has about 2000 records, returned in JSON via a simple RESTful API I have written.

To reduce issues with lots of data, I want to use pagination so that I only return say the first 10 or first 20 per request via like an offset or limit or page, etc.

But my question is how does the iOS UITableView know when to get the next page of results?

I really am unsure of how to do this.  The user could be scrolling superfast and so the API might not have enough time to retrieve 20 or 50 records at a time.

Another issue related to this is, lets say the user scrolls down on the UITableView, then up and then back down again -- how do you prevent the API from firing multiple times for the same rows?

Thanks

答:
For Swift</p>

```<code>func scrollViewDidScroll(scrollView: UIScrollView) {
        if collectionViewGif.contentOffset.y >= self.collectionViewGif.contentSize.height - self.collectionViewGif.frame.size.height
        {
            offset = offset + 1
            self.fetchGifWithPaination(defaultText)
        }
    }
</code>```

Body:
For Swift

func scrollViewDidScroll(scrollView: UIScrollView) {
        if collectionViewGif.contentOffset.y >= self.collectionViewGif.contentSize.height - self.collectionViewGif.frame.size.height
        {
            offset = offset + 1
            self.fetchGifWithPaination(defaultText)
        }
    }


问:
how to export intellij project
I simply want to export my java intellij project from one pc to another, no need for git because I only want to test something on the other pc because it has more memory.
Surprisingly no information on this is available, there is information on how to export a project to a jar file, but I cannot import from this jar file. On their website : https://www.jetbrains.com/help/idea/2016.3/import-existing-sources-project-name-and-location.html they don't give any clear instructions on how to do this simple operation? how is this done?</p>

答:
Till version 2016.3.4 IntelliJ doesn't provide such facility.

Best way to do so would be to copy the whole directory containing your project or module. Doing this would retain all your project related settings.

Title: how to export intellij project


问:
How to keep autoresize textarea text away from the very bottom of screen?
I'm trying to create a 100px gap between a textarea that autoresizes using this js library autosize and the very bottom of the screen.

The demo from the link showcases this problem. Once you hit the bottom of the screen there is no space between the text and the window.

Cant seem to find any solutions and margins and paddings dont seem to fix this. Any help appreciated thanks.

答:
An important note is that, in order to work, the script below needs flow-content after the <textarea> element worth of 100px in height. If it doesn't have it, it can't scroll there, so it doesn't work. I provided this scroll-space by setting a padding-bottom:100px on  but if you have enough content after your <textarea> to provide the 100px of scroll space, that padding is not necessary. Actually, all of the CSS is there mostly to demonstrate the principle, you shouldn't add it to your project.

The solution is provided by the javascript part.

Another note would be that this is not a fully-working-fit-all-copy-paste-ultimate-solution, but rather a delicate-proof-of-concept. It's up to you to understand what it does and alter it so it works for your specific case. If you have any trouble applying it, just ask/provide details.

And, as a final note, I only added jQuery to it after trying to get scrollTo animated in vanilla without much success. In the end I didn't want to lose more time so just used jQuery.animate(). If you don't need to smooth-scroll to position or if you know how to do it in vanilla, jQuery should be removed altogether (as autosizer is stand-alone too). So, if you need/want it, I could provide a jQuery free non-animated solution.

Here it is:

autosize(document.querySelectorAll('textarea'));

$('textarea').each(function(){
  autosize(this);
}).on('autosize:resized', function(){
  let fromBottom = $(window).height() - this.clientHeight;
  if (fromBottom < 102) {
    $('html, body').stop().animate({
      scrollTop:(102 - fromBottom) + 'px'
    }, 210);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea {
  width: 80%;
  margin-left: 10%;
}
body {
  padding-bottom: 100px;
  margin: 0;
  min-height: 100vh;
  box-sizing: border-box;

}
body::before {
  left: 0;
  width: 100%;
  position: fixed;
  bottom: 100px;
  content: '';
  display: block;
  border-bottom: 1px solid red;
}</code>```

<textarea>test textarea</textarea>```

Body:
An important note is that, in order to work, the script below needs flow-content after the <textarea> element worth of 100px in height. If it doesn't have it, it can't scroll there, so it doesn't work. I provided this scroll-space by setting a padding-bottom:100px on <body> but if you have enough content after your <textarea> to provide the 100px of scroll space, that padding is not necessary. Actually, all of the CSS is there mostly to demonstrate the principle, you shouldn't add it to your project.

The solution is provided by the javascript part.

Another note would be that this is not a fully-working-fit-all-copy-paste-ultimate-solution, but rather a delicate-proof-of-concept. It's up to you to understand what it does and alter it so it works for your specific case. If you have any trouble applying it, just ask/provide details.

And, as a final note, I only added jQuery to it after trying to get scrollTo animated in vanilla without much success. In the end I didn't want to lose more time so just used jQuery.animate(). If you don't need to smooth-scroll to position or if you know how to do it in vanilla, jQuery should be removed altogether (as autosizer is stand-alone too). So, if you need/want it, I could provide a jQuery free non-animated solution.

Here it is:

autosize(document.querySelectorAll('textarea'));

$('textarea').each(function(){
  autosize(this);
}).on('autosize:resized', function(){
  let fromBottom = $(window).height() - this.clientHeight;
  if (fromBottom < 102) {
    $('html, body').stop().animate({
      scrollTop:(102 - fromBottom) + 'px'
    }, 210);
  }
});

textarea {
  width: 80%;
  margin-left: 10%;
}
body {
  padding-bottom: 100px;
  margin: 0;
  min-height: 100vh;
  box-sizing: border-box;

}
body::before {
  left: 0;
  width: 100%;
  position: fixed;
  bottom: 100px;
  content: '';
  display: block;
  border-bottom: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autosize.js/3.0.20/autosize.min.js"></script>

<textarea>test textarea</textarea>


问:
Unix saved encrypted passwords and decoding
Where do linux systems keep the users encrypted passwords and how can it be decoded? Or maybe there is a workaround for getting the initial user's password? Thanks</p>

答:
the default directory to the file that keeps passwords in Unix systems is

```<code>etc/passwds
</code>```

and in macOS

```<code>etc/master.passwds
</code>```

https://docs.python.org/3/library/crypt.html

you can read about crypt library of python which may help you to decode the Unix password. One of the ways I do it is I generate all possible Strings of a certain length 8, and then compare the hash from that file with the hash of each of these words. I am not sure that it is the optimal way of solving this question but it works.

Take a look here:
Python generate all possible strings of length n

Body:
the default directory to the file that keeps passwords in Unix systems is

etc/passwds

and in macOS

etc/master.passwds

https://docs.python.org/3/library/crypt.html

you can read about crypt library of python which may help you to decode the Unix password. One of the ways I do it is I generate all possible Strings of a certain length 8, and then compare the hash from that file with the hash of each of these words. I am not sure that it is the optimal way of solving this question but it works.

Take a look here:
Python generate all possible strings of length n


问:
AWS API Gateway & Lambda - API Pagination
I am thinking to use AWS API Gateway and AWS Lambda(Python) to create a serverless API's , but while designing this i was thinking of some aspects like pagination,security,caching,versioning ..etc

so my question is:
What is the best approach performance & cost wise to implement API pagination with very big data (1 million records)?

should i implement the pagination in postgresql db? (i think this
would be slow)

should i not use postgresql db pagination and just cache all the results i get from db into aws elastic cache and then do server side pagination in lambda.

I appreciate your help guys.

答:
If your data is going to live in a postgresql data base anyway I would start with your requests hitting the database and profile the performance. You've made assumptions about it being slow but you haven't stated what your requirements for latency are or what your schema is, so any assertions people would make about whether or not it would fit your case is completely speculative.

If you do decide that after profiling that it is not fast enough, than adding a cache would make sense, though storing the entire contents in the cache seems wasteful unless you can guarantee your clients will always iterate through all results. You may want to consider a mechanism that prefetches blocks of data that would service a few requests rather than trying to cache the whole data.

TL;DR : Don't prematurely optimize your solution. Quantify how you want your system to respond and test and validate your assumptions.


问:
Create a virtual printer in Java
I would like to create a virtual printer using Java, so that when you go to print a file( using Word or something) the Java printer is listed as a valid printer.  My goal is to get the printer formatted object that the programs (Word, etc..) send directly to the printer. I don't know if this is possible. It seemed like a more logical solution to this question:

Printing multiple file types using java

Any ideas?  I heard this is only possible using C or C++, but I don't know for sure.

答: There is a LPD implementation available in Java.  You can then create manually a printer in Windows which use the LPR protocol to print to said Java LPD.  This captures the result as a byte stream which you can then manipulate further.</p>

Title: Create a virtual printer in Java


问:
How do I parameterize template blocks in knitr?
Say I have the following code in knitr. How can I run it multiple times with different values of i?

```<code>```{r, echo=FALSE}
i<-0.1
```

### X,Y plot of Y=X+e where e is a standard normal distro: mean=0, sd=`r i`

```{r, echo=FALSE}
r<-rnorm(100,mean=0,sd=i)
x<-seq(0,1,length.out=100)
y<-x+r
plot(x,y)
```
</code>```

EDIT:

As has been suggested ... I tried to do something like this: start a loop in an R code block, have a template in between and then close the loop -- R throws and error.

```<code>```{r, echo=FALSE}
for (i in 1:4) {
```

# bla

```{r, echo=FALSE}
}
```
</code>```

答:
What makes this question tricky is that not only the chunk content (the plot) must be repeated, but the heading as well. That's why we can neither simply reuse the chunk nor just loop over the plot command like

```<code>for (i in 1:3) { plot(rnorm(100, sd = i)) }
</code>```

But it's almost that simple: We loop over the code that produces the plot and output the heading from inside the loop. This requires the chunk option results="asis" and cat to get verbatim markdown output:

```<code>```{r, echo=FALSE, results = "asis"}
sdVec <- c(0.1, 0.2, 0.3)
for (sd in sdVec) {
  cat(sprintf("\n### X,Y plot of Y=X+e where e ~ N(0, %s)", sd))
  r<-rnorm(100,mean=0,sd=sd)
  x<-seq(0,1,length.out=100)
  y<-x+r
  plot(x,y)
}
```
</code>```

See this answer for related issues.

Body:
Say I have the following code in knitr. How can I run it multiple times with different values of i?

```{r, echo=FALSE}
i<-0.1
```

### X,Y plot of Y=X+e where e is a standard normal distro: mean=0, sd=`r i`

```{r, echo=FALSE}
r<-rnorm(100,mean=0,sd=i)
x<-seq(0,1,length.out=100)
y<-x+r
plot(x,y)
```

EDIT:

As has been suggested ... I tried to do something like this: start a loop in an R code block, have a template in between and then close the loop -- R throws and error.

```{r, echo=FALSE}
for (i in 1:4) {
```

# bla

```{r, echo=FALSE}
}
```

Body:
What makes this question tricky is that not only the chunk content (the plot) must be repeated, but the heading as well. That's why we can neither simply reuse the chunk nor just loop over the plot command like

for (i in 1:3) { plot(rnorm(100, sd = i)) }

But it's almost that simple: We loop over the code that produces the plot and output the heading from inside the loop. This requires the chunk option results="asis" and cat to get verbatim markdown output:

```{r, echo=FALSE, results = "asis"}
sdVec <- c(0.1, 0.2, 0.3)
for (sd in sdVec) {
  cat(sprintf("\n### X,Y plot of Y=X+e where e ~ N(0, %s)", sd))
  r<-rnorm(100,mean=0,sd=sd)
  x<-seq(0,1,length.out=100)
  y<-x+r
  plot(x,y)
}
```

See this answer for related issues.


问:
spring, get json keys in the controller function
i am sending a JSON object to my controller using POST method inside the request body (using post man).

i want to receive the JSON parameters as variables of my controller function

for ample when i send this

```<code>{"A":"some a value", "B":"Some b value"}
</code>```

i want to get them like this in my controller

```<code>@RestController
public class UserController {
    @RequestMapping(value="/api/some-update-url"    , method=RequestMethod.POST)
    Boolean updateSomeData(@RequestParam String A, @RequestParam String B) {
        .....
    }
}
</code>```

but this is the result of my postman

```<code>{
    "timestamp": 1490896822946,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
    "message": "Required Gender parameter 'gender' is not present",
    "path": "/api/some-update-url"
}
</code>```

can you help me please

thank you !!

答:
@RequestParam is used to map POST/GET request parameters. What you are doing is sending JSON as the body of the request. In that case you need to use @RequestBody parameter on one of your Controller's method parameters.

```<code>@RequestMapping(value="/api/some-update-url", method=RequestMethod.PUT)
Boolean updateSomeData(@RequestBody MyClass myClass) {
   .....
}
</code>```

You can further read about @RequestBody here:
https://www.javacodegeeks.com/2013/07/spring-mvc-requestbody-and-responsebody-demystified.html

Body:
i am sending a JSON object to my controller using POST method inside the request body (using post man).

i want to receive the JSON parameters as variables of my controller function

for ample when i send this

{"A":"some a value", "B":"Some b value"}

i want to get them like this in my controller

@RestController
public class UserController {
    @RequestMapping(value="/api/some-update-url"    , method=RequestMethod.POST)
    Boolean updateSomeData(@RequestParam String A, @RequestParam String B) {
        .....
    }
}

but this is the result of my postman

{
    "timestamp": 1490896822946,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
    "message": "Required Gender parameter 'gender' is not present",
    "path": "/api/some-update-url"
}

can you help me please

thank you !!

Body:
@RequestParam is used to map POST/GET request parameters. What you are doing is sending JSON as the body of the request. In that case you need to use @RequestBody parameter on one of your Controller's method parameters.

@RequestMapping(value="/api/some-update-url", method=RequestMethod.PUT)
Boolean updateSomeData(@RequestBody MyClass myClass) {
   .....
}

You can further read about @RequestBody here:
https://www.javacodegeeks.com/2013/07/spring-mvc-requestbody-and-responsebody-demystified.html


问:
Ansible Host: how to get the value for $HOME variable?
I know about ansible_env.HOME variable, which allow us to retrieve the path for the home user for the VMs we are connecting using Ansible.

However I need to get the home path for the ansible host. That means, the machine which is running the ansible playbook. Is there a short variable to retrieve that information? I was hoping to avoid running a local command and storing the result in a variable.

答:
You should be able to access it with a lookup plugin like so:

```<code>- debug: msg="{{ lookup('env','HOME') }}"
</code>```

Lookup plugins run on the control machine not the remote systems.

Body:
You should be able to access it with a lookup plugin like so:

- debug: msg="{{ lookup('env','HOME') }}"

Lookup plugins run on the control machine not the remote systems.


问:
How to insert 'require' or 'import' into js file with Webpack 2?

Problem

Say I have a structure of modules like this:

```

    ./app-- file.js
         |- some.js
         |- foo.js
         |- and-so-on.js

```

In each file I have to write some identical lines like this:

```

    import Foo, { baz, bar } from 'foo';
    import Fee from 'fee';
    import 'zee';

```

I feel lazy and don't want to do such a routine by hand.

Question

How do I do this automatically with the help of Webpack 2, so I don't need to write the same thing again and again?

答:
You can use index.js file into your directory with this content:

```<code>import Foo from './foo'
import Bar from './bar'
// etc
export Foo
export Bar
// etc
</code>```

And import from each other files:

```<code>import * from 'your-dir'
</code>```

Body:
Problem

Say I have a structure of modules like this:

    ./app-- file.js
         |- some.js
         |- foo.js
         |- and-so-on.js

In each file I have to write some identical lines like this:

    import Foo, { baz, bar } from 'foo';
    import Fee from 'fee';
    import 'zee';

I feel lazy and don't want to do such a routine by hand.

Question

How do I do this automatically with the help of Webpack 2, so I don't need to write the same thing again and again?

Body:
You can use index.js file into your directory with this content:

import Foo from './foo'
import Bar from './bar'
// etc
export Foo
export Bar
// etc

And import from each other files:

import * from 'your-dir'


问:
Postgresql stopped working after restart
```<code>psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

running on localhost gives the same result:

```<code>psql -h localhost                                                                                ⏎ master ✱ ◼
psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
</code>```

Service status:

```<code>sudo service postgresql status                                                                                ⏎ master ✱ ◼
[sudo] password for david:
● postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
   Active: active (exited) since Sat 2015-10-10 15:48:54 IDT; 26min ago
  Process: 5470 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 5470 (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/postgresql.service

Oct 10 15:48:54 david-X48-DS4 systemd[1]: Starting PostgreSQL RDBMS...
Oct 10 15:48:54 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.
Oct 10 15:49:21 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.
Oct 10 15:51:40 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.
Oct 10 15:51:41 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.
</code>```

running sudo netstat -nl | grep postgres gives no result

I'm running xubuntu 15.04

what should my next troubleshooting steps be?

答:
YASP (Yet Another Systemd Problem)

The systemd integration of PostgreSQL in Xenial is somewhat idiosyncratic.
The postgresql service unit is just a dummy which is supposed to trigger the starting of your actual database instance(s) via service dependencies.
That's why it says ExecStart=/bin/true - the unit's start command is /bin/true, ie. "do nothing, successfully".

The instances have service units of their own named postgresql@<version>-<name>.
You can see those by running the command

```<code>systemctl list-dependencies postgresql
</code>```

Dependencies are generated by the script /lib/systemd/system-generators/postgresql-generator for all instances whose start mode is set to auto in their respective start.conf files under /etc/postgresql.

At least that's how it is supposed to work.
Every once in a while, though, these dependencies stop working.
Systemd will cheerfully report Started PostgreSQL RDBMS. but in fact will have done nothing, successfully.

So your next troubleshooting steps should be:

Check whether your instances are listed by list-dependencies.

If so, debug systemd's dependency processing. (Good luck.)

Otherwise check your instances' start.conf files.

If those are correct, debug the dependency generator.

Body:
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

running on localhost gives the same result:

psql -h localhost                                                                                ⏎ master ✱ ◼
psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

Service status:

sudo service postgresql status                                                                                ⏎ master ✱ ◼
[sudo] password for david:
● postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
   Active: active (exited) since Sat 2015-10-10 15:48:54 IDT; 26min ago
  Process: 5470 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 5470 (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/postgresql.service

Oct 10 15:48:54 david-X48-DS4 systemd[1]: Starting PostgreSQL RDBMS...
Oct 10 15:48:54 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.
Oct 10 15:49:21 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.
Oct 10 15:51:40 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.
Oct 10 15:51:41 david-X48-DS4 systemd[1]: Started PostgreSQL RDBMS.

running sudo netstat -nl | grep postgres gives no result

I'm running xubuntu 15.04

what should my next troubleshooting steps be?

Body:
YASP (Yet Another Systemd Problem)

The systemd integration of PostgreSQL in Xenial is somewhat idiosyncratic.
The postgresql service unit is just a dummy which is supposed to trigger the starting of your actual database instance(s) via service dependencies.
That's why it says ExecStart=/bin/true - the unit's start command is /bin/true, ie. "do nothing, successfully".

The instances have service units of their own named postgresql@<version>-<name>.
You can see those by running the command

systemctl list-dependencies postgresql

Dependencies are generated by the script /lib/systemd/system-generators/postgresql-generator for all instances whose start mode is set to auto in their respective start.conf files under /etc/postgresql.

At least that's how it is supposed to work.
Every once in a while, though, these dependencies stop working.
Systemd will cheerfully report Started PostgreSQL RDBMS. but in fact will have done nothing, successfully.

So your next troubleshooting steps should be:

Check whether your instances are listed by list-dependencies.

If so, debug systemd's dependency processing. (Good luck.)

Otherwise check your instances' start.conf files.

If those are correct, debug the dependency generator.


问:
How can I get the list of Twitter user names by their location?
I've been using the twitter REST API and need to access the list of Twitter users by their location. I've looked through the GET request lists here: https://dev.twitter.com/rest/reference/get/users/lookup, but I can't seem to find the GET request that would accomplish what I need. I am working with R and have looked at TwitteR but didn't find anything useful. and I am new to using APIs so any help would appreciated.</p>

答:
you can use users/search and pass locations as a parameter with url

You need to change url to https://api.twitter.com/1.1/users/search.json?q=Toronto&page=1&count=3


问:
What is the best way to optimize a function with many if-else statements(multiple conditions)?
What is the best approach or design pattern to optimize the code below?(I've thought about using switch statement but switch statement cannot handle multiple conditions in a single case.)

Below is the code snippet. Each major is determined by a certain numerical range.

```<code>public String getMajor(String major) {
    crnCompare = Integer.parseInt(major);
    if ((crnCompare >= 90702 && crnCompare <= 90733) || (crnCompare >= 10004 && crnCompare <= 10037)) {
        this.major = "AC";
    } else if ((crnCompare >= 10087 && crnCompare <= 10108) || (crnCompare >= 10471 && crnCompare <= 10482) || (crnCompare >= 90024 && crnCompare <= 90071)) {
        this.major = "CS";
    } else if ((crnCompare >= 10109 && crnCompare <= 10158) || (crnCompare >= 90072 && crnCompare <= 90116)) {
        this.major = "EC";
    } else if ((crnCompare >= 90117 && crnCompare <= 90203) || (crnCompare >= 10075 && crnCompare <= 10213) || (crnCompare >= 10498 && crnCompare <= 10572)) {
        this.major = "EN";
    } else if ((crnCompare >= 10038 && crnCompare <= 10040) || (crnCompare >= 10214 && crnCompare <= 10255) || (crnCompare >= 10256 && crnCompare <= 10260) || (crnCompare >= 90017 && crnCompare <= 90203) || crnCompare == 11172) {
        this.major = "FI";
    } else if ((crnCompare >= 90670 && crnCompare <= 90790) || (crnCompare >= 11236 && crnCompare <= 11239)) {
        this.major = "FS";
    } else if ((crnCompare >= 90253 && crnCompare <= 90273) || (crnCompare >= 90734 && crnCompare <= 90769) || (crnCompare >= 90274 && crnCompare <= 90360) || (crnCompare >= 10261 && crnCompare <= 10393)) {
        this.major = "GB";
    } else if ((crnCompare >= 100394 && crnCompare <= 10429) || (crnCompare >= 90361 && crnCompare <= 90398)) {
        this.major = "GLS";
    } else if ((crnCompare >= 10430 && crnCompare <= 10451) || (crnCompare >= 90399 && crnCompare <= 90420)) {
        this.major = "HI";
    } else if ((crnCompare >= 10452 && crnCompare <= 10468) || (crnCompare >= 90422 && crnCompare <= 90436) || crnCompare == 11119) {
        this.major = "IDCC";
    } else if ((crnCompare >= 9437 && crnCompare <= 90438) || (crnCompare >= 10469 && crnCompare <= 10470)) {
        this.major = "IPM";
    } else if ((crnCompare == 90421) || (crnCompare >= 11280 && crnCompare <= 11426)) {
        this.major = "ID";
    } else if ((crnCompare >= 90439 && crnCompare <= 90448) || (crnCompare >= 90483 && crnCompare <= 90497)) {
        this.major = "LTF";
    } else if ((crnCompare >= 90504 && crnCompare <= 90535) || (crnCompare >= 10573 && crnCompare <= 10596) || crnCompare == 90785) {
        this.major = "MG";
    } else if ((crnCompare >= 90536 && crnCompare <= 90553) || (crnCompare >= 10598 && crnCompare <= 10616) || crnCompare == 10740) {
        this.major = "MK";
    } else if ((crnCompare >= 90449 && crnCompare <= 90503) || (crnCompare >= 10514 && crnCompare <= 10564) || (crnCompare == 11120) || (crnCompare == 10555) || (crnCompare == 11127)) {
        this.major = "MA";
    } else if ((crnCompare >= 10637 && crnCompare <= 10715) || (crnCompare == 11142) || (crnCompare == 10739) || (crnCompare >= 90575 && crnCompare <= 90622)) {
        this.major = "NAS";
    } else if (crnCompare >= 90554 && crnCompare <= 90574 || crnCompare == 10617 || crnCompare == 10636) {
        this.major = "ML";
    } else if ((crnCompare >= 90623 && crnCompare <= 10646) || (crnCompare >= 10671 && crnCompare <= 10696)) {
        this.major = "PI";
    } else if ((crnCompare == 90647 || crnCompare == 90649) || (crnCompare >= 10697 && crnCompare <= 10698) || crnCompare == 10756) {
        this.major = "PRS";
    } else if ((crnCompare >= 11341 && crnCompare <= 11420)) {
        this.major = "SL";
    } else if ((crnCompare >= 90650 && crnCompare <= 90668) || (crnCompare >= 10716 && crnCompare <= 10734)) {
        this.major = "SO";
    } else if ((crnCompare == 10735)) {
        this.major = "ST";
    }

    return this.major;
}
</code>```

答:
I thought a while about this; focusing on the aspect of: "how can you make sure that your implementation is correct?"

In that sense, I would have suggested a Range class, similar to the one proposed by Jim. Because such a class allows you to not only have a contains() method closely associated to the range data; but on top of that, you could add methods like:

boolean isOverlapping(Range other) ... which you can use to detect situations when you didn't pay attention and you defined ranges that, well, overlap!

int compareTo(Range other) ... to implement the Comparable interface. And now you could sort ranges. Which would allow you to do binary search when the list of ranges for a certain "category" gets too large.

But: I would not put that "major" name into the Range class; but the other way round:

```<code>public enum RangeBasedMajor {
  AC(Arrays.asList(new Range(90702, 90733), new Range(...)),
  EN(...

  private RangeBasedMajor(List<Range> ranges) ...
</code>```

Key points here:

you have one place where those "majors" are created and mapped to their ranges

you can write some nice unit tests that fetch all constants from that enum, then grep their ranges, to ensure that no range is overlapping

and you are still free to push all that information into the special type of map Andy recommended to you in his solution ...

Depending on your context, this might be overkill. It really depends on how often you expect things to change in there; and for example: if it is required to access/deal with that "major" information within other parts of the program. When your requirement is only to map that number to a string (for example for printing something); then that RangeMap is fine.

But when you have other code that "deals" with "Majors" - then it might be worth looking into some of the suggestions I am making here.

Body:
What is the best approach or design pattern to optimize the code below?(I've thought about using switch statement but switch statement cannot handle multiple conditions in a single case.)

Below is the code snippet. Each major is determined by a certain numerical range.

public String getMajor(String major) {
    crnCompare = Integer.parseInt(major);
    if ((crnCompare >= 90702 && crnCompare <= 90733) || (crnCompare >= 10004 && crnCompare <= 10037)) {
        this.major = "AC";
    } else if ((crnCompare >= 10087 && crnCompare <= 10108) || (crnCompare >= 10471 && crnCompare <= 10482) || (crnCompare >= 90024 && crnCompare <= 90071)) {
        this.major = "CS";
    } else if ((crnCompare >= 10109 && crnCompare <= 10158) || (crnCompare >= 90072 && crnCompare <= 90116)) {
        this.major = "EC";
    } else if ((crnCompare >= 90117 && crnCompare <= 90203) || (crnCompare >= 10075 && crnCompare <= 10213) || (crnCompare >= 10498 && crnCompare <= 10572)) {
        this.major = "EN";
    } else if ((crnCompare >= 10038 && crnCompare <= 10040) || (crnCompare >= 10214 && crnCompare <= 10255) || (crnCompare >= 10256 && crnCompare <= 10260) || (crnCompare >= 90017 && crnCompare <= 90203) || crnCompare == 11172) {
        this.major = "FI";
    } else if ((crnCompare >= 90670 && crnCompare <= 90790) || (crnCompare >= 11236 && crnCompare <= 11239)) {
        this.major = "FS";
    } else if ((crnCompare >= 90253 && crnCompare <= 90273) || (crnCompare >= 90734 && crnCompare <= 90769) || (crnCompare >= 90274 && crnCompare <= 90360) || (crnCompare >= 10261 && crnCompare <= 10393)) {
        this.major = "GB";
    } else if ((crnCompare >= 100394 && crnCompare <= 10429) || (crnCompare >= 90361 && crnCompare <= 90398)) {
        this.major = "GLS";
    } else if ((crnCompare >= 10430 && crnCompare <= 10451) || (crnCompare >= 90399 && crnCompare <= 90420)) {
        this.major = "HI";
    } else if ((crnCompare >= 10452 && crnCompare <= 10468) || (crnCompare >= 90422 && crnCompare <= 90436) || crnCompare == 11119) {
        this.major = "IDCC";
    } else if ((crnCompare >= 9437 && crnCompare <= 90438) || (crnCompare >= 10469 && crnCompare <= 10470)) {
        this.major = "IPM";
    } else if ((crnCompare == 90421) || (crnCompare >= 11280 && crnCompare <= 11426)) {
        this.major = "ID";
    } else if ((crnCompare >= 90439 && crnCompare <= 90448) || (crnCompare >= 90483 && crnCompare <= 90497)) {
        this.major = "LTF";
    } else if ((crnCompare >= 90504 && crnCompare <= 90535) || (crnCompare >= 10573 && crnCompare <= 10596) || crnCompare == 90785) {
        this.major = "MG";
    } else if ((crnCompare >= 90536 && crnCompare <= 90553) || (crnCompare >= 10598 && crnCompare <= 10616) || crnCompare == 10740) {
        this.major = "MK";
    } else if ((crnCompare >= 90449 && crnCompare <= 90503) || (crnCompare >= 10514 && crnCompare <= 10564) || (crnCompare == 11120) || (crnCompare == 10555) || (crnCompare == 11127)) {
        this.major = "MA";
    } else if ((crnCompare >= 10637 && crnCompare <= 10715) || (crnCompare == 11142) || (crnCompare == 10739) || (crnCompare >= 90575 && crnCompare <= 90622)) {
        this.major = "NAS";
    } else if (crnCompare >= 90554 && crnCompare <= 90574 || crnCompare == 10617 || crnCompare == 10636) {
        this.major = "ML";
    } else if ((crnCompare >= 90623 && crnCompare <= 10646) || (crnCompare >= 10671 && crnCompare <= 10696)) {
        this.major = "PI";
    } else if ((crnCompare == 90647 || crnCompare == 90649) || (crnCompare >= 10697 && crnCompare <= 10698) || crnCompare == 10756) {
        this.major = "PRS";
    } else if ((crnCompare >= 11341 && crnCompare <= 11420)) {
        this.major = "SL";
    } else if ((crnCompare >= 90650 && crnCompare <= 90668) || (crnCompare >= 10716 && crnCompare <= 10734)) {
        this.major = "SO";
    } else if ((crnCompare == 10735)) {
        this.major = "ST";
    }

    return this.major;
}

Body:
I thought a while about this; focusing on the aspect of: "how can you make sure that your implementation is correct?"

In that sense, I would have suggested a Range class, similar to the one proposed by Jim. Because such a class allows you to not only have a contains() method closely associated to the range data; but on top of that, you could add methods like:

boolean isOverlapping(Range other) ... which you can use to detect situations when you didn't pay attention and you defined ranges that, well, overlap!

int compareTo(Range other) ... to implement the Comparable interface. And now you could sort ranges. Which would allow you to do binary search when the list of ranges for a certain "category" gets too large.

But: I would not put that "major" name into the Range class; but the other way round:

public enum RangeBasedMajor {
  AC(Arrays.asList(new Range(90702, 90733), new Range(...)),
  EN(...

  private RangeBasedMajor(List<Range> ranges) ...

Key points here:

you have one place where those "majors" are created and mapped to their ranges

you can write some nice unit tests that fetch all constants from that enum, then grep their ranges, to ensure that no range is overlapping

and you are still free to push all that information into the special type of map Andy recommended to you in his solution ...

Depending on your context, this might be overkill. It really depends on how often you expect things to change in there; and for example: if it is required to access/deal with that "major" information within other parts of the program. When your requirement is only to map that number to a string (for example for printing something); then that RangeMap is fine.

But when you have other code that "deals" with "Majors" - then it might be worth looking into some of the suggestions I am making here.


问:
xtype vs type column in Sysobjects
Can anyone tell me why Sysobjects table have two columns xtype and type. Both are of data type char(2) and stores the object type.

答:
I believe type should be used as it is still in the new view. xtype is there for backward compatibility.

NOTE:

It appears that sys.sysobjects will be removed in future versions and you should use sys.objects instead.

Title: xtype vs type column in Sysobjects