问:
Entity Framework Invalid Column Name Error
Hi I have class in Entity Framework Like this:-

```<code>public partial class JLLContact : DomainEntity, IUniqueId
{
    // Simple Props
    public int? Record1ObjectTypeCode { get; set; }
    public int? Record2ObjectTypeCode { get; set; }
    public DateTime? CreatedOn { get; set; }
    public string Email { get; set; }
    public string Description { get; set; }
    public bool IsActive { get; set; }
    public int JLLContactId { get; set; }
    public DateTime? ModifiedOn { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public int? RoleLid { get; set; }
    public int? BusinessLineLId { get; set; }
    public int? RegionLId { get; set; }
    public int? RelationScoreLId { get; set; }
    public int? RelationStrengthLId { get; set; }
    public int? Record1LId { get; set; }
    public int? Record2LId { get; set; }
    public bool? IsPrimary { get; set; }
    public int? CountryLid { get; set; }

    // UniqueId
    public string __Id
    {
        get { return JLLContactId.ToString(); }
    }

    // Parents
    public virtual ListItem Role { get; set; }
    public virtual ListItem Region { get; set; }
    public virtual ListItem Country { get; set; }
    public virtual ListItem BusinessLine { get; set; }

}
</code>```

When I try to add an entry of this type to DB, I get an error. Invalid column Name "BusinessLine_ListItemId", "Country_ListItemId", "Region_ListItemId".
Obviously they are referring to parents properties. But I don't understand the issue. Can anyone point me in the right direction.

答:
The answer lies in the Entity Map file. These are the changes I needed to make:</p>

```<code>this.HasOptional(t => t.Role).WithMany(t => t.Role_JLLContacts).HasForeignKey(d => new { d.RoleLid });
this.HasOptional(t => t.BusinessLine).WithMany(t => t.BusinessLine_JLLContacts).HasForeignKey(d => new { d.BusinessLineLId });
this.HasOptional(t => t.Region).WithMany(t => t.Region_JLLContacts).HasForeignKey(d => new { d.RegionLId });
</code>```

Body:
Hi I have class in Entity Framework Like this:-

public partial class JLLContact : DomainEntity, IUniqueId
{
    // Simple Props
    public int? Record1ObjectTypeCode { get; set; }
    public int? Record2ObjectTypeCode { get; set; }
    public DateTime? CreatedOn { get; set; }
    public string Email { get; set; }
    public string Description { get; set; }
    public bool IsActive { get; set; }
    public int JLLContactId { get; set; }
    public DateTime? ModifiedOn { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public int? RoleLid { get; set; }
    public int? BusinessLineLId { get; set; }
    public int? RegionLId { get; set; }
    public int? RelationScoreLId { get; set; }
    public int? RelationStrengthLId { get; set; }
    public int? Record1LId { get; set; }
    public int? Record2LId { get; set; }
    public bool? IsPrimary { get; set; }
    public int? CountryLid { get; set; }

    // UniqueId
    public string __Id
    {
        get { return JLLContactId.ToString(); }
    }

    // Parents
    public virtual ListItem Role { get; set; }
    public virtual ListItem Region { get; set; }
    public virtual ListItem Country { get; set; }
    public virtual ListItem BusinessLine { get; set; }

}

When I try to add an entry of this type to DB, I get an error. Invalid column Name "BusinessLine_ListItemId", "Country_ListItemId", "Region_ListItemId".
Obviously they are referring to parents properties. But I don't understand the issue. Can anyone point me in the right direction.

Body:
The answer lies in the Entity Map file. These are the changes I needed to make:

this.HasOptional(t => t.Role).WithMany(t => t.Role_JLLContacts).HasForeignKey(d => new { d.RoleLid });
this.HasOptional(t => t.BusinessLine).WithMany(t => t.BusinessLine_JLLContacts).HasForeignKey(d => new { d.BusinessLineLId });
this.HasOptional(t => t.Region).WithMany(t => t.Region_JLLContacts).HasForeignKey(d => new { d.RegionLId });


来源: stackexchange

问:
How to remove the ',' when converting Javascript object to .csv file?
I need to convert javascript some objects like this:

```<code>{available :null
avg: null
current:116
max:null
min:null
status:"Pending, Charged Off"
balance:-166085.77}
</code>```

using other people's js code and adding a little bit my code for get API, which including two functions the first one is for converting:

```<code>$scope.convertArrayOfObjectsToCSV = function (args) {
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

        data = args.data || null;
        if (data == null || !data.length) {
            return null;
        }

        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';

        keys = Object.keys(data[0]);

        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;

                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });

        return result;
    }
</code>```

the second one is for downloading :

```<code>$scope.downloadCSV = function (args) {
        var data, filename, link;
        //my code:
        $http.get(
                 apis[$scope.selectedKeys[0]]
            ).success(function (data) {
                    $scope.data = data;
        })
        var stringData = angular.toJson($scope.data.items);
        $scope.newData = JSON.parse(stringData);
        console.log($scope.newData);
        //my code end
        var csv = $scope.convertArrayOfObjectsToCSV({
            data: $scope.newData
        });
        if (csv == null) return;

        // filename = args.filename || 'export.csv';
        filename =  $scope.selectedKeys[0] + '.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
</code>```

It works fine, only one problem is when some columns with the comma like this in object: status:"Pending, Charged Off" will be converted in to another column in csv file. I think I need to do something with this line:

```<code>columnDelimiter = args.columnDelimiter || ',';
</code>```

but do not know how to do? Can any one help? Thank you in advanced!

答:
To get , in a value surround it with double quotes ":

```<code>foo,"foo,bar",bar
</code>```

Is interpreted in CSV as:

```<code>[ "foo", "foo,bar", "bar" ]
</code>```

But what if your value also has a double quote in it? ie:

```<code>foo,"foo",bar",bar
</code>```

Now this is just a mess. You need to escape the double quote by adding another double quote:

```<code>foo,"foo"",bar",bar
</code>```

Gives:

```<code>[ "foo", "foo\",bar", "bar" ]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to convert javascript some objects like this:

{available :null
avg: null
current:116
max:null
min:null
status:"Pending, Charged Off"
balance:-166085.77}

using other people's js code and adding a little bit my code for get API, which including two functions the first one is for converting:

$scope.convertArrayOfObjectsToCSV = function (args) {
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

        data = args.data || null;
        if (data == null || !data.length) {
            return null;
        }

        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';

        keys = Object.keys(data[0]);

        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;

                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });

        return result;
    }

the second one is for downloading :

$scope.downloadCSV = function (args) {
        var data, filename, link;
        //my code:
        $http.get(
                 apis[$scope.selectedKeys[0]]
            ).success(function (data) {
                    $scope.data = data;
        })
        var stringData = angular.toJson($scope.data.items);
        $scope.newData = JSON.parse(stringData);
        console.log($scope.newData);
        //my code end
        var csv = $scope.convertArrayOfObjectsToCSV({
            data: $scope.newData
        });
        if (csv == null) return;

        // filename = args.filename || 'export.csv';
        filename =  $scope.selectedKeys[0] + '.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }

It works fine, only one problem is when some columns with the comma like this in object: status:"Pending, Charged Off" will be converted in to another column in csv file. I think I need to do something with this line:

columnDelimiter = args.columnDelimiter || ',';

but do not know how to do? Can any one help? Thank you in advanced!

Body:
To get , in a value surround it with double quotes ":

foo,"foo,bar",bar

Is interpreted in CSV as:

[ "foo", "foo,bar", "bar" ]

But what if your value also has a double quote in it? ie:

foo,"foo",bar",bar

Now this is just a mess. You need to escape the double quote by adding another double quote:

foo,"foo"",bar",bar

Gives:

[ "foo", "foo\",bar", "bar" ]


问:
How to fix WixCloseApplications: Error 0x8007064f: failed to open view on database?
I am new to Wix. While installing a msi, I would like to use the util:CloseApplication to detect if notepad.exe is running. My simple code.

```<code><Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
         xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

<util:CloseApplication CloseMessage="no" Target="notepad.exe" RebootPrompt="no"/>

<InstallExecuteSequence>
    <Custom Action="WixCloseApplications" After="InstallInitialize"/>
</InstallExecuteSequence>
</code>```

Failed to in both Wix 3.10 and 3.11 toolsets. Any suggestion?
Have also tried to execute the WixCloseApplications Before="InstallValidate". Same result.

MSI LogFile: (time stamp stripped off)

```<code>MSI (s) (6C:90) [10:47:42:356]: Doing action: WixCloseApplications
Action 10:47:42: WixCloseApplications.
Action start 10:47:42: WixCloseApplications.
MSI (s)  Creating MSIHANDLE (1) of type 790542 for thread 60816
MSI (s)  Invoking remote custom action. DLL: C:\Windows\Installer\MSI95B2.tmp, Entrypoint: WixCloseApplications
MSI (s)  Generating random cookie.
MSI (s)  Created Custom Action Server with PID 57776 (0xE1B0).
MSI (s)  Running as a service.
MSI (s)  Hello, I'm your 32bit Impersonated custom action server.
MSI (s)  Creating MSIHANDLE (2) of type 790541 for thread 60964
MSI (s)  Note: 1: 2205 2:  3: WixCloseApplication
MSI (s)  Note: 1: 2228 2:  3: WixCloseApplication 4: SELECT `WixCloseApplication`, `Target`, `Description`, `Condition`, `Attributes`, `Property`, `TerminateExitCode`, `Timeout` FROM `WixCloseApplication` ORDER BY `Sequence`
MSI (s)  Creating MSIHANDLE (3) of type 790531 for thread 60964
WixCloseApplications:  Error 0x8007064f: failed to open view on database
MSI (s)  Closing MSIHANDLE (3) of type 790531 for thread 60964
MSI (s)  Creating MSIHANDLE (4) of type 790531 for thread 60964
WixCloseApplications:  Error 0x8007064f: failed to open view on WixCloseApplication table
MSI (s) Closing MSIHANDLE (4) of type 790531 for thread 60964
MSI (s) Closing MSIHANDLE (2) of type 790541 for thread 60964
CustomAction WixCloseApplications returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)
MSI (s) Closing MSIHANDLE (1) of type 790542 for thread 60816
Action ended 10:47:42: WixCloseApplications. Return value 3.
MSI (s) Machine policy value 'DisableRollback' is 0
MSI (s) Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3: 2
MSI (s) Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3: 2
MSI (s) Calling SRSetRestorePoint API. dwRestorePtType: 13, dwEventType: 103, llSequenceNumber: 958, szDescription: "".
MSI (s) The call to SRSetRestorePoint API succeeded. Returned status: 0.
MSI (s) Unlocking Server
Action ended 10:47:42: INSTALL. Return value 3.
</code>```

答:
I think I have found out the root cause of the problem I experienced.
If I put the complete ClosApplication codes inside a <Fragment></Fragment>, the whole fragment of code is skipped (simply due to lack of reference).

```<code><Fragment>
    <util:CloseApplication ID="StopNotepad" CloseMessage="no" Target="notepad.exe" RebootPrompt="no"/>

    <InstallExecuteSequence>
        <Custom Action="WixCloseApplications" After="InstallInitialize"/>
    </InstallExecuteSequence>
</Fragment>
</code>```

The problem I saw earlier was slightly different. My fragment just contain this

```<code><Fragment>
    <util:CloseApplication ID="StopNotepad" CloseMessage="no" Target="notepad.exe" RebootPrompt="no"/>
</Fragment>
</code>```

The required custom action was included via an external wxi file. The final msi contains the call to custom action but missing the Util:CloseApplication declaration. As a result, the msi failed to deploy and I saw the weird log entry stating WixCloseApplications:  Error 0x8007064f: failed to open view on database

Solution:
By moving the <util:CloseApplication fragment code inside the <Product><\Product> or other existing <Fragment> that has a reference to the outside world. For example, Directory Id=etc will resolve the problem.

Unless there is a way to include <util:CloseApplication reference (that I am not aware of), don't put the <util:CloseApplication code in its own fragment!

Body:
I am new to Wix. While installing a msi, I would like to use the util:CloseApplication to detect if notepad.exe is running. My simple code.

<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
         xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

<util:CloseApplication CloseMessage="no" Target="notepad.exe" RebootPrompt="no"/>

<InstallExecuteSequence>
    <Custom Action="WixCloseApplications" After="InstallInitialize"/>
</InstallExecuteSequence>

Failed to in both Wix 3.10 and 3.11 toolsets. Any suggestion?
Have also tried to execute the WixCloseApplications Before="InstallValidate". Same result.

MSI LogFile: (time stamp stripped off)

MSI (s) (6C:90) [10:47:42:356]: Doing action: WixCloseApplications
Action 10:47:42: WixCloseApplications.
Action start 10:47:42: WixCloseApplications.
MSI (s)  Creating MSIHANDLE (1) of type 790542 for thread 60816
MSI (s)  Invoking remote custom action. DLL: C:\Windows\Installer\MSI95B2.tmp, Entrypoint: WixCloseApplications
MSI (s)  Generating random cookie.
MSI (s)  Created Custom Action Server with PID 57776 (0xE1B0).
MSI (s)  Running as a service.
MSI (s)  Hello, I'm your 32bit Impersonated custom action server.
MSI (s)  Creating MSIHANDLE (2) of type 790541 for thread 60964
MSI (s)  Note: 1: 2205 2:  3: WixCloseApplication
MSI (s)  Note: 1: 2228 2:  3: WixCloseApplication 4: SELECT `WixCloseApplication`, `Target`, `Description`, `Condition`, `Attributes`, `Property`, `TerminateExitCode`, `Timeout` FROM `WixCloseApplication` ORDER BY `Sequence`
MSI (s)  Creating MSIHANDLE (3) of type 790531 for thread 60964
WixCloseApplications:  Error 0x8007064f: failed to open view on database
MSI (s)  Closing MSIHANDLE (3) of type 790531 for thread 60964
MSI (s)  Creating MSIHANDLE (4) of type 790531 for thread 60964
WixCloseApplications:  Error 0x8007064f: failed to open view on WixCloseApplication table
MSI (s) Closing MSIHANDLE (4) of type 790531 for thread 60964
MSI (s) Closing MSIHANDLE (2) of type 790541 for thread 60964
CustomAction WixCloseApplications returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)
MSI (s) Closing MSIHANDLE (1) of type 790542 for thread 60816
Action ended 10:47:42: WixCloseApplications. Return value 3.
MSI (s) Machine policy value 'DisableRollback' is 0
MSI (s) Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3: 2
MSI (s) Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3: 2
MSI (s) Calling SRSetRestorePoint API. dwRestorePtType: 13, dwEventType: 103, llSequenceNumber: 958, szDescription: "".
MSI (s) The call to SRSetRestorePoint API succeeded. Returned status: 0.
MSI (s) Unlocking Server
Action ended 10:47:42: INSTALL. Return value 3.

Body:
I think I have found out the root cause of the problem I experienced.
If I put the complete ClosApplication codes inside a <Fragment></Fragment>, the whole fragment of code is skipped (simply due to lack of reference).

<Fragment>
    <util:CloseApplication ID="StopNotepad" CloseMessage="no" Target="notepad.exe" RebootPrompt="no"/>

    <InstallExecuteSequence>
        <Custom Action="WixCloseApplications" After="InstallInitialize"/>
    </InstallExecuteSequence>
</Fragment>

The problem I saw earlier was slightly different. My fragment just contain this

<Fragment>
    <util:CloseApplication ID="StopNotepad" CloseMessage="no" Target="notepad.exe" RebootPrompt="no"/>
</Fragment>

The required custom action was included via an external wxi file. The final msi contains the call to custom action but missing the Util:CloseApplication declaration. As a result, the msi failed to deploy and I saw the weird log entry stating WixCloseApplications:  Error 0x8007064f: failed to open view on database

Solution:
By moving the <util:CloseApplication fragment code inside the <Product><\Product> or other existing <Fragment> that has a reference to the outside world. For example, Directory Id=etc will resolve the problem.

Unless there is a way to include <util:CloseApplication reference (that I am not aware of), don't put the <util:CloseApplication code in its own fragment!


问:
Can't open lib '/usr/lib/oracle/11.2/client64/lib/libsqora.so.11.1 when create "Database Monitor" item in zabbix
Before that, unixODBC was installed

unixODBC.x86_64                        2.2.14-14.el6

unixODBC-devel.x86_64                  2.2.14-14.el6

And Oracle ODBC driver installed is:

oracle-instantclient11.2-basic-11.2.0.1.0-1.x86_64

oracle-instantclient11.2-odbc-11.2.0.1.0-1.x86_64

oracle-instantclient11.2-devel-11.2.0.1.0-1.x86_64

And odbcinst.ini:

```<code>[Oracle-11g]
Description=ODBC for Oracle
Driver=/usr/lib/oracle/11.2/client64/lib/libsqora.so.11.1
UsageCount=1
FileUsage=1
Driver Logging = 7
</code>```

odbc.ini:

```<code>[test]
Driver      = Oracle-11g
DSN = Oracle-11g
ServerName =  gzdb
UserID = xxx
Password = xxx
</code>```

And ODBC connection is working successfully

```<code>shell> isql -v test
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
</code>```

To enable ODBC support, I recompiled zabbix3.0 with flag: --with-unixodbc

```<code>./configure --enable-server --enable-agent --with-mysql --enable-ipv6 --with-net-snmp --with-libcurl --with-libxml2 --with-unixodbc
</code>```

and replace the old zabbix_sever with new binary compiled.

However, When I create "Database Monitor" item in zabbix,there is still an error:
enter image description here

So I run su - zabbix -c "ldd /usr/lib/oracle/11.2/client64/lib/libsqora.so.11.1"
it appears ok

```<code> su - zabbix -c "ldd /usr/lib/oracle/11.2/client64/lib/libsqora.so.11.1"
    linux-vdso.so.1 =>  (0x00007fffe21ee000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00007f1ad095e000)
    libm.so.6 => /lib64/libm.so.6 (0x00007f1ad06d9000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f1ad04bc000)
    libnsl.so.1 => /lib64/libnsl.so.1 (0x00007f1ad02a3000)
    libclntsh.so.11.1 => /usr/lib/oracle/11.2/client64/lib/libclntsh.so.11.1 (0x00007f1acdd72000)
    libodbcinst.so.1 => /usr/lib64/libodbcinst.so.1 (0x00007f1acdb61000)
    libc.so.6 => /lib64/libc.so.6 (0x00007f1acd7cd000)
    /lib64/ld-linux-x86-64.so.2 (0x000000373c600000)
    libnnz11.so => /usr/lib/oracle/11.2/client64/lib/libnnz11.so (0x00007f1acd404000)
    libaio.so.1 => /lib64/libaio.so.1 (0x00007f1acd203000)
    libltdl.so.7 => /usr/lib64/libltdl.so.7 (0x00007f1accffa000)
</code>```

I really do not know what the error means

答:
That because your zabbix server doesn't know where to look for the Oracle lib.
Try to export environment variable LD_LIBRARY_PATH to the zabbix server

Don't know what OS you are using, I'm on CentOS 7

create /etc/sysconfig/zabbix-server file, and edit with

```<code>LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/lib/oracle/12.1/client64/lib"
export LD_LIBRARY_PATH
</code>```

then restart zabbix-server

Body:
Before that, unixODBC was installed

unixODBC.x86_64                        2.2.14-14.el6

unixODBC-devel.x86_64                  2.2.14-14.el6

And Oracle ODBC driver installed is:

oracle-instantclient11.2-basic-11.2.0.1.0-1.x86_64

oracle-instantclient11.2-odbc-11.2.0.1.0-1.x86_64

oracle-instantclient11.2-devel-11.2.0.1.0-1.x86_64

And odbcinst.ini:

[Oracle-11g]
Description=ODBC for Oracle
Driver=/usr/lib/oracle/11.2/client64/lib/libsqora.so.11.1
UsageCount=1
FileUsage=1
Driver Logging = 7

odbc.ini:

[test]
Driver      = Oracle-11g
DSN = Oracle-11g
ServerName =  gzdb
UserID = xxx
Password = xxx

And ODBC connection is working successfully

shell> isql -v test
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+

To enable ODBC support, I recompiled zabbix3.0 with flag: --with-unixodbc

./configure --enable-server --enable-agent --with-mysql --enable-ipv6 --with-net-snmp --with-libcurl --with-libxml2 --with-unixodbc

and replace the old zabbix_sever with new binary compiled.

However, When I create "Database Monitor" item in zabbix,there is still an error:
enter image description here

So I run su - zabbix -c "ldd /usr/lib/oracle/11.2/client64/lib/libsqora.so.11.1"
it appears ok

 su - zabbix -c "ldd /usr/lib/oracle/11.2/client64/lib/libsqora.so.11.1"
    linux-vdso.so.1 =>  (0x00007fffe21ee000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00007f1ad095e000)
    libm.so.6 => /lib64/libm.so.6 (0x00007f1ad06d9000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f1ad04bc000)
    libnsl.so.1 => /lib64/libnsl.so.1 (0x00007f1ad02a3000)
    libclntsh.so.11.1 => /usr/lib/oracle/11.2/client64/lib/libclntsh.so.11.1 (0x00007f1acdd72000)
    libodbcinst.so.1 => /usr/lib64/libodbcinst.so.1 (0x00007f1acdb61000)
    libc.so.6 => /lib64/libc.so.6 (0x00007f1acd7cd000)
    /lib64/ld-linux-x86-64.so.2 (0x000000373c600000)
    libnnz11.so => /usr/lib/oracle/11.2/client64/lib/libnnz11.so (0x00007f1acd404000)
    libaio.so.1 => /lib64/libaio.so.1 (0x00007f1acd203000)
    libltdl.so.7 => /usr/lib64/libltdl.so.7 (0x00007f1accffa000)

I really do not know what the error means

Body:
That because your zabbix server doesn't know where to look for the Oracle lib.
Try to export environment variable LD_LIBRARY_PATH to the zabbix server

Don't know what OS you are using, I'm on CentOS 7

create /etc/sysconfig/zabbix-server file, and edit with

LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/lib/oracle/12.1/client64/lib"
export LD_LIBRARY_PATH

then restart zabbix-server


问:
C#: Access Enum from another class
I know I can declare an enum directly in the Namespace so everyone can access it being in the same namespace.

But can I declare it in a class to access from other class:

public class Class1
{
    public enum Mode { Selected, New }
}

public class Class2
{
    var class1 = new ();
    // Set the Mode
    class1.Mode = Mode.Selected;
}
```

Is it possible to use enums without declaring it in the namespace?

答:
Yes:

```<code>class2.Mode = class2.Mode.Selected
</code>```

But note that you can't have a nested type defined that has the same name as one of the outer class' members, so this code will not compile.  Either the enum or the property will need to be named something else.  Your class name and variable name conflict too, making this a bit more complex.

To make this a more generic answer, if you have this:

```<code>public class Foo
{
    public SomeEnum SomeProperty { get; set; }

    public enum SomeEnum {
        Hello, World
    }
}
</code>```

Then this code will assign an enum value to the property:

```<code>Foo foo = new Foo();
foo.SomeProperty = Foo.SomeEnum.Hello;
</code>```

ContentLicense: CC BY-SA 4.0

Title: C#: Access Enum from another class

Body:
I know I can declare an enum directly in the Namespace so everyone can access it being in the same namespace.

But can I declare it in a class to access from other class:

public class Class1
{
    public enum Mode { Selected, New }
}

public class Class2
{
    var class1 = new ();
    // Set the Mode
    class1.Mode = Mode.Selected;
}

Is it possible to use enums without declaring it in the namespace?

Body:
Yes:

class2.Mode = class2.Mode.Selected

But note that you can't have a nested type defined that has the same name as one of the outer class' members, so this code will not compile.  Either the enum or the property will need to be named something else.  Your class name and variable name conflict too, making this a bit more complex.

To make this a more generic answer, if you have this:

public class Foo
{
    public SomeEnum SomeProperty { get; set; }

    public enum SomeEnum {
        Hello, World
    }
}

Then this code will assign an enum value to the property:

Foo foo = new Foo();
foo.SomeProperty = Foo.SomeEnum.Hello;

ContentLicense: CC BY-SA 2.5


问:
Can Nginx insert a missing "/" or missing "/bla/" in a URL?
Looking through the error.log file of Nginx, we can see requests coming as one of two incorrect patterns:

http://www.example.com/app-contextmoduleA/controller1 -> should be http://www.example.com/app-context/moduleA/controller1

http://www.example.com/app-contextcontroller2 -> should be http://www.example.com/app-context/moduleB/controller2

The current Nginx configuration looks like this:

```<code>server {

  listen        8080;

  location /app-context/ {

    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_pass http://localhost:8888/app-context/;
  }
}
</code>```

The challenge is inserting the missing / after app-context (for the first wrong URL) or missing /moduleB/ (for the second wrong URL). It doesn't look like try_files would support that, and I have not found a way to do it with rewrite.

Is there a way for Nginx to rewrite the URLs for both use cases? In particular, I would prefer not to have to know all the name of the modules or controllers in advance. There are many, so "hard-coding" them in the rewrite rule would be onerous.

答:
Looking through quite a few online resources and through trial and error, I was able to come to a good-enough solution:</p>

```<code>location /app-context {
    location ~ (moduleA|moduleB) {
      # inserts a forward slash after app-context if not there,
      # e.g. /app-contextmoduleA/foo/bar to /app-context/moduleA/foo/bar
      rewrite ^(/app-context(?!/))(.*) $1/$2 break;
      try_files $uri @proxy;
    }
    # inserts /defaultModule/ after app-context
    # e.g. /app-context/controller1 to /app-context/defaultModule/controller1
    rewrite ^(/app-context(?!/defaultModule/))(.*) $1/defaultModule/$2 break;
    try_files $uri @proxy;
}

location @proxy {
    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_pass http://localhost:8888;
}
</code>```

Body:
Looking through the error.log file of Nginx, we can see requests coming as one of two incorrect patterns:

http://www.example.com/app-contextmoduleA/controller1 -> should be http://www.example.com/app-context/moduleA/controller1

http://www.example.com/app-contextcontroller2 -> should be http://www.example.com/app-context/moduleB/controller2

The current Nginx configuration looks like this:

server {

  listen        8080;

  location /app-context/ {

    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_pass http://localhost:8888/app-context/;
  }
}

The challenge is inserting the missing / after app-context (for the first wrong URL) or missing /moduleB/ (for the second wrong URL). It doesn't look like try_files would support that, and I have not found a way to do it with rewrite.

Is there a way for Nginx to rewrite the URLs for both use cases? In particular, I would prefer not to have to know all the name of the modules or controllers in advance. There are many, so "hard-coding" them in the rewrite rule would be onerous.

Body:
Looking through quite a few online resources and through trial and error, I was able to come to a good-enough solution:

location /app-context {
    location ~ (moduleA|moduleB) {
      # inserts a forward slash after app-context if not there,
      # e.g. /app-contextmoduleA/foo/bar to /app-context/moduleA/foo/bar
      rewrite ^(/app-context(?!/))(.*) $1/$2 break;
      try_files $uri @proxy;
    }
    # inserts /defaultModule/ after app-context
    # e.g. /app-context/controller1 to /app-context/defaultModule/controller1
    rewrite ^(/app-context(?!/defaultModule/))(.*) $1/defaultModule/$2 break;
    try_files $uri @proxy;
}

location @proxy {
    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_pass http://localhost:8888;
}


问:
How to handle business rules in DDD + CQRS + Event Sourcing approach?
I'm trying to figure out how to deal with complex domain model using CQRS/ES approach. Let's imagine we have e.g. Order domain entity, which handles both state and behavior of order. It has a Status property with transition rules for switching between statuses (implementing State pattern or any other kind of state machine). According to DDD principles, this logic should be implemented in Order class (representing the Order model) itself, having methods like approve(), cancel(), ship(), etc.

Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules? Or just handle commands and events themselves, without having any write-model entity?

Pseudocode to illustrate:

```<code>class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        this.status.approve(); // business rules blah blah
        this.Apply(new OrderApproved(this.id)); // applying event
    }

    // ...
}
</code>```

Isn't that overdoing or somewhat?

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

EDIT2: fixed read/write models mistake

答: Put your business logic on Entities or Value Objet .If they don't fit there strive for Domain Services . </p>

Body:
I'm trying to figure out how to deal with complex domain model using CQRS/ES approach. Let's imagine we have e.g. Order domain entity, which handles both state and behavior of order. It has a Status property with transition rules for switching between statuses (implementing State pattern or any other kind of state machine). According to DDD principles, this logic should be implemented in Order class (representing the Order model) itself, having methods like approve(), cancel(), ship(), etc.

Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules? Or just handle commands and events themselves, without having any write-model entity?

Pseudocode to illustrate:

class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        this.status.approve(); // business rules blah blah
        this.Apply(new OrderApproved(this.id)); // applying event
    }

    // ...
}

Isn't that overdoing or somewhat?

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

EDIT2: fixed read/write models mistake


问:
Merging documents using OpenXml and section breaks causes empty paragraphs
I am stitching a couple of documents together with a requirement that each document should retain its header and footer information in the final document. Using AltChunk instead of raw OpenXml or DocumentBuilder saves a lot of effort with regards to styles, formatting, references, parts, etc.

Unfortunately, after a couple of days I can't seem to get a 100% working version due to a small and frustrating issue and I need some insight.

My code is loosly based on this article

I modify each sub document, prior to appending it (as an AltChunk) to a working document, by moving the last section properties into the last paragraph (in order to retain header and footer references), but Word seems to be adding a blank paragraph to each of these documents as it renders them in the final document.  I end up with:

document 1 with correct header and footer
section properties/break
blank paragraph
document 2 with correct header and footer
section properties/break
blank paragraph
etc.

I cant remove the blank paragraphs afterwards, as I ideally don't want to use WAS to render the document first.

It seems as if you cannot have a next-page section break without a following paragraph?

答:
I have the similar empty paragraph issue while importing HTML files.

My solution is,

After inserting HTML AltChunk, I add a GUID place holder. After processing the file, I will open the file again, locate the GUID and check if there is a empty paragraph before it, if so remove the empty paragraph and GUID. it seems work perfectly in my solution.

Hope it helps.


问:
Jetsam kills WebGL application on iOS
I am currently struggling with memory management inside a webgl application on the web, on iOS only.

I keep getting the following error message :

Application 'UIKitApplication:com.apple.Preferences[0xa7c1]' was killed by jetsam.

I understand that Jetsam is the system process responsible for memory management, but the crash occurs while the browser uses around 25% of the device's RAM, which is not that high. I don't have any other open application while running my webGL content. What I don't understand is what Taun Chapman said :

Jetsam monitors memory use and kills applications which are not good memory citizens. A good memory citizen is an application which is willing to give back memory when asked and does not keep asking for more memory.

Well, the app needs more memory in a short time (when unzipping 3D models using workers), I can't continue my app without it! And it crashed at these particular times.

Moreover, I think I have some memory leaks in my app, according to Chrome DevTools I am currently trying to fix. But the browser itself seems to have some leaks too. Thus, fixing mine will just delay the inevitable.

I know the following question is odd, or inappropriate, but do you know if the jetsam "limit" can be increased ? Or if you can add an exception on the currently running WebGL app ?

For your information, I use the Three.js WebGL library and the zip.js library to compress my 3D models.

Yes, I've already read the following question : Why does simple website crash on mobile (iOS Safari and Chrome, at least)?, but the problem does not come from my CSS.

答:
The 10.3.2 version of iOS (released the 15th of May) made Jetsam less aggressive, or at least, the memory is better handled.

https://support.apple.com/en-gb/HT207798

Title: Jetsam kills WebGL application on iOS


问:
A file or folder with the name already exists Visual Studio
I try to add a new file to my source controlled solution and receive this message:

A file or folder with the name 'xxx' already exists. Please give a unique
name to the item you are adding, or delete the existing item first.

I'm 100% sure that there is no file with the given name.

So how do I get VS to add items again?

答:
Steps if a folder is Missing

In the Solution Explorer window

Select visual studio project which holds the missing folder.

Select or turn on the Show All Files button (  ) to show the existing, but missing folder.

Select the hidden folder then right click and select the menu item Include in Project to add into the project in the project view.


问:
type of high order functions
if I specify the (I think) correct type for a high order function the OCaml compiler rejects the second usage of that function.

The code

```<code>let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y
</code>```

leads to the following error message

```File "test.ml", line 6, characters 14-15:
Error: This expression has type float -> string
       but an expression was expected of type int -> string```

So the first usage of f seems to fix the type of its first parameter to int -> string. I could understand that. But what I don't get is that omitting the type restriction on f fixes the problem.

```<code>let foo ():string  =
    let f g v = g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y</code>```

And moving f to global scope fixes the problem, too:

```<code>let f: ('a -> string) -> 'a -> string = fun g v -> g v

let foo ():string  =
  let h = string_of_int
  in let i = string_of_float
  in let x = f h 23
  in let y = f i 23.0
  in x ^ y</code>```

Why is it that the first example does not compile while the later ones do?

答:
Let me use a simpler example that illustrates the issue.

```<code># let cons0 (x : 'a) (y : 'a list) = x :: y;;
val cons0 : 'a -> 'a list -> 'a list = <fun>
# let cons1 (x : 'a) (y : 'a list) = x :: y in cons1 1 [];;
- : int list = [1]
# let cons2 (x : 'a) (y : 'a list) = x :: y in (cons2 1 [], cons2 true []);;
This expression has type bool but is here used with type int
# let cons3 x y = x :: y in (cons3 1 [], cons3 true []);;
- : int list * bool list = ([1], [true])
</code>```

cons0 is a polymorphic function definition, defined at global scope. It's just a trivial wrapper to the :: operator. Unsurprisingly, the definition works. cons1 is almost the same as cons0, except that its scope is limited to the expression in the in body. The change of scope looks innocuous, and sure enough, it typechecks. cons3 is again the same function, with no type annotation, and we can use it polymorphically in the in body.

So what's wrong with cons2? The problem is the scope of 'a: it's the whole toplevel phrase. The semantics of the phrase that defines cons2 is

```<code>for some type 'a, (let cons2 (x : 'a) (y : 'a list) = ... in ...)
</code>```

Since 'a must be compatible with int (due to cons3 1 []) and with bool (due to cons3 true [], there is no possible instantiation of 'a. Therefore the phrase is ill-typed.

If you like to think about ML typing in terms of its usual type inference algorithm, each explicit user variable introduces a set of constraints in the unification algorithm. Here the constraints are 'a = "type of the parameter x" and ' = "type of the parameter y". But the scope of 'a is the whole phrase, it's not generalized in any inner scope. So int and bool both end up unified to the non-generalized 'a.

Recent versions OCaml introduce scoped type variables (as in Niki Yoshiuchi's answer). The same effect could have been achieved with a local module in earlier versions (≥2.0):

```<code>let module M = struct
    let cons2 (x : 'a) (y : 'a list) = x :: y
  end in
(M.cons2 1 [], M.cons2 true []);;
</code>```

(Standard MLers note: this is one place where OCaml and SML differ.)

Title: type of high order functions

Body:
if I specify the (I think) correct type for a high order function the OCaml compiler rejects the second usage of that function.

The code

let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y

leads to the following error message

File "test.ml", line 6, characters 14-15:
Error: This expression has type float -> string
       but an expression was expected of type int -> string

So the first usage of f seems to fix the type of its first parameter to int -> string. I could understand that. But what I don't get is that omitting the type restriction on f fixes the problem.

let foo ():string  =
    let f g v = g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y

And moving f to global scope fixes the problem, too:

let f: ('a -> string) -> 'a -> string = fun g v -> g v

let foo ():string  =
  let h = string_of_int
  in let i = string_of_float
  in let x = f h 23
  in let y = f i 23.0
  in x ^ y

Why is it that the first example does not compile while the later ones do?

Body:
Let me use a simpler example that illustrates the issue.

# let cons0 (x : 'a) (y : 'a list) = x :: y;;
val cons0 : 'a -> 'a list -> 'a list = <fun>
# let cons1 (x : 'a) (y : 'a list) = x :: y in cons1 1 [];;
- : int list = [1]
# let cons2 (x : 'a) (y : 'a list) = x :: y in (cons2 1 [], cons2 true []);;
This expression has type bool but is here used with type int
# let cons3 x y = x :: y in (cons3 1 [], cons3 true []);;
- : int list * bool list = ([1], [true])

cons0 is a polymorphic function definition, defined at global scope. It's just a trivial wrapper to the :: operator. Unsurprisingly, the definition works. cons1 is almost the same as cons0, except that its scope is limited to the expression in the in body. The change of scope looks innocuous, and sure enough, it typechecks. cons3 is again the same function, with no type annotation, and we can use it polymorphically in the in body.

So what's wrong with cons2? The problem is the scope of 'a: it's the whole toplevel phrase. The semantics of the phrase that defines cons2 is

for some type 'a, (let cons2 (x : 'a) (y : 'a list) = ... in ...)

Since 'a must be compatible with int (due to cons3 1 []) and with bool (due to cons3 true [], there is no possible instantiation of 'a. Therefore the phrase is ill-typed.

If you like to think about ML typing in terms of its usual type inference algorithm, each explicit user variable introduces a set of constraints in the unification algorithm. Here the constraints are 'a = "type of the parameter x" and ' = "type of the parameter y". But the scope of 'a is the whole phrase, it's not generalized in any inner scope. So int and bool both end up unified to the non-generalized 'a.

Recent versions OCaml introduce scoped type variables (as in Niki Yoshiuchi's answer). The same effect could have been achieved with a local module in earlier versions (≥2.0):

let module M = struct
    let cons2 (x : 'a) (y : 'a list) = x :: y
  end in
(M.cons2 1 [], M.cons2 true []);;

(Standard MLers note: this is one place where OCaml and SML differ.)


问:
composer dump-autoload doesn´t work Laravel 4.2
If I run the composer dump-autoload in command line following happens :

```<code>Generating autoload files
Warning: Ambiguous class resolution, "CreateRevisionsTable" was found in both "$baseDir . '/app/database/migrations/2013_04_09_062329_create_revisions_table.php" and "C:\Users\Username\PhpstormProjects\projectname\www\ve ndor/venturecraft/revisionable/src/migrations\2013_04_09_062329_create_revisions_table.php" the first will be used
</code>```

But then nothing happenes and if i want to go and check out my project in browser he can´t find the Classes.

The autoload_classmap seems to be correct, too but still the error.

I tried to fix it for half a week and don´t seem to get a solution.

Please help.

Edit : Pasted in the file directorys
Additional Note : This error only happens to me. Other people working on this repository( shared via git) are totally fine

I recently upgraded my xampp to the php 7 version but even if i downgrade again it won´t work...

答:
What is the bla bla bit as this tells you where its being duplicated. You need to either rename one or see why it thinks you have two the same name.
Also does this help?
suppress-ambiguous-class-resolution-warning-on-composer-dump-autoload

or

ambiguous-class-resolution-in-laravel-phpexcel-update

Body:
If I run the composer dump-autoload in command line following happens :

Generating autoload files
Warning: Ambiguous class resolution, "CreateRevisionsTable" was found in both "$baseDir . '/app/database/migrations/2013_04_09_062329_create_revisions_table.php" and "C:\Users\Username\PhpstormProjects\projectname\www\ve ndor/venturecraft/revisionable/src/migrations\2013_04_09_062329_create_revisions_table.php" the first will be used

But then nothing happenes and if i want to go and check out my project in browser he can´t find the Classes.

The autoload_classmap seems to be correct, too but still the error.

I tried to fix it for half a week and don´t seem to get a solution.

Please help.

Edit : Pasted in the file directorys
Additional Note : This error only happens to me. Other people working on this repository( shared via git) are totally fine

I recently upgraded my xampp to the php 7 version but even if i downgrade again it won´t work...


问:
Sorting date m/y format in a data frame in R
I am trying to sort date column which is in the format M/Y. I tried using several ways given in other posts but none helped. Please suggest.
For 2012 it shows correctly with all the months given with 2012 but then it changes the pattern. Thank you.

Here is how it looks like currently

答:
1) This converts DF (see Note) to a zoo time series whose first column is of class yearmon and which is sorted by that.

```<code>library(zoo)

z <- read.zoo(DF, FUN = as.yearmon, format = "%m/%y")
</code>```

You may wish to keep it as a zoo object as above or to convert it back to a data frame:

```<code>fortify.zoo(z)
</code>```

2) This is an alternative to read.zoo.  It also uses class yearmon.

```<code>library(zoo)

DF2 <- transform(DF, monyear. = as.yearmon(monyear., "%m/%y"))
DF2[order(DF2$monyear.), ]
</code>```

Note: The above uses DF defined as:

```<code>library(tesseract)
u <- "https://i.stack.imgur.com/Szlhw.png"
DF <- read.table(text = ocr(u), header = TRUE, as.is = TRUE)
</code>```

Body:
1) This converts DF (see Note) to a zoo time series whose first column is of class yearmon and which is sorted by that.

library(zoo)

z <- read.zoo(DF, FUN = as.yearmon, format = "%m/%y")

You may wish to keep it as a zoo object as above or to convert it back to a data frame:

fortify.zoo(z)

2) This is an alternative to read.zoo.  It also uses class yearmon.

library(zoo)

DF2 <- transform(DF, monyear. = as.yearmon(monyear., "%m/%y"))
DF2[order(DF2$monyear.), ]

Note: The above uses DF defined as:

library(tesseract)
u <- "https://i.stack.imgur.com/Szlhw.png"
DF <- read.table(text = ocr(u), header = TRUE, as.is = TRUE)


问:
Woocommerce add action before div in woocommerce_before_main_content
I want to add the woocommerce_catalog_ordering action right before my shop-header div. This will add it after my container div. Since my custom html isn't an action like woocommerce has built in, i'm not sure how to order them both.

```<code>function shop_page_header() {
    get_template_part('elements/header-nav');

        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_catalog_ordering', 30 );
        // Remove the result count from WooCommerce
        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_result_count', 20 );

    if (is_shop()) { ?>

    <div class="container">
        <?php add_action( 'woocommerce_before_main_content', 'woocommerce_catalog_ordering', 20 ); ?>
        <div class="shop-header">
            <div class="callout">
                <div class="inner">
                    <h4>test</h4>
                    <h1>test</h1>
                    <div class="price">$59.00 - $149.00</div>
                    <h4>test</h4>
                    <a href="" class="btn brown arrow white-arrow">Shop Now</a>
                    <a href="" class="btn white-outline">View More</a>
                </div>
            </div>
        </div>
    </div>
    <?php }
}

add_action('woocommerce_before_main_content', 'shop_page_header');
</code>```

答: If your theme has the right hook built in you can use the Simply Show Hooks plugin to find the right one:  https://wordpress.org/plugins/simply-show-hooks/</p>

Body:
I want to add the woocommerce_catalog_ordering action right before my shop-header div. This will add it after my container div. Since my custom html isn't an action like woocommerce has built in, i'm not sure how to order them both.

function shop_page_header() {
    get_template_part('elements/header-nav');

        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_catalog_ordering', 30 );
        // Remove the result count from WooCommerce
        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_result_count', 20 );

    if (is_shop()) { ?>

        <?php add_action( 'woocommerce_before_main_content', 'woocommerce_catalog_ordering', 20 ); ?>

test

test

$59.00 - $149.00

test

                    Shop Now
                    View More

    <?php }
}

add_action('woocommerce_before_main_content', 'shop_page_header');


问:
PHP - highlight text from a string containing HTML
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

```<code><p>bla bla foo bar bla</p>
</code>```

so it should be something like:

```<code><p>bla <span class="highlight">foo bar</span> bla bla</p>
</code>```

答:
```<code>$searchString = 'foo bar';
$searchResult = '<p>bla bla foo bar bla</p>';

var_dump(str_replace($searchString, '<span>'.$searchString.'</span>', $searchResult));

var_dump(preg_replace('/'.$searchString.'/', '<span>'.$searchString.'</span>', $searchResult));
</code>```

Body:
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

bla bla foo bar bla

so it should be something like:

bla foo bar bla bla


问:
NullPointerException with HikariCP
I get the following error when starting my application:

```<code>java.lang.NullPointerException
        at me.MyApp.MyApp.Database.getConn(Database.java:30) ~[?:?]
        at me.MyApp.MyApp.Models.MyAppModel.<init>(MyAppModel.java:18) ~[?:?]
</code>```

Here is how I've set up my Database class:

```<code>public class Database {
    private static MyApp instance = MyApp.getInstance();
    private static Config config = new Config();

private static HikariDataSource ds = new HikariDataSource();

static {

    HikariConfig dbConfig = new HikariConfig();
    dbConfig.setJdbcUrl("jdbc:mysql://localhost:3306/" + config.get("database.database"));
    dbConfig.setUsername(config.get("database.username"));
    dbConfig.setPassword(config.get("database.password"));
    dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
    dbConfig.addDataSourceProperty("cachePrepStmts", "true");
    dbConfig.addDataSourceProperty("prepStmtCacheSize", "250");
        dbConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

}

    public static Connection getConn() {
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
</code>```

And here is my model class that triggers the error:

```<code>public class MyAppModel {

    private MyApp instance = MyApp.getInstance();
    private Connection connection;

    public MyAppModel() {
        connection = Database.getConn();
    }

    public void createTable() {
        BukkitRunnable r = new BukkitRunnable() {
            @Override
            public void run() {
                try {
                    String sql = "CREATE TABLE IF NOT EXISTS `myapp` ( " +
                            " `id` INT NOT NULL AUTO_INCREMENT ," +
                            "`uuid` VARCHAR(255) NOT NULL ," +
                            " `join_message` VARCHAR(255) NOT NULL ," +
                            " `quit_message` VARCHAR(255) NOT NULL ," +
                            " `change_points` INT NOT NULL," +
                            " `last_modified` TIMESTAMP NOT NULL," +
                            " PRIMARY KEY (`id`)" +
                            ")";
                    Statement statement = connection.createStatement();
                    statement.executeUpdate(sql);
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }
        };

        r.runTaskAsynchronously(instance);
    }
}
</code>```

I think MyAppModel connection returns null and I'm handling the TryCatch handling wrong, but I'm not entirely sure why it's returning null. What am I doing wrong?

I understand the concept of a NullPointerException but not why my application is giving me this error.

答:
In your getConn() function you call ds.getConnection() but the variable ds has never been created within your class. Make sure you initialize the HikariDataSource object called ds.

Sorry I was confused by the objects being used so change the dbConfig back to what you had and just create the new HikariDataSource object using its constructor according to the javadocs -> HikariDataSource(HikariConfig configuration)

Therefore you will need to switch the initialization of the objects and use your dbConfig object within the constructor of your HikariDataSource object.

```<code>private static HikariConfig dbConfig;
static { //keep this the same
    dbConfig = new HikariConfig();
    dbConfig.setJdbcUrl("jdbc:mysql://localhost:3306/" + config.get("database.database"));
    dbConfig.setUsername(config.get("database.username"));
    dbConfig.setPassword(config.get("database.password"));
    dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
    dbConfig.addDataSourceProperty("cachePrepStmts", "true");
    dbConfig.addDataSourceProperty("prepStmtCacheSize", "250");
    dbConfig.addDataSourceProperty( "prepStmtCacheSqlLimit", "2048");
}

private static HikariDataSource ds = new HikariDataSource(dbConfig); //intialize here with your newly created HikariConfig object
</code>```

Title: NullPointerException with HikariCP

Body:
I get the following error when starting my application:

java.lang.NullPointerException
        at me.MyApp.MyApp.Database.getConn(Database.java:30) ~[?:?]
        at me.MyApp.MyApp.Models.MyAppModel.<init>(MyAppModel.java:18) ~[?:?]

Here is how I've set up my Database class:

public class Database {
    private static MyApp instance = MyApp.getInstance();
    private static Config config = new Config();

private static HikariDataSource ds = new HikariDataSource();

static {

    HikariConfig dbConfig = new HikariConfig();
    dbConfig.setJdbcUrl("jdbc:mysql://localhost:3306/" + config.get("database.database"));
    dbConfig.setUsername(config.get("database.username"));
    dbConfig.setPassword(config.get("database.password"));
    dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
    dbConfig.addDataSourceProperty("cachePrepStmts", "true");
    dbConfig.addDataSourceProperty("prepStmtCacheSize", "250");
        dbConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

}

    public static Connection getConn() {
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

And here is my model class that triggers the error:

public class MyAppModel {

    private MyApp instance = MyApp.getInstance();
    private Connection connection;

    public MyAppModel() {
        connection = Database.getConn();
    }

    public void createTable() {
        BukkitRunnable r = new BukkitRunnable() {
            @Override
            public void run() {
                try {
                    String sql = "CREATE TABLE IF NOT EXISTS `myapp` ( " +
                            " `id` INT NOT NULL AUTO_INCREMENT ," +
                            "`uuid` VARCHAR(255) NOT NULL ," +
                            " `join_message` VARCHAR(255) NOT NULL ," +
                            " `quit_message` VARCHAR(255) NOT NULL ," +
                            " `change_points` INT NOT NULL," +
                            " `last_modified` TIMESTAMP NOT NULL," +
                            " PRIMARY KEY (`id`)" +
                            ")";
                    Statement statement = connection.createStatement();
                    statement.executeUpdate(sql);
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }
        };

        r.runTaskAsynchronously(instance);
    }
}

I think MyAppModel connection returns null and I'm handling the TryCatch handling wrong, but I'm not entirely sure why it's returning null. What am I doing wrong?

I understand the concept of a NullPointerException but not why my application is giving me this error.

Body:
In your getConn() function you call ds.getConnection() but the variable ds has never been created within your class. Make sure you initialize the HikariDataSource object called ds.

Sorry I was confused by the objects being used so change the dbConfig back to what you had and just create the new HikariDataSource object using its constructor according to the javadocs -> HikariDataSource(HikariConfig configuration)

Therefore you will need to switch the initialization of the objects and use your dbConfig object within the constructor of your HikariDataSource object.

private static HikariConfig dbConfig;
static { //keep this the same
    dbConfig = new HikariConfig();
    dbConfig.setJdbcUrl("jdbc:mysql://localhost:3306/" + config.get("database.database"));
    dbConfig.setUsername(config.get("database.username"));
    dbConfig.setPassword(config.get("database.password"));
    dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
    dbConfig.addDataSourceProperty("cachePrepStmts", "true");
    dbConfig.addDataSourceProperty("prepStmtCacheSize", "250");
    dbConfig.addDataSourceProperty( "prepStmtCacheSqlLimit", "2048");
}

private static HikariDataSource ds = new HikariDataSource(dbConfig); //intialize here with your newly created HikariConfig object


问:
R: how to properly create rx_forest_model object?
I'm trying to do a churn analysis with R and SQL Server 2016.
I have uploaded my dataset on my database in a local SQL Server and I did all the preliminary work on this dataset.
Well, now I have this function trainModel() which I would use to estimate my random model forest:

```<code>trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString

trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
                                table = trainTable,
                                colInfo = cdrColInfo)

## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)

## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
                             data = trainDataSQL,
                             nTree = 8,
                             maxDepth = 16,
                             mTry = 2,
                             minBucket = 1,
                             replace = TRUE,
                             importance = TRUE,
                             seed = 8,
                             parms = list(loss = c(0, 4, 1, 0)))

return(rx_forest_model)
}
</code>```

But when I run the function I get this wrong output:

```<code>> system.time({
+   trainModel(sqlSettings, trainTable)
+ })
   user  system elapsed
   0.29    0.07   58.18
Warning message:
In tempGetNumObs(numObs) :
  Number of observations not available for this data source. 'numObs' set to 1e6.
</code>```

And for this warning message, the function trainModel() does not create the object rx_forest_model

Does anyone have any suggestions on how to solve this problem?

答:
After several attempts, I found the reason why the function trainModel() did not function properly.
Is not a connection string problem and is not even a data source type issue.
The problem is in the syntax of function trainModel().

It is enough to eliminate from the body of the function the statement:

```<code>return(rx_forest_model)
</code>```

In this way, the function returns the same warning message, but creates the object rx_forest_model in the correct way.

So, the correct function is:

```<code>trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString

trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
                            table = trainTable,
                            colInfo = cdrColInfo)

## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)

## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
                             data = trainDataSQL,
                             nTree = 8,
                             maxDepth = 16,
                             mTry = 2,
                             minBucket = 1,
                             replace = TRUE,
                             importance = TRUE,
                             seed = 8,
                             parms = list(loss = c(0, 4, 1, 0)))

}
</code>```

Body:
I'm trying to do a churn analysis with R and SQL Server 2016.
I have uploaded my dataset on my database in a local SQL Server and I did all the preliminary work on this dataset.
Well, now I have this function trainModel() which I would use to estimate my random model forest:

trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString

trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
                                table = trainTable,
                                colInfo = cdrColInfo)

## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)

## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
                             data = trainDataSQL,
                             nTree = 8,
                             maxDepth = 16,
                             mTry = 2,
                             minBucket = 1,
                             replace = TRUE,
                             importance = TRUE,
                             seed = 8,
                             parms = list(loss = c(0, 4, 1, 0)))

return(rx_forest_model)
}

But when I run the function I get this wrong output:

> system.time({
+   trainModel(sqlSettings, trainTable)
+ })
   user  system elapsed
   0.29    0.07   58.18
Warning message:
In tempGetNumObs(numObs) :
  Number of observations not available for this data source. 'numObs' set to 1e6.

And for this warning message, the function trainModel() does not create the object rx_forest_model

Does anyone have any suggestions on how to solve this problem?

Body:
After several attempts, I found the reason why the function trainModel() did not function properly.
Is not a connection string problem and is not even a data source type issue.
The problem is in the syntax of function trainModel().

It is enough to eliminate from the body of the function the statement:

return(rx_forest_model)

In this way, the function returns the same warning message, but creates the object rx_forest_model in the correct way.

So, the correct function is:

trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString

trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
                            table = trainTable,
                            colInfo = cdrColInfo)

## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)

## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
                             data = trainDataSQL,
                             nTree = 8,
                             maxDepth = 16,
                             mTry = 2,
                             minBucket = 1,
                             replace = TRUE,
                             importance = TRUE,
                             seed = 8,
                             parms = list(loss = c(0, 4, 1, 0)))

}


问:
Cant save datetime2 in database because of foreign keys?
I am really struggeling with my datetimes at my rest service. All I want is to create a new date like this:

```<code>Date ter = new Date()
                    {
                        StartTime = dto.StartTime,
                        EndTime = dto.EndTime,
                        Name = dto.Name,
                        Place = dto.Place,
                        Datetype = tera,
                        Type = dto.Type,
                        //Squad = new Squad(),
                        TeamNumber = mannschaft.Id
                    };
                    uow.RepDate.Create(ter);
                    //mannschaft.Dates.Add(ter);
                    uow.SaveChanges();
</code>```

Instead of creating this date I get this error message:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

I dont have any foreign keys set in my date entity. Whats happening?

EDIT

My Date Entity:

```<code>public class Date
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Place { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    //public Squad Squad { get; set; }
    public virtual Datetype Datetype { get; set; }
    [ForeignKey("Datetype")]
    public int DatetypeId { get; set; }

    public string Type { get; set; }
    public virtual ICollection<Participation> Participations { get; set; }
    public virtual Squad Squad { get; set; }
    public int TeamNumber { get; set; }
}
</code>```

Inner Exception now (changed fields in date entity):

The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Dates_dbo.Datetypes_DatetypeId\". The conflict occurred in database \"SchoolDb\", table \"dbo.Datetypes\", column 'DatetypeId'.\r\nThe statement has been terminated.

Datetype:

```<code>public class Datetype
{
    [Key]
    public int DatetypeId { get; set; }
    public string Name { get; set; }
    //public virtual ICollection<Squad> Squads { get; set; }
    public int TeamId { get; set; }

}
</code>```

EDIT
The problem is here I think:

```<code> Datetype tera=new Datetype();
            if (mannschaft != null)
            {
                if (!dto.DatetypeId.Equals(null)) {
                foreach (Datetype termin in mannschaft.Datetypes)
                {
                    if (termin.DatetypeId == dto.DatetypeId)
                    {
                        tera = termin;
                    }
                }
</code>```

Whenever I tested the service I was to lazy to create a Datetype for the date so tera was a empty datetype. So the foreign key got several problems to find the datetype. When I created a datetype everything works fine. Is there a way to make datetype optional?

答:
Thank you for updating your question

We don't have the code for where you are getting your DateType entity when you assign it to your Date entity.  However, from the context and the errors it sounds like the DateType entity was not queried from the database by the context attempting to save the Date entity.  As such it is not being tracked by the context and when you call SaveChanges it attempts to insert that entity, which already exists in the database.

These are your options:

Query the DateType entity using the same context

Attach the DateType entity you have to the current context before saving it

Don't use the relationship assignment, instead just assign the foreign key ID

The most efficient option is the last one:

```<code>Date ter = new Date()
{
    StartTime = dto.StartTime,
    EndTime = dto.EndTime,
    Name = dto.Name,
    Place = dto.Place,
    //Datetype = tera,
    DatetypeId = tera.DatetypeId,
    Type = dto.Type,
    //Squad = new Squad(),
    TeamNumber = mannschaft.Id
};
uow.RepDate.Create(ter);
//mannschaft.Dates.Add(ter);
uow.SaveChanges();
</code>```

Body:
I am really struggeling with my datetimes at my rest service. All I want is to create a new date like this:

Date ter = new Date()
                    {
                        StartTime = dto.StartTime,
                        EndTime = dto.EndTime,
                        Name = dto.Name,
                        Place = dto.Place,
                        Datetype = tera,
                        Type = dto.Type,
                        //Squad = new Squad(),
                        TeamNumber = mannschaft.Id
                    };
                    uow.RepDate.Create(ter);
                    //mannschaft.Dates.Add(ter);
                    uow.SaveChanges();

Instead of creating this date I get this error message:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

I dont have any foreign keys set in my date entity. Whats happening?

EDIT

My Date Entity:

public class Date
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Place { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    //public Squad Squad { get; set; }
    public virtual Datetype Datetype { get; set; }
    [ForeignKey("Datetype")]
    public int DatetypeId { get; set; }

    public string Type { get; set; }
    public virtual ICollection<Participation> Participations { get; set; }
    public virtual Squad Squad { get; set; }
    public int TeamNumber { get; set; }
}

Inner Exception now (changed fields in date entity):

The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Dates_dbo.Datetypes_DatetypeId\". The conflict occurred in database \"SchoolDb\", table \"dbo.Datetypes\", column 'DatetypeId'.\r\nThe statement has been terminated.

Datetype:

public class Datetype
{
    [Key]
    public int DatetypeId { get; set; }
    public string Name { get; set; }
    //public virtual ICollection<Squad> Squads { get; set; }
    public int TeamId { get; set; }

}

EDIT
The problem is here I think:

 Datetype tera=new Datetype();
            if (mannschaft != null)
            {
                if (!dto.DatetypeId.Equals(null)) {
                foreach (Datetype termin in mannschaft.Datetypes)
                {
                    if (termin.DatetypeId == dto.DatetypeId)
                    {
                        tera = termin;
                    }
                }

Whenever I tested the service I was to lazy to create a Datetype for the date so tera was a empty datetype. So the foreign key got several problems to find the datetype. When I created a datetype everything works fine. Is there a way to make datetype optional?

Body:
Thank you for updating your question

We don't have the code for where you are getting your DateType entity when you assign it to your Date entity.  However, from the context and the errors it sounds like the DateType entity was not queried from the database by the context attempting to save the Date entity.  As such it is not being tracked by the context and when you call SaveChanges it attempts to insert that entity, which already exists in the database.

These are your options:

Query the DateType entity using the same context

Attach the DateType entity you have to the current context before saving it

Don't use the relationship assignment, instead just assign the foreign key ID

The most efficient option is the last one:

Date ter = new Date()
{
    StartTime = dto.StartTime,
    EndTime = dto.EndTime,
    Name = dto.Name,
    Place = dto.Place,
    //Datetype = tera,
    DatetypeId = tera.DatetypeId,
    Type = dto.Type,
    //Squad = new Squad(),
    TeamNumber = mannschaft.Id
};
uow.RepDate.Create(ter);
//mannschaft.Dates.Add(ter);
uow.SaveChanges();


问:
Significance of array with only one element
I have come across an array with only one element. This array is defined inside a structure. Which goes like this:

```<code>typedef struct abc
{
    int variable1;
    char variable2;
    float array[1];
};
</code>```

I don't understand why this array is required, why can't we define just a variable or define a  pointer(considering array property).

I want to use it. How do i use this variable? abc.array[0] seems correct. Isn't it.

Addition I am not using any dynamic memory allocation then what is its significance ?

答:
It's probably what is called the "struct hack". By allocating a large block of memory, the array becomes dynamic. The one element is just a placeholder to make it compile, in fact there will be many floats.

The dynamic array has to be the last element.

Use like this:

```<code>struct abc *ptr = malloc(sizeof(struct abc) + (N-1) * sizeof(float));
ptr->variable1 = N; /* usually store length somewhere in struct*/
</code>```

Body:
I have come across an array with only one element. This array is defined inside a structure. Which goes like this:

typedef struct abc
{
    int variable1;
    char variable2;
    float array[1];
};

I don't understand why this array is required, why can't we define just a variable or define a  pointer(considering array property).

I want to use it. How do i use this variable? abc.array[0] seems correct. Isn't it.

Addition I am not using any dynamic memory allocation then what is its significance ?

Body:
It's probably what is called the "struct hack". By allocating a large block of memory, the array becomes dynamic. The one element is just a placeholder to make it compile, in fact there will be many floats.

The dynamic array has to be the last element.

Use like this:

struct abc *ptr = malloc(sizeof(struct abc) + (N-1) * sizeof(float));
ptr->variable1 = N; /* usually store length somewhere in struct*/


问:
Is it possible to create a Singleton factory class maintaining a dictionary for instances?
I have multiple classes that inherit from IPrint. I want to instantiate these classes using a factory but I want to maintain a single instance of each type.
Is this possible?

Please find my sample code below.

```<code> public interface IPrint
    {
        void DoPrint();
    }
    public class DigitalPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class InkPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class PrintFactory
    {
        private static IDictionary<IPrint, object> prints = new
   Dictionary<IPrint, object>();
        private PrintFactory()
        {

        }
        public static IPrint GetPrint(PrintType type)
        {
            // return instance depending on type. Instantiate only once
             //like singleton
            // How to write so that it returns a single instance depending
            //on type
            return null;
        }
    }

    public enum PrintType
    {
        DigitalPrint,
        InkPrint
    }
</code>```

Can someone give me some idea if this is possible?

Thanks.

答:
Yes, it's possible.

This creates the IPrint's before they're needed.  You could make them lazily created, instead.

```<code>public class Program
{
    public static void Main(string[] args)
    {
        var factory = new PrintFactory();
        Console.WriteLine(PrintFactory.GetPrint(PrintType.DigitalPrint));
        Console.WriteLine(PrintFactory.GetPrint(PrintType.InkPrint));
    }
}

public interface IPrint
{
    void DoPrint();
}

public class DigitalPrint : IPrint
{
    public void DoPrint()
    {
        // logic
    }
}

public class InkPrint : IPrint
{
    public void DoPrint()
    {
        // logic
    }
}

public class PrintFactory
{
    // Make the dictionary from PrintType to IPrint instead of IPrint to object
    private static IDictionary<PrintType, IPrint> prints = new Dictionary<PrintType, IPrint>();

    // Initialize prints in a static constructor.
    static PrintFactory()
    {
        prints.Add(PrintType.DigitalPrint, new DigitalPrint());
        prints.Add(PrintType.InkPrint, new InkPrint());
    }

    public static IPrint GetPrint(PrintType type)
    {
        if (!prints.ContainsKey(type))
        {
            // TODO: Maybe throw an exception or log?
        }
        return prints[type];
    }
}

public enum PrintType
{
    DigitalPrint,
    InkPrint
}
</code>```

Body:
I have multiple classes that inherit from IPrint. I want to instantiate these classes using a factory but I want to maintain a single instance of each type.
Is this possible?

Please find my sample code below.

 public interface IPrint
    {
        void DoPrint();
    }
    public class DigitalPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class InkPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class PrintFactory
    {
        private static IDictionary<IPrint, object> prints = new
   Dictionary<IPrint, object>();
        private PrintFactory()
        {

        }
        public static IPrint GetPrint(PrintType type)
        {
            // return instance depending on type. Instantiate only once
             //like singleton
            // How to write so that it returns a single instance depending
            //on type
            return null;
        }
    }

    public enum PrintType
    {
        DigitalPrint,
        InkPrint
    }

Can someone give me some idea if this is possible?

Thanks.

Body:
Yes, it's possible.

This creates the IPrint's before they're needed.  You could make them lazily created, instead.

public class Program
{
    public static void Main(string[] args)
    {
        var factory = new PrintFactory();
        Console.WriteLine(PrintFactory.GetPrint(PrintType.DigitalPrint));
        Console.WriteLine(PrintFactory.GetPrint(PrintType.InkPrint));
    }
}

public interface IPrint
{
    void DoPrint();
}

public class DigitalPrint : IPrint
{
    public void DoPrint()
    {
        // logic
    }
}

public class InkPrint : IPrint
{
    public void DoPrint()
    {
        // logic
    }
}

public class PrintFactory
{
    // Make the dictionary from PrintType to IPrint instead of IPrint to object
    private static IDictionary<PrintType, IPrint> prints = new Dictionary<PrintType, IPrint>();

    // Initialize prints in a static constructor.
    static PrintFactory()
    {
        prints.Add(PrintType.DigitalPrint, new DigitalPrint());
        prints.Add(PrintType.InkPrint, new InkPrint());
    }

    public static IPrint GetPrint(PrintType type)
    {
        if (!prints.ContainsKey(type))
        {
            // TODO: Maybe throw an exception or log?
        }
        return prints[type];
    }
}

public enum PrintType
{
    DigitalPrint,
    InkPrint
}


问:
Convert UTC datetime string to local datetime
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

```<code>datetime.utcfromtimestamp(timestamp)
</code>```

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

```<code>"2011-01-21 02:37:21"
</code>```

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

答:
You can use calendar.timegm to convert your time to seconds since Unix epoch and time.localtime to convert back:

```<code>import calendar
import time

time_tuple = time.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
t = calendar.timegm(time_tuple)

print time.ctime(t)
</code>```

Gives Fri Jan 21 05:37:21 2011 (because I'm in UTC+03:00 timezone).

Body:
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

datetime.utcfromtimestamp(timestamp)

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

"2011-01-21 02:37:21"

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

Body:
You can use calendar.timegm to convert your time to seconds since Unix epoch and time.localtime to convert back:

import calendar
import time

time_tuple = time.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
t = calendar.timegm(time_tuple)

print time.ctime(t)

Gives Fri Jan 21 05:37:21 2011 (because I'm in UTC+03:00 timezone).


问:
Seeking One-Size-Fits-All Context Based Storage
First off, I wish context based storage was consistent across the framework!

With that said, I'm looking for an elegant solution to make these properties safe across ASP.NET, WCF and any other multithreaded .NET code. The properties are located in some low-level tracing helpers (these are exposed via methods if you're wondering why they're internal).

I'd rather not have a dependency on unneeded assemblies (like System.Web, etc). I don't want to require anyone using this code to configure anything. I just want it to work ;) That may be too tall of an order though...

Anyone have any tricks up their sleeves? (I've seen Spring's implementation)

```<code>    internal static string CurrentInstance
    {
        get
        {
            return CallContext.LogicalGetData(currentInstanceSlotName) as string;
        }
        set
        {
            CallContext.LogicalSetData(currentInstanceSlotName, value);
        }
    }

    internal static Stack<ActivityState> AmbientActivityId
    {
        get
        {
            Stack<ActivityState> stack = CallContext.LogicalGetData(ambientActivityStateSlotName) as Stack<ActivityState>;
            if (stack == null)
            {
                stack = new Stack<ActivityState>();
                CallContext.LogicalSetData(ambientActivityStateSlotName, stack);
            }

            return stack;
        }
    }
</code>```

Update

By safe I do not mean synchronized. Background on the issue here

答:
Here is a link to (at least part of) NHibernate's "context" implementation:

https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/nhibernate/src/NHibernate/Context/

It is not clear to me exactly where or how this comes into play in the context of NHibernate.  That is, if I wanted to store some values in "the context" would I get "the context" from NHibernate and add my values?  I don't use NHibernate, so I don't really know.

I suppose that you could look and determine for yourself if this kind of implementation would be useful to you.  Apparently the idea would be to inject the desired implementation, depending on the type of application (ASP.NET, WCF, etc).  That probably implies some configuration (maybe minimal if one were to use MEF to load "the" ICurrentSessionContext interface).

At any rate, I found this idea interesting when I found it some time ago while searching for information on CallContext.SetData/GetData/LogicalSetData/LogicalGetData, Thread.SetData/GetData, [ThreadStatic], etc.

Also, based on your use of CallContext.LogicalSetData rather than CallContext.SetData, I assume that you want to take advantage of the fact that information associated with the logical thread will be propagated to child threads as opposed to just wanting a "thread safe" place to store info.  So, if you were to set (pr Push) the AmbientActivity in your app's startup and then not push any more activities, any subsequent threads would also be part of that same activity since data stored via LogicalSetData is inherited by child threads.

If you have learned anything in the meantime since you first asked this question I would be very interested in hearing about it.  Even if you haven't, I would be interested in learning about what you are doing with the context.

At the moment, I am working on maintaining some context information for logging/tracing (similar to Trace.CorrelationManager.ActivityId and Trace.CorrelationManager.LogicalOpertionStack and log4net/NLog context support).  I would like to save some context (current app, current app instance, current activity (maybe nested)) for use in an app or WCF service AND I want to propagate it "automatically" across WCF service boundaries.  This is to allow logging statements logged in a central repository to be correlated by client/activity/etc.  We would be able to query and correlate for all logging statements by a specific instance of a specific application.  The logging statements could have been generated on the client or in one or more WCF services.

The WCF propagation of ActivityId is not necessarily sufficient for us because we want to propagate (or we think we do) more than just the ActivityId.  Also, we want to propagate this information from Silverlight clients to WCF services and Trace.CorrelationManager is not available in Silverlight (at least not in 4.0, maybe something like it will be available in the future).

Currently I am prototyping the propagation of our "context" information using IClientMessageInspector and IDispatchMessageInspector.  It looks like it will probably work ok for us.

Regarding a dependency on System.Web, the NHibernate implementation does have a "ReflectiveHttpContext" that uses reflection to access the HttpContext so there would not be a project dependency on System.Web.  Obviously, System.Web would have to be available where the app is deployed if HttpContext is configured to be used.

Body:
First off, I wish context based storage was consistent across the framework!

With that said, I'm looking for an elegant solution to make these properties safe across ASP.NET, WCF and any other multithreaded .NET code. The properties are located in some low-level tracing helpers (these are exposed via methods if you're wondering why they're internal).

I'd rather not have a dependency on unneeded assemblies (like System.Web, etc). I don't want to require anyone using this code to configure anything. I just want it to work ;) That may be too tall of an order though...

Anyone have any tricks up their sleeves? (I've seen Spring's implementation)

    internal static string CurrentInstance
    {
        get
        {
            return CallContext.LogicalGetData(currentInstanceSlotName) as string;
        }
        set
        {
            CallContext.LogicalSetData(currentInstanceSlotName, value);
        }
    }

    internal static Stack<ActivityState> AmbientActivityId
    {
        get
        {
            Stack<ActivityState> stack = CallContext.LogicalGetData(ambientActivityStateSlotName) as Stack<ActivityState>;
            if (stack == null)
            {
                stack = new Stack<ActivityState>();
                CallContext.LogicalSetData(ambientActivityStateSlotName, stack);
            }

            return stack;
        }
    }

Update

By safe I do not mean synchronized. Background on the issue here


问:
get the most recent two dates for a customer MySQL
I need to retrieve the last two dates for customers with entries in at least two different dates, implying there are some customer who had purchased only in one date, the table is as follow

```<code>client_id  date
1          2016-07-02
1          2016-07-02
1          2016-06-01
2          2015-06-01
</code>```

as a response, I would get

```<code>client_id      previous_date     last_date
1              2016-06-01        2016-07-02
</code>```

important:

a client can have multiple entries for the same date

a client can have entries only for one date, such customer should be discarded

答:
Try this: group by the client_id column, with a having of count(*) > 1 to find results with more than one result. Then do a check of the min and max date, to ensure they aren't the same. Then just select the date, and order the results by date in desc order, with a limit of 2.

```<code>select
    date
from
    my_table
group by
    client_id
having
    min(date) <> max(date)
    and count(*) > 1
order by
    date desc
limit 2
</code>```

Body:
I need to retrieve the last two dates for customers with entries in at least two different dates, implying there are some customer who had purchased only in one date, the table is as follow

client_id  date
1          2016-07-02
1          2016-07-02
1          2016-06-01
2          2015-06-01

as a response, I would get

client_id      previous_date     last_date
1              2016-06-01        2016-07-02

important:

a client can have multiple entries for the same date

a client can have entries only for one date, such customer should be discarded

Body:
Try this: group by the client_id column, with a having of count(*) > 1 to find results with more than one result. Then do a check of the min and max date, to ensure they aren't the same. Then just select the date, and order the results by date in desc order, with a limit of 2.

select
    date
from
    my_table
group by
    client_id
having
    min(date) <> max(date)
    and count(*) > 1
order by
    date desc
limit 2