问:
Keras - Modifying lambda layer after `compile()`
In Keras, how do I change a lambda layer after the model is compiled?

More specifically, let's say I want a lambda layer that computes y=a*x+b with a and b being changed every epoch.

```<code>import keras
from keras.layers import Input, Lambda, Dense
import numpy as np

np.random.seed(seed=42)

a = 1
b = 2

def f(x, a, b):
    return a * x + b

inputs = keras.layers.Input(shape=(3,))
lam = Lambda(f, arguments={"a": a, "b": b})(inputs)
out = keras.layers.Dense(5)(lam)

model = keras.models.Model(inputs, out)
model.trainable = False
model.compile(optimizer='rmsprop', loss='mse')

x1 = np.random.random((10, 3))
x2 = np.random.random((10, 5))

model.fit(x1, x2, epochs=1)

print("Updating. But that won't work")
a = 10
b = 20
model.fit(x1, x2, epochs=1)
</code>```

This returns twice loss: 5.2914 where it should return once loss: 5.2914 and then loss: 562.0562.

As far as I can tell, this seems to be an open issue, which could be remedied by writing a custom layer but I haven't been to make it work.

Any guidance is welcomed.

答:
If you work with a and b being tensors, you can change their values even after compilation.

There are two approaches. In one, you treat a and b as global vars and take them from outside the function:

```<code>import keras.backend as K

a = K.variable([1])
b = K.variable([2])

def f(x):
    return a*x + b #see the vars coming from outside here

#....

lam = Lambda(f)(inputs)
</code>```

At any moment, you can manually call K.set_value(a,[newNumber]).

```<code>K.set_value(a,[10])
K.set_value(b,[20])
model.fit(x1,x2,epochs=1)
</code>```

In another approach (I don't know if there are advantages, but...it sounds at least better organized) you can make a and b be inputs to the model:

```<code>a = K.variable([1])
b = K.variable([2])
aInput = Input(tensor=a)
bInput = Input(tensor=b)

def f(x):
    return x[0]*x[1] + x[2] #here, we input all tensors in the function

#.....

lam = Lambda(f)([inputs,aInput,bInput])
</code>```

You set the values of a and b the same way as the other approach.

Body:
In Keras, how do I change a lambda layer after the model is compiled?

More specifically, let's say I want a lambda layer that computes y=a*x+b with a and b being changed every epoch.

import keras
from keras.layers import Input, Lambda, Dense
import numpy as np

np.random.seed(seed=42)

a = 1
b = 2

def f(x, a, b):
    return a * x + b

inputs = keras.layers.Input(shape=(3,))
lam = Lambda(f, arguments={"a": a, "b": b})(inputs)
out = keras.layers.Dense(5)(lam)

model = keras.models.Model(inputs, out)
model.trainable = False
model.compile(optimizer='rmsprop', loss='mse')

x1 = np.random.random((10, 3))
x2 = np.random.random((10, 5))

model.fit(x1, x2, epochs=1)

print("Updating. But that won't work")
a = 10
b = 20
model.fit(x1, x2, epochs=1)

This returns twice loss: 5.2914 where it should return once loss: 5.2914 and then loss: 562.0562.

As far as I can tell, this seems to be an open issue, which could be remedied by writing a custom layer but I haven't been to make it work.

Any guidance is welcomed.

Body:
If you work with a and b being tensors, you can change their values even after compilation.

There are two approaches. In one, you treat a and b as global vars and take them from outside the function:

import keras.backend as K

a = K.variable([1])
b = K.variable([2])

def f(x):
    return a*x + b #see the vars coming from outside here

#....

lam = Lambda(f)(inputs)

At any moment, you can manually call K.set_value(a,[newNumber]).

K.set_value(a,[10])
K.set_value(b,[20])
model.fit(x1,x2,epochs=1)

In another approach (I don't know if there are advantages, but...it sounds at least better organized) you can make a and b be inputs to the model:

a = K.variable([1])
b = K.variable([2])
aInput = Input(tensor=a)
bInput = Input(tensor=b)

def f(x):
    return x[0]*x[1] + x[2] #here, we input all tensors in the function

#.....

lam = Lambda(f)([inputs,aInput,bInput])

You set the values of a and b the same way as the other approach.


来源: stackexchange

问:
using rand() in a function in c
I have made a function that creates a random number between 0 and 9 but when i call the function in main in a for loop with index i = 0 ; i < n ; i++ it prints 1 random number n types. but i want different values to be printed n times.
here is the code which i made :-

```<code>    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
     int i;
     srand(time(NULL));
     i = rand()%10;
     printf("%d ",i);
    }
    main() {
     for(int j=0;j<10;j++) {
      random_variable();
     }
    }
</code>```

output is this :-

please click on the link to see the output :-
here instead of 8 ten times i needed 10 different values

答:
srand() initializes the PRNG (pseudo random number generator) of your standard C library. A PRNG works by applying more-or-less complicated arithmetic operations to a value stored internally and returning part of the result as the next "random" number. srand() sets this internal state.

If you call srand() every time in your function, you won't get (sensible) random numbers because the internal state is reset every time. Call it once your program starts.

ContentLicense: CC BY-SA 3.0

Title: using rand() in a function in c

Body:
I have made a function that creates a random number between 0 and 9 but when i call the function in main in a for loop with index i = 0 ; i < n ; i++ it prints 1 random number n types. but i want different values to be printed n times.
here is the code which i made :-

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
     int i;
     srand(time(NULL));
     i = rand()%10;
     printf("%d ",i);
    }
    main() {
     for(int j=0;j<10;j++) {
      random_variable();
     }
    }

output is this :-

please click on the link to see the output :-
here instead of 8 ten times i needed 10 different values


问:
How to remove controls in WinAPI (opposite of CreateWindowEX)
So I can create controls I need using CreateWindowEx, but now I am trying to remove them completely.

I tried using

```<code>DestroyWindow(hwndCustom);
DestroyWindow(hwndLabel);
DestroyWindow(hwndUpDnEdtBdy);
DestroyWindow(hwndUpDnCtl);
DestroyWindow(hwndSlider);
</code>```

And etc. but the controls are still showing in the window.

How can I remove them completely?

Do I need to repaint the window?

Controls are subclassed, the subclass is created on the click of one button and deleted on the click of another button in the main MsgProc

The DestroyWindow functions are in the destructor of the subclass

Creation of controls goes without issues, but they don't get removed from the window

Thanks,

-D

答:
Ok, I figured it out, the controls are being deleted, but the window still leaves them painted on. I am still having this issue and other artifacts appearing when dragging or resizing the window.

EDIT:

The problem was creating the window, I changed:

```<code>w_cex.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
</code>```

To

```<code>w_cex.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
</code>```

And it worked fine afterwards

Body:
So I can create controls I need using CreateWindowEx, but now I am trying to remove them completely.

I tried using

DestroyWindow(hwndCustom);
DestroyWindow(hwndLabel);
DestroyWindow(hwndUpDnEdtBdy);
DestroyWindow(hwndUpDnCtl);
DestroyWindow(hwndSlider);

And etc. but the controls are still showing in the window.

How can I remove them completely?

Do I need to repaint the window?

Controls are subclassed, the subclass is created on the click of one button and deleted on the click of another button in the main MsgProc

The DestroyWindow functions are in the destructor of the subclass

Creation of controls goes without issues, but they don't get removed from the window

Thanks,

-D

Body:
Ok, I figured it out, the controls are being deleted, but the window still leaves them painted on. I am still having this issue and other artifacts appearing when dragging or resizing the window.

EDIT:

The problem was creating the window, I changed:

w_cex.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);

To

w_cex.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);

And it worked fine afterwards


问:
Unable to install GitHub for Windows
I'm trying to install github for windows when I received this error:

```<code>Application cannot be started. Contact the application vendor.
</code>```

The error log produced this:

```<code>PLATFORM VERSION INFO
    Windows             : 6.2.9200.0 (Win32NT)
    Common Language Runtime     : 4.0.30319.34014
    System.Deployment.dll       : 4.0.30319.33440 built by: FX45W81RTMREL
    clr.dll             : 4.0.30319.34014 built by: FX45W81RTMGDR
    dfdll.dll           : 4.0.30319.33440 built by: FX45W81RTMREL
    dfshim.dll          : 6.3.9600.16384 (winblue_rtm.130821-1623)

SOURCES
    Deployment url          : http://github-windows.s3.amazonaws.com/GitHub.application

ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of http://github-windows.s3.amazonaws.com/GitHub.application resulted in exception. Following failure messages were detected:
        + The referenced assembly is not installed on your system. (Exception from HRESULT: 0x800736B3)

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [8/22/2014 12:51:27 AM] : Activation of http://github-windows.s3.amazonaws.com/GitHub.application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [8/22/2014 12:51:28 AM] System.Runtime.InteropServices.COMException
        - The referenced assembly is not installed on your system. (Exception from HRESULT: 0x800736B3)
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Internal.Isolation.IStore.GetAssemblyInformation(UInt32 Flags, IDefinitionIdentity DefinitionIdentity, Guid& riid)
            at System.Deployment.Application.ComponentStore.GetSubscriptionStateInternal(DefinitionIdentity subId)
            at System.Deployment.Application.SubscriptionStore.GetSubscriptionStateInternal(SubscriptionState subState)
            at System.Deployment.Application.SubscriptionState.Validate()
            at System.Deployment.Application.SubscriptionStore.CheckAndReferenceApplication(SubscriptionState subState, DefinitionAppId appId, Int64 transactionId)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

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

According to https://status.github.com/messages ,  there are no issues currently with the servers.
I am on a personal computer so there shouldn't be any issues with the connection. I tried downloading the application directly from  http://github-windows.s3.amazonaws.com/GitHub.application , but the result was the same.

I am running Windows 8.1 Pro x64.

Edit 1: Currently I'm working around being unable to install GitHub for Windows by first installing it on another system, then taking the newly installed files from %appdata%\Local\Apps\2.0, and moving them to the system that is having trouble installing. (The full directory is %appdata%\Local\Apps\2.0\EWG9HYRR.BKG\2XKOJCRD.XRD\gith..tion_317444273a93ac29_0002.0002_f44dcb2e9d4cde94).

One of the major caveats of this workaround is that on the problem system, GitHub for Windows will report "This isn't a networked deployed app." and therefor not automatically update.

答: The problem we had was that a third-party security application that controlled our corporate firewall on each device was blocking ClickOnce from accessing dfshim.dll over WiFi, so one potential solution for us was to have our inspectors start the .NET application while connected via ethernet and then after the app was booted up they could go out and perform their inspections.</p>

Title: Unable to install GitHub for Windows

Body:
I'm trying to install github for windows when I received this error:

Application cannot be started. Contact the application vendor.

The error log produced this:

PLATFORM VERSION INFO
    Windows             : 6.2.9200.0 (Win32NT)
    Common Language Runtime     : 4.0.30319.34014
    System.Deployment.dll       : 4.0.30319.33440 built by: FX45W81RTMREL
    clr.dll             : 4.0.30319.34014 built by: FX45W81RTMGDR
    dfdll.dll           : 4.0.30319.33440 built by: FX45W81RTMREL
    dfshim.dll          : 6.3.9600.16384 (winblue_rtm.130821-1623)

SOURCES
    Deployment url          : http://github-windows.s3.amazonaws.com/GitHub.application

ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of http://github-windows.s3.amazonaws.com/GitHub.application resulted in exception. Following failure messages were detected:
        + The referenced assembly is not installed on your system. (Exception from HRESULT: 0x800736B3)

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [8/22/2014 12:51:27 AM] : Activation of http://github-windows.s3.amazonaws.com/GitHub.application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [8/22/2014 12:51:28 AM] System.Runtime.InteropServices.COMException
        - The referenced assembly is not installed on your system. (Exception from HRESULT: 0x800736B3)
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Internal.Isolation.IStore.GetAssemblyInformation(UInt32 Flags, IDefinitionIdentity DefinitionIdentity, Guid& riid)
            at System.Deployment.Application.ComponentStore.GetSubscriptionStateInternal(DefinitionIdentity subId)
            at System.Deployment.Application.SubscriptionStore.GetSubscriptionStateInternal(SubscriptionState subState)
            at System.Deployment.Application.SubscriptionState.Validate()
            at System.Deployment.Application.SubscriptionStore.CheckAndReferenceApplication(SubscriptionState subState, DefinitionAppId appId, Int64 transactionId)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

According to https://status.github.com/messages ,  there are no issues currently with the servers.
I am on a personal computer so there shouldn't be any issues with the connection. I tried downloading the application directly from  http://github-windows.s3.amazonaws.com/GitHub.application , but the result was the same.

I am running Windows 8.1 Pro x64.

Edit 1: Currently I'm working around being unable to install GitHub for Windows by first installing it on another system, then taking the newly installed files from %appdata%\Local\Apps\2.0, and moving them to the system that is having trouble installing. (The full directory is %appdata%\Local\Apps\2.0\EWG9HYRR.BKG\2XKOJCRD.XRD\gith..tion_317444273a93ac29_0002.0002_f44dcb2e9d4cde94).

One of the major caveats of this workaround is that on the problem system, GitHub for Windows will report "This isn't a networked deployed app." and therefor not automatically update.


问:
Intel System Studio IoT edition installation error: SetUp Wizard ended prematurely; Integrity checking failed
I'm trying to install Intel System Studio IoT edition and it keeps failing. Can anyone help fix the error?

答: I recommend you use the Intel System Studio 2018 Beta, which carries forward the IoT functionality (docker containers) https://software.intel.com/sites/intel-system-studio-2018-beta/#/</p>


问:
Embed child records into single row with parent information
I have the following tables

BATCH

```<code>BatchID     Name      CustomerID  DateCreated  Status
12           A         1           01/01/2013   Active
13           B         12          01/01/2013   Inactive
14           C         245         01/01/2013   Complete
</code>```

BATCHDETAIL

```<code>BatchDetailID  BatchID  Weight  Price    DestinationCode
1              12       55      500.00   99
2              12       119     1500.00  55
3              13       12      133      1212
</code>```

A batch record can have many batch detail records linked via the FK BatchDetail.BatchID

I want to write a query to select a single row back to the user which combines the information in the BATCH record and the Weight,Price and DestinationCode from both BATCHDETAIL records for BatchID = 12

So the output would be :

```<code>BatchID      Name      CustomerID  DateCreated  Status  WeightA PriceA  DestinationCodeA  WeightB  PriceB   DestinationCodeB
12           A         1           01/01/2013   Active  55      500.00  99                119       1500      55
</code>```

So you can see I want to have 1 row with all information combined in the one row  and differentiate each detail record with A or B ( Lets assume a maximum of 2 detail records is only allowed )

I have thought of creating a table with these fields and then building up the information in a series of select statements and finally doing a select on the temp table but getting the query into a single block of SQL would be ideal.

答:
Here is a solution using dynamic SQL:

```<code>-- Get the MAX total number of records per BatchID (how many sets of columns do we need?)

DECLARE @requiredLevels int = (SELECT MAX(C) FROM (SELECT COUNT(*) C FROM BATCHDETAIL GROUP BY BatchID) Q)
;

-- Build a dynamic statement for the final SELECT fields

DECLARE
    @finalFieldsSQL varchar(1000) = ''
    , @finalFieldsN int = 1
;

WHILE @finalFieldsN <= @requiredLevels
BEGIN
    SET @finalFieldsSQL = @finalFieldsSQL + ', Weight' + CHAR(64 + @finalFieldsN) + ', Price' + CHAR(64 + @finalFieldsN) + ', DestinationCode' + CHAR(64 + @finalFieldsN)
    SET @finalFieldsN = @finalFieldsN + 1
END

-- Build a dynamic statement for the subquery SELECT fields

DECLARE
    @subqueryFieldsSQL varchar(1000) = ''
    , @subqueryFieldsN int = 1
;

WHILE @subqueryFieldsN <= @requiredLevels
BEGIN
    SET @subqueryFieldsSQL = @subqueryFieldsSQL + ', MAX([' + CAST(@subqueryFieldsN AS varchar) + ']) ColumnName' + CHAR(64 + @subqueryFieldsN)
    SET @subqueryFieldsN = @subqueryFieldsN + 1
END

-- Build a dynamic statement for the PIVOT fields

DECLARE
    @pivotFieldsSQL varchar(1000) = ''
    , @pivotFieldsN int = 1
;

WHILE @pivotFieldsN <= @requiredLevels
BEGIN
    SET @pivotFieldsSQL = @pivotFieldsSQL + ', [' + CAST(@pivotFieldsN AS varchar) + ']'
    SET @pivotFieldsN = @pivotFieldsN + 1
END

SET @pivotFieldsSQL = SUBSTRING(@pivotFieldsSQL, 3, LEN(@pivotFieldsSQL) - 2)

-- Build the final SQL statement and execute

DECLARE @SQL varchar(8000) =
    '
        SELECT
            B.BatchID, B.Name, B.CustomerID, B.DateCreated, [Status]' + @finalFieldsSQL + '
        FROM
            BATCH B
            LEFT JOIN
                (
                    SELECT
                        BatchID' + REPLACE(@subqueryFieldsSQL, 'ColumnName', 'Weight') + '
                    FROM
                        (
                            SELECT BD.BatchID, [Weight], ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
                            FROM
                                BATCH B
                                JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
                        ) Q
                        PIVOT
                        (
                            MAX([Weight])
                            FOR R IN (' + @pivotFieldsSQL + ')
                        ) P
                    GROUP BY BatchID
                ) W
            ON B.BatchID = W.BatchID
            LEFT JOIN
                (
                    SELECT
                        BatchID' + REPLACE(@subqueryFieldsSQL, 'ColumnName', 'Price') + '
                    FROM
                        (
                            SELECT BD.BatchID, Price, ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
                            FROM
                                BATCH B
                                JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
                        ) Q
                        PIVOT
                        (
                            MAX(Price)
                            FOR R IN (' + @pivotFieldsSQL + ')
                        ) P
                    GROUP BY BatchID
                ) P
            ON B.BatchID = P.BatchID
            LEFT JOIN
                (
                    SELECT
                        BatchID' + REPLACE(@subqueryFieldsSQL, 'ColumnName', 'DestinationCode') + '
                    FROM
                        (
                            SELECT BD.BatchID, DestinationCode, ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
                            FROM
                                BATCH B
                                JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
                        ) Q
                        PIVOT
                        (
                            MAX(DestinationCode)
                            FOR R IN (' + @pivotFieldsSQL + ')
                        ) P
                    GROUP BY BatchID
                ) D
            ON B.BatchID = D.BatchID
    '

EXEC (@SQL)
</code>```

If you don't want to show empty records, replace LEFT JOIN with JOIN in the final statement (3 occurences).

Body:
I have the following tables

BATCH

BatchID     Name      CustomerID  DateCreated  Status
12           A         1           01/01/2013   Active
13           B         12          01/01/2013   Inactive
14           C         245         01/01/2013   Complete

BATCHDETAIL

BatchDetailID  BatchID  Weight  Price    DestinationCode
1              12       55      500.00   99
2              12       119     1500.00  55
3              13       12      133      1212

A batch record can have many batch detail records linked via the FK BatchDetail.BatchID

I want to write a query to select a single row back to the user which combines the information in the BATCH record and the Weight,Price and DestinationCode from both BATCHDETAIL records for BatchID = 12

So the output would be :

BatchID      Name      CustomerID  DateCreated  Status  WeightA PriceA  DestinationCodeA  WeightB  PriceB   DestinationCodeB
12           A         1           01/01/2013   Active  55      500.00  99                119       1500      55

So you can see I want to have 1 row with all information combined in the one row  and differentiate each detail record with A or B ( Lets assume a maximum of 2 detail records is only allowed )

I have thought of creating a table with these fields and then building up the information in a series of select statements and finally doing a select on the temp table but getting the query into a single block of SQL would be ideal.

Body:
Here is a solution using dynamic SQL:

-- Get the MAX total number of records per BatchID (how many sets of columns do we need?)

DECLARE @requiredLevels int = (SELECT MAX(C) FROM (SELECT COUNT(*) C FROM BATCHDETAIL GROUP BY BatchID) Q)
;

-- Build a dynamic statement for the final SELECT fields

DECLARE
    @finalFieldsSQL varchar(1000) = ''
    , @finalFieldsN int = 1
;

WHILE @finalFieldsN <= @requiredLevels
BEGIN
    SET @finalFieldsSQL = @finalFieldsSQL + ', Weight' + CHAR(64 + @finalFieldsN) + ', Price' + CHAR(64 + @finalFieldsN) + ', DestinationCode' + CHAR(64 + @finalFieldsN)
    SET @finalFieldsN = @finalFieldsN + 1
END

-- Build a dynamic statement for the subquery SELECT fields

DECLARE
    @subqueryFieldsSQL varchar(1000) = ''
    , @subqueryFieldsN int = 1
;

WHILE @subqueryFieldsN <= @requiredLevels
BEGIN
    SET @subqueryFieldsSQL = @subqueryFieldsSQL + ', MAX([' + CAST(@subqueryFieldsN AS varchar) + ']) ColumnName' + CHAR(64 + @subqueryFieldsN)
    SET @subqueryFieldsN = @subqueryFieldsN + 1
END

-- Build a dynamic statement for the PIVOT fields

DECLARE
    @pivotFieldsSQL varchar(1000) = ''
    , @pivotFieldsN int = 1
;

WHILE @pivotFieldsN <= @requiredLevels
BEGIN
    SET @pivotFieldsSQL = @pivotFieldsSQL + ', [' + CAST(@pivotFieldsN AS varchar) + ']'
    SET @pivotFieldsN = @pivotFieldsN + 1
END

SET @pivotFieldsSQL = SUBSTRING(@pivotFieldsSQL, 3, LEN(@pivotFieldsSQL) - 2)

-- Build the final SQL statement and execute

DECLARE @SQL varchar(8000) =
    '
        SELECT
            B.BatchID, B.Name, B.CustomerID, B.DateCreated, [Status]' + @finalFieldsSQL + '
        FROM
            BATCH B
            LEFT JOIN
                (
                    SELECT
                        BatchID' + REPLACE(@subqueryFieldsSQL, 'ColumnName', 'Weight') + '
                    FROM
                        (
                            SELECT BD.BatchID, [Weight], ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
                            FROM
                                BATCH B
                                JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
                        ) Q
                        PIVOT
                        (
                            MAX([Weight])
                            FOR R IN (' + @pivotFieldsSQL + ')
                        ) P
                    GROUP BY BatchID
                ) W
            ON B.BatchID = W.BatchID
            LEFT JOIN
                (
                    SELECT
                        BatchID' + REPLACE(@subqueryFieldsSQL, 'ColumnName', 'Price') + '
                    FROM
                        (
                            SELECT BD.BatchID, Price, ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
                            FROM
                                BATCH B
                                JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
                        ) Q
                        PIVOT
                        (
                            MAX(Price)
                            FOR R IN (' + @pivotFieldsSQL + ')
                        ) P
                    GROUP BY BatchID
                ) P
            ON B.BatchID = P.BatchID
            LEFT JOIN
                (
                    SELECT
                        BatchID' + REPLACE(@subqueryFieldsSQL, 'ColumnName', 'DestinationCode') + '
                    FROM
                        (
                            SELECT BD.BatchID, DestinationCode, ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
                            FROM
                                BATCH B
                                JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
                        ) Q
                        PIVOT
                        (
                            MAX(DestinationCode)
                            FOR R IN (' + @pivotFieldsSQL + ')
                        ) P
                    GROUP BY BatchID
                ) D
            ON B.BatchID = D.BatchID
    '

EXEC (@SQL)

If you don't want to show empty records, replace LEFT JOIN with JOIN in the final statement (3 occurences).


问:
Java JPA/Hibernate: How to avoid multiple instances of an entity in a session?
I realize JPA doesn't work as I expected, as I often end up with multiple instance of a single entity in a session.

Here's the study case: A parent has a collection of child mapped with @OneToMany

In a single method:

get an instance of the Parent P
entity

load the collection of child with P.getChilds(): it contains an instance of C1 and C2

then find a specific Child with an optimized JPA query having the Parent P has a parameter: Child C = dao.getSpecificChild(P)

Here I would expect C to be one of the two instances already loaded (of C1 or C2). I thought JPA would check the already existing instance in its current session.
But JPA will load a new instance of C (whether it is C1 or C2 doesn't matter here).

So that I end up with two different instances of C.

My question is: is this the expected behavior?
If it is, how can I reconcile my entity instances in a session?

cheers

答:
how can I
  reconcile my entity instances in a
  session?

If you want to transfer state from entity a to entity b, you can do the following:

```<code>entityManager.merge(a);
entityManager.refresh(b);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
how can I
  reconcile my entity instances in a
  session?

If you want to transfer state from entity a to entity b, you can do the following:

entityManager.merge(a);
entityManager.refresh(b);


问:
Python: replace a string in a CSV file
I am a beginner and I have an issue with a short code. I want to replace a string from a csv to with another string, and put out a new
csv with an new name. The strings are separated with commas.

My code is a catastrophe:

```<code>import csv

f = open('C:\\User\\Desktop\\Replace_Test\\Testreplace.csv')
csv_f = csv.reader(f)

g = open('C:\\Users\\Desktop\\Replace_Test\\Testreplace.csv')
csv_g = csv.writer(g)

findlist = ['The String, that should replaced']
replacelist = ['The string that should replace the old striong']

#the function  ?:
def findReplace(find,replace):
s = f.read()
for item, replacement in zip(findlist,replacelist):
s = s.replace(item,replacement)
g.write(s)

for row in csv_f:
print(row)

f.close()
g.close()
</code>```

答:
You can do this with the regex package re. Also, if you use with you don't have to remember to close your files, which helps me.

EDIT: Keep in mind that this matches the exact string, meaning it's also case-sensitive. If you don't want that then you probably need to use an actual regex to find the strings that need replacing. You would do this by replacing find_str in the re.sub() call with r'your_regex_here'.

```<code>import re

# open your csv and read as a text string
with open(my_csv_path, 'r') as f:
    my_csv_text = f.read()

find_str = 'The String, that should replaced'
replace_str = 'The string that should replace the old striong'

# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)

# open new file and save
new_csv_path = './my_new_csv.csv' # or whatever path and name you want
with open(new_csv_path, 'w') as f:
    f.write(new_csv_str)
</code>```

Title: Python: replace a string in a CSV file

Body:
I am a beginner and I have an issue with a short code. I want to replace a string from a csv to with another string, and put out a new
csv with an new name. The strings are separated with commas.

My code is a catastrophe:

import csv

f = open('C:\\User\\Desktop\\Replace_Test\\Testreplace.csv')
csv_f = csv.reader(f)

g = open('C:\\Users\\Desktop\\Replace_Test\\Testreplace.csv')
csv_g = csv.writer(g)

findlist = ['The String, that should replaced']
replacelist = ['The string that should replace the old striong']

#the function  ?:
def findReplace(find,replace):
s = f.read()
for item, replacement in zip(findlist,replacelist):
s = s.replace(item,replacement)
g.write(s)

for row in csv_f:
print(row)

f.close()
g.close()

Body:
You can do this with the regex package re. Also, if you use with you don't have to remember to close your files, which helps me.

EDIT: Keep in mind that this matches the exact string, meaning it's also case-sensitive. If you don't want that then you probably need to use an actual regex to find the strings that need replacing. You would do this by replacing find_str in the re.sub() call with r'your_regex_here'.

import re

# open your csv and read as a text string
with open(my_csv_path, 'r') as f:
    my_csv_text = f.read()

find_str = 'The String, that should replaced'
replace_str = 'The string that should replace the old striong'

# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)

# open new file and save
new_csv_path = './my_new_csv.csv' # or whatever path and name you want
with open(new_csv_path, 'w') as f:
    f.write(new_csv_str)


答:
you can use Pivot and UnPivot to achieve this result. Try Something like this:

```<code>SELECT
BatchID,[Name],[CustomerID],[DateCreated],[Status],
MAX(Weight1) as WeightA,
MAX(Price1) as PriceA,
MAX(DestinationCode1) as DestinationCodeA,
MAX(Weight2) as WeightB,
MAX(Price2) as PriceB,
MAX(DestinationCode2) as DestinationCodeB

FROM (

        SELECT *,COL + CAST(DENSE_RANK() OVER (PARTITION BY Batchid ORDER BY BatchDetailID ASC) AS VARCHAR) AS BATCHPIVOT
        FROM
        (
          SELECT  b.*,cast(d.Weight as varchar(255)) as Weight, cast(d.Price as varchar(255)) as Price, cast(d.DestinationCode as varchar(255)) as DestinationCode,d.BatchDetailID
        FROM #Batch B
        INNER JOIN #BATCHDETAIL D on b.BatchID = d.BatchID
        ) AS cp
        UNPIVOT
        (
          Val FOR Col IN ([Weight], [Price], [DestinationCode])
        ) AS up
) AS query

PIVOT (MAX(Val)
      FOR BATCHPIVOT IN (Weight1,Price1,DestinationCode1, Weight2, Price2, DestinationCode2)) AS Pivot1
GROUP BY BatchID,[Name],[CustomerID],[DateCreated],[Status]
</code>```

This is just standard query. you can make this script Dynamic according to your liking:

Complete Script:

```<code>Create table #Batch
(BatchID int,
[Name] char(1),
[CustomerID] int,
[DateCreated] date,
[Status] varchar(50)
)

Create table #BATCHDETAIL
(BatchDetailID int,
BatchID int,
[Weight] int,
Price money,
DestinationCode int
)

INSERT INTO #Batch
VALUES(12,'A',1,'01/01/2013','Active')
,(13,'B',12,'01/01/2013','Inactive')
,(14,'C',245,'01/01/2013','Complete')

INSERT INTO #BATCHDETAIL
VALUES(1,12,55,500.00,99)
,(2,12,119,1500.00,55)
,(3,13,12,133,1212)

SELECT
BatchID,[Name],[CustomerID],[DateCreated],[Status],
MAX(Weight1) as WeightA,
MAX(Price1) as PriceA,
MAX(DestinationCode1) as DestinationCodeA,
MAX(Weight2) as WeightB,
MAX(Price2) as PriceB,
MAX(DestinationCode2) as DestinationCodeB

FROM (

        SELECT *,COL + CAST(DENSE_RANK() OVER (PARTITION BY Batchid ORDER BY BatchDetailID ASC) AS VARCHAR) AS BATCHPIVOT
        FROM
        (
          SELECT  b.*,cast(d.Weight as varchar(255)) as Weight, cast(d.Price as varchar(255)) as Price, cast(d.DestinationCode as varchar(255)) as DestinationCode,d.BatchDetailID
        FROM #Batch B
        INNER JOIN #BATCHDETAIL D on b.BatchID = d.BatchID
        ) AS cp
        UNPIVOT
        (
          Val FOR Col IN ([Weight], [Price], [DestinationCode])
        ) AS up
) AS query

PIVOT (MAX(Val)
      FOR BATCHPIVOT IN (Weight1,Price1,DestinationCode1, Weight2, Price2, DestinationCode2)) AS Pivot1
GROUP BY BatchID,[Name],[CustomerID],[DateCreated],[Status]
</code>```

Title: Embed child records into single row with parent information

Body:
you can use Pivot and UnPivot to achieve this result. Try Something like this:

SELECT
BatchID,[Name],[CustomerID],[DateCreated],[Status],
MAX(Weight1) as WeightA,
MAX(Price1) as PriceA,
MAX(DestinationCode1) as DestinationCodeA,
MAX(Weight2) as WeightB,
MAX(Price2) as PriceB,
MAX(DestinationCode2) as DestinationCodeB

FROM (

        SELECT *,COL + CAST(DENSE_RANK() OVER (PARTITION BY Batchid ORDER BY BatchDetailID ASC) AS VARCHAR) AS BATCHPIVOT
        FROM
        (
          SELECT  b.*,cast(d.Weight as varchar(255)) as Weight, cast(d.Price as varchar(255)) as Price, cast(d.DestinationCode as varchar(255)) as DestinationCode,d.BatchDetailID
        FROM #Batch B
        INNER JOIN #BATCHDETAIL D on b.BatchID = d.BatchID
        ) AS cp
        UNPIVOT
        (
          Val FOR Col IN ([Weight], [Price], [DestinationCode])
        ) AS up
) AS query

PIVOT (MAX(Val)
      FOR BATCHPIVOT IN (Weight1,Price1,DestinationCode1, Weight2, Price2, DestinationCode2)) AS Pivot1
GROUP BY BatchID,[Name],[CustomerID],[DateCreated],[Status]

This is just standard query. you can make this script Dynamic according to your liking:

Complete Script:

Create table #Batch
(BatchID int,
[Name] char(1),
[CustomerID] int,
[DateCreated] date,
[Status] varchar(50)
)

Create table #BATCHDETAIL
(BatchDetailID int,
BatchID int,
[Weight] int,
Price money,
DestinationCode int
)

INSERT INTO #Batch
VALUES(12,'A',1,'01/01/2013','Active')
,(13,'B',12,'01/01/2013','Inactive')
,(14,'C',245,'01/01/2013','Complete')

INSERT INTO #BATCHDETAIL
VALUES(1,12,55,500.00,99)
,(2,12,119,1500.00,55)
,(3,13,12,133,1212)

SELECT
BatchID,[Name],[CustomerID],[DateCreated],[Status],
MAX(Weight1) as WeightA,
MAX(Price1) as PriceA,
MAX(DestinationCode1) as DestinationCodeA,
MAX(Weight2) as WeightB,
MAX(Price2) as PriceB,
MAX(DestinationCode2) as DestinationCodeB

FROM (

        SELECT *,COL + CAST(DENSE_RANK() OVER (PARTITION BY Batchid ORDER BY BatchDetailID ASC) AS VARCHAR) AS BATCHPIVOT
        FROM
        (
          SELECT  b.*,cast(d.Weight as varchar(255)) as Weight, cast(d.Price as varchar(255)) as Price, cast(d.DestinationCode as varchar(255)) as DestinationCode,d.BatchDetailID
        FROM #Batch B
        INNER JOIN #BATCHDETAIL D on b.BatchID = d.BatchID
        ) AS cp
        UNPIVOT
        (
          Val FOR Col IN ([Weight], [Price], [DestinationCode])
        ) AS up
) AS query

PIVOT (MAX(Val)
      FOR BATCHPIVOT IN (Weight1,Price1,DestinationCode1, Weight2, Price2, DestinationCode2)) AS Pivot1
GROUP BY BatchID,[Name],[CustomerID],[DateCreated],[Status]


问:
How can I be sure a constructor function only runs once?
Is there any way for this code in the constructor of my service TranslatorService is calling just one time for all application or on demande, and not all time homecomponent is load ????

```<code>this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })
</code>```

translation class for my translate retrive from firestore ex:

```<code>{
  "WELCOME": {
   "FR": "bienvenue",
   "GB": "Welcome"
 }
}

export interface Translation {
    [code: string]: TranslationInfo;

}

export interface TranslationInfo {
    [language: string]: string;
}
</code>```

my core module

```<code>import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { TranslatorService } from '../services/translator.service';
@NgModule({
imports: [
    AngularFireAuthModule,
    AngularFirestoreModule
],
providers: [AuthService, TranslatorService]
})
export class CoreModule { }
</code>```

injected in appmodule

```<code>@NgModule({
declarations: [
...

],
imports: [
...
    CoreModule,
...
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

my translator service

```<code>    @Injectable()
export class TranslatorService {

  translationsCollection: AngularFirestoreCollection<Translation>;
  translations$: Observable<any>;
  public translations: Translation[];

  constructor(private afs: AngularFirestore) {
    var translationsCollection = this.afs.collection("translations");
    this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })
    });
</code>```

my component

```<code>    export class HomeComponent implements OnInit {
translations$: Observable<any>;
constructor(private translator: TranslatorService) { }

ngOnInit() {
    this.translations$ = this.translator.translations$;
}
</code>```

my component view

```<code><div *ngFor="let translation of translations$|async">
```{{translation | json}}```
</div>
</code>```

答:
Just use a singleton pattern: move the code to a static function and store its result in a static field.  The constructor just calls the static function which will check the field before running its code:</p>

```<code>export class TranslatorService {

  translationsCollection: AngularFirestoreCollection<Translation>;
  translations$: Observable<any>;

  static tCollection : AngularFirestoreCollection<Translation>;
  static t$: Observable<any>;
  static initialize(afs: AngularFireStore) : void {
    if (TranslatorService.tCollection == null) {
      TranslatorService.tCollection = afs.collection("translations");
      TranslatorService.t$ = TranslatorService.tCollection.snapshotChanges().map(actions => actions.map(a => ...));
    }
  }

  public translations: Translation[];

  constructor(private afs: AngularFirestore) {
    TranslatorService.initialize(this.afs);
    this.translations$ = TranslatorService.t$;
    this.translationsCollection = TranslatorService.tCollection;
  }
}
</code>```

Body:
Is there any way for this code in the constructor of my service TranslatorService is calling just one time for all application or on demande, and not all time homecomponent is load ????

this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })

translation class for my translate retrive from firestore ex:

{
  "WELCOME": {
   "FR": "bienvenue",
   "GB": "Welcome"
 }
}

export interface Translation {
    [code: string]: TranslationInfo;

}

export interface TranslationInfo {
    [language: string]: string;
}

my core module

import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { TranslatorService } from '../services/translator.service';
@NgModule({
imports: [
    AngularFireAuthModule,
    AngularFirestoreModule
],
providers: [AuthService, TranslatorService]
})
export class CoreModule { }

injected in appmodule

@NgModule({
declarations: [
...

],
imports: [
...
    CoreModule,
...
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }

my translator service

    @Injectable()
export class TranslatorService {

  translationsCollection: AngularFirestoreCollection<Translation>;
  translations$: Observable<any>;
  public translations: Translation[];

  constructor(private afs: AngularFirestore) {
    var translationsCollection = this.afs.collection("translations");
    this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })
    });

my component

    export class HomeComponent implements OnInit {
translations$: Observable<any>;
constructor(private translator: TranslatorService) { }

ngOnInit() {
    this.translations$ = this.translator.translations$;
}

my component view

{{translation | json}}

Body:
Just use a singleton pattern: move the code to a static function and store its result in a static field.  The constructor just calls the static function which will check the field before running its code:

export class TranslatorService {

  translationsCollection: AngularFirestoreCollection<Translation>;
  translations$: Observable<any>;

  static tCollection : AngularFirestoreCollection<Translation>;
  static t$: Observable<any>;
  static initialize(afs: AngularFireStore) : void {
    if (TranslatorService.tCollection == null) {
      TranslatorService.tCollection = afs.collection("translations");
      TranslatorService.t$ = TranslatorService.tCollection.snapshotChanges().map(actions => actions.map(a => ...));
    }
  }

  public translations: Translation[];

  constructor(private afs: AngularFirestore) {
    TranslatorService.initialize(this.afs);
    this.translations$ = TranslatorService.t$;
    this.translationsCollection = TranslatorService.tCollection;
  }
}


问:
Check if an input form is filled in, in a Adaptive Card
You can use input forms in an Adaptive card.
But how can i check if the fields are filled in without going further to the next dialog. So after i clicked a submit button, it should check if the fields are filled in.

Code: nodejs

Example: http://adaptivecards.io/samples/InputForm.html

答:
Adaptive Cards do not have client-side validation so you would have to retrieve the values from your bot service and verify on the server. If the fields are not filed in as you expect then you can send a response back to the user with what they should fill in. Take a look at this bot to see an example, go through a few of the steps in the dialog and when prompted for an input, send a blank response, and the bot will respond with a friendly message asking you to fill in the field(s).

http://contososcubabot.azurewebsites.net/

Source code: https://github.com/matthidinger/ContosoScubaBot


问:
Symfony 2 Entity Repository find() returns empty array
Thank you all for your answers from now. Thatś the question. I have a symfony 2 app with two entities (Tasks and Products). When i tried to find (findBy,findOneBy,findAll) a product it returns an empty array.

Tasks Entity

```<code>    <?php

namespace pablo\UserBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Task
 *
 * @ORM\Table(name="tasks")
 * @ORM\Entity(repositoryClass="pablo\UserBundle\Repository\TaskRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Task
{
    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="tasks")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $user;

    /**
     * @ORM\ManyToOne(targetEntity="Product", inversedBy="task")
     *  @ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $product;

public function __construct()
    {
        $this->tasks = new ArrayCollection();
    }

/**
     * Set product
     *
     * @param \pablo\UserBundle\Entity\Product $product
     *
     * @return Task
     */
    public function setProduct(\pablo\UserBundle\Entity\Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \pablo\UserBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }

    /**
     * @return ArrayCollection
     */
    public function getTasks()
    {
        return $this->tasks;
    }

    /**
     * @param ArrayCollection $tasks
     */
    public function setTasks($tasks)
    {
        $this->tasks = $tasks;
    }
</code>```

And Products Entity

```<code><?php

namespace pablo\UserBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * Products
 *
 * @ORM\Table(name="products")
 * @ORM\Entity(repositoryClass="pablo\UserBundle\Repository\ProductsRepository")
 * @UniqueEntity("productsName")
 */
class Product
{

    /**
     * @ORM\OneToMany(targetEntity="Task", mappedBy="product")
     */
    protected $task;

    /**
     * @ORM\OneToMany(targetEntity="Publicaciones", mappedBy="product")
     */
    protected $publicaciones;

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="products_name", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $productsName;

    public function __construct()
    {
        $this->task = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set productsName
     *
     * @param string $productsName
     *
     * @return Product
     */
    public function setProductsName($productsName)
    {
        $this->productsName = $productsName;

        return $this;
    }

    /**
     * Get productsName
     *
     * @return string
     */
    public function getProductsName()
    {
        return $this->productsName;
    }

    public function __toString() {
        return $this->productsName;
    }

    /**
     * Get task
     *
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function getTask()
    {
        return $this->task;
    }

    /**
     * Set task
     *
     * @param \Doctrine\Common\Collections\ArrayCollection $typeSponsor
     *
     * @return Task
     */
    public function setTask($task)
    {
        $this->task = $task;
    }

    /**
     * @return mixed
     */
    public function getPublicaciones()
    {
        return $this->publicaciones;
    }

    /**
     * @param mixed $publicaciones
     */
    public function setPublicaciones($publicaciones)
    {
        $this->publicaciones = $publicaciones;
    }

}
</code>```

Now, when i tried to find a product from controller it returns an empty array ({}). I can't see what is wrong with this.

```<code>$productId = '18';
$product = $this->get('doctrine.orm.default_entity_manager')->getRepository('pabloUserBundle:Product')->find($productId);
</code>```

答:
Actually you have a result, it just is an empty object because you have not defined which of the properties should be printed.

The best solution is for your entity to implement JsonSerializable.

```<code>class Product  implements \JsonSerializable
{
...
public function jsonSerialize()
{
    return [
        "id"=> $this->getId(),
        "name" => $this->getProductsName()
    ];
}
</code>```

Now it knows what it should print when converting the class to json object.

If you want the task collection also, implement JsonSerializable for the Task Entity and add in Product Entity:

```<code> public function jsonSerialize()
{
    return [
        "id"=> $this->getId(),
        "name" => $this->getProductsName(),
        "task" => $this->getTask()->toArray()
    ];
}
</code>```

The JsonSerializable interface

Body:
Thank you all for your answers from now. Thatś the question. I have a symfony 2 app with two entities (Tasks and Products). When i tried to find (findBy,findOneBy,findAll) a product it returns an empty array.

Tasks Entity

    <?php

namespace pablo\UserBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Task
 *
 * @ORM\Table(name="tasks")
 * @ORM\Entity(repositoryClass="pablo\UserBundle\Repository\TaskRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Task
{
    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="tasks")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $user;

    /**
     * @ORM\ManyToOne(targetEntity="Product", inversedBy="task")
     *  @ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $product;

public function __construct()
    {
        $this->tasks = new ArrayCollection();
    }

/**
     * Set product
     *
     * @param \pablo\UserBundle\Entity\Product $product
     *
     * @return Task
     */
    public function setProduct(\pablo\UserBundle\Entity\Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \pablo\UserBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }

    /**
     * @return ArrayCollection
     */
    public function getTasks()
    {
        return $this->tasks;
    }

    /**
     * @param ArrayCollection $tasks
     */
    public function setTasks($tasks)
    {
        $this->tasks = $tasks;
    }

And Products Entity

<?php

namespace pablo\UserBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * Products
 *
 * @ORM\Table(name="products")
 * @ORM\Entity(repositoryClass="pablo\UserBundle\Repository\ProductsRepository")
 * @UniqueEntity("productsName")
 */
class Product
{

    /**
     * @ORM\OneToMany(targetEntity="Task", mappedBy="product")
     */
    protected $task;

    /**
     * @ORM\OneToMany(targetEntity="Publicaciones", mappedBy="product")
     */
    protected $publicaciones;

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="products_name", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $productsName;

    public function __construct()
    {
        $this->task = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set productsName
     *
     * @param string $productsName
     *
     * @return Product
     */
    public function setProductsName($productsName)
    {
        $this->productsName = $productsName;

        return $this;
    }

    /**
     * Get productsName
     *
     * @return string
     */
    public function getProductsName()
    {
        return $this->productsName;
    }

    public function __toString() {
        return $this->productsName;
    }

    /**
     * Get task
     *
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function getTask()
    {
        return $this->task;
    }

    /**
     * Set task
     *
     * @param \Doctrine\Common\Collections\ArrayCollection $typeSponsor
     *
     * @return Task
     */
    public function setTask($task)
    {
        $this->task = $task;
    }

    /**
     * @return mixed
     */
    public function getPublicaciones()
    {
        return $this->publicaciones;
    }

    /**
     * @param mixed $publicaciones
     */
    public function setPublicaciones($publicaciones)
    {
        $this->publicaciones = $publicaciones;
    }

}

Now, when i tried to find a product from controller it returns an empty array ({}). I can't see what is wrong with this.

$productId = '18';
$product = $this->get('doctrine.orm.default_entity_manager')->getRepository('pabloUserBundle:Product')->find($productId);

Body:
Actually you have a result, it just is an empty object because you have not defined which of the properties should be printed.

The best solution is for your entity to implement JsonSerializable.

class Product  implements \JsonSerializable
{
...
public function jsonSerialize()
{
    return [
        "id"=> $this->getId(),
        "name" => $this->getProductsName()
    ];
}

Now it knows what it should print when converting the class to json object.

If you want the task collection also, implement JsonSerializable for the Task Entity and add in Product Entity:

 public function jsonSerialize()
{
    return [
        "id"=> $this->getId(),
        "name" => $this->getProductsName(),
        "task" => $this->getTask()->toArray()
    ];
}

The JsonSerializable interface

ContentLicense: CC BY-SA 4.0


问:
Git: Set up a fetch-only remote?
When I run git remote -v in one of my Git repositories that has a remote(s) configured, I see that each remote has both fetch and push specs:

```<code>$ git remote -v
<remote-name> ssh://host/path/to/repo (fetch)
<remote-name> ssh://host/path/to/repo (push)
</code>```

For remotes that point to peer developers there's no need to push, and Git will refuse to push to a non-bare repository anyway. Is there any way to configure these remotes as "fetch-only" with no push address or capabilities?

答:
Apart from changing the push URL to something invalid (e.g., git remote set-url --push origin DISABLED), one can also use the pre-push hook.

One quick way to stop git push is to symlink /usr/bin/false to be the hook:

```<code>$ ln -s /usr/bin/false .git/hooks/pre-push
$ git push
error: failed to push some refs to '...'
</code>```

Using a hook allows for more fine-grained control of pushes if desirable. See .git/hooks/pre-push.sample for an example of how to prevent pushing work-in-progress commits.

To prevent pushing to a specific branch or to limit pushing to a single branch, this in an example hook:

$ cat .git/hooks/pre-push
#!/usr/bin/sh

# An example hook script to limit pushing to a single remote.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If this script exits with a non-zero status nothing will be pushed.

remote="$1"
url="$2"

[[ "$remote" == "origin" ]]
```

<p>A test repo with multiple remotes:</p>

```$ git remote -v
origin  ../gitorigin (fetch)
origin  ../gitorigin (push)
upstream        ../gitupstream (fetch)
upstream        ../gitupstream (push)
```

<p>Pushing to <code>origin</code> is allowed:</p>

```$ git push origin
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 222 bytes | 222.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To ../gitorigin
 * [new branch]      master -> master
```

<p>Pushing to any other remote is not allowed:</p>

```$ git push upstream
error: failed to push some refs to '../gitupstream'
```

Note that the pre-push hook script can be modified to, among other things, print a message to stderr saying the push has been disabled.

Title: Git: Set up a fetch-only remote?

Body:
When I run git remote -v in one of my Git repositories that has a remote(s) configured, I see that each remote has both fetch and push specs:

$ git remote -v
<remote-name> ssh://host/path/to/repo (fetch)
<remote-name> ssh://host/path/to/repo (push)

For remotes that point to peer developers there's no need to push, and Git will refuse to push to a non-bare repository anyway. Is there any way to configure these remotes as "fetch-only" with no push address or capabilities?

Body:
Apart from changing the push URL to something invalid (e.g., git remote set-url --push origin DISABLED), one can also use the pre-push hook.

One quick way to stop git push is to symlink /usr/bin/false to be the hook:

$ ln -s /usr/bin/false .git/hooks/pre-push
$ git push
error: failed to push some refs to '...'

Using a hook allows for more fine-grained control of pushes if desirable. See .git/hooks/pre-push.sample for an example of how to prevent pushing work-in-progress commits.

To prevent pushing to a specific branch or to limit pushing to a single branch, this in an example hook:

$ cat .git/hooks/pre-push
#!/usr/bin/sh

# An example hook script to limit pushing to a single remote.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If this script exits with a non-zero status nothing will be pushed.

remote="$1"
url="$2"

[[ "$remote" == "origin" ]]

A test repo with multiple remotes:

$ git remote -v
origin  ../gitorigin (fetch)
origin  ../gitorigin (push)
upstream        ../gitupstream (fetch)
upstream        ../gitupstream (push)

Pushing to origin is allowed:

$ git push origin
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 222 bytes | 222.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To ../gitorigin
 * [new branch]      master -> master

Pushing to any other remote is not allowed:

$ git push upstream
error: failed to push some refs to '../gitupstream'

Note that the pre-push hook script can be modified to, among other things, print a message to stderr saying the push has been disabled.


问:
Clear all fields in ASP.net form
Is there an easy way to reset all the fields in a form?

I have around 100 controls in my asp.net form and there are submit and reset buttons.

How do I make all values in the fields null when user hits reset button?

I have a lot of dropdown boxes, textboxes, checkboxes.

答:
Or if you are using Angular.

Add this to your button on the cshtml page:

```<code><input type="button" value="Cancel" id="cancel" ng-click="cancel();" />
</code>```

And this to your .js file:

```<code>$scope.cancel = function () {
    if (!$('form').dirtyForms('isDirty')) {
        $('form').dirtyForms('setClean');
    }
    else {
        $('form').dirtyForms('isDirty', true);
    }
     var that = this;
    var method = that.getUrl('CONTROLLER', 'ACTION', 'id', 'querystring');
    window.location = method;
</code>```

Title: Clear all fields in ASP.net form

Body:
Or if you are using Angular.

Add this to your button on the cshtml page:

<input type="button" value="Cancel" id="cancel" ng-click="cancel();" />

And this to your .js file:

$scope.cancel = function () {
    if (!$('form').dirtyForms('isDirty')) {
        $('form').dirtyForms('setClean');
    }
    else {
        $('form').dirtyForms('isDirty', true);
    }
     var that = this;
    var method = that.getUrl('CONTROLLER', 'ACTION', 'id', 'querystring');
    window.location = method;


问:
how to call actionmailer in rails admin controller?
I want to send a email to user after create something via rails admin.

I know I can call it in model callback but it's not considered as a good pratices

the best way is to put the actionmailer action after model save in the controller but I don't know how to do it in rails_admin controller

```<code>class UsersController < ApplicationController
  # POST /users
  # POST /users.json
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        # Tell the UserMailer to send a welcome email after save
        UserMailer.welcome_email(@user).deliver_later

        format.html { redirect_to(@user, notice: 'User was successfully created.') }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end
</code>```

答:
What you want to do is not easy on rails admin because you cannot modify the controllers nor do you have access to them without monkey patching them.

I actually made a fork of rails admin for this functionality checkout the commit with the changes:
https://github.com/aliada-mx/rails_admin/commit/6251554efd1d83cdb418f42683ee55a4e27c2474
Just touched two files

And example usage

```<code>class User
   after_save :on_admin_updates
   attr_accessor :edited_in_rails_admin

   def on_admin_updates
      return unless edited_in_rails_admin
      self.edited_in_rails_admin = false

     UserMailer.welcome_email(self.id)
  end
end
</code>```

A bit clunky i know, PR´s welcome.

Body:
I want to send a email to user after create something via rails admin.

I know I can call it in model callback but it's not considered as a good pratices

the best way is to put the actionmailer action after model save in the controller but I don't know how to do it in rails_admin controller

class UsersController < ApplicationController
  # POST /users
  # POST /users.json
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        # Tell the UserMailer to send a welcome email after save
        UserMailer.welcome_email(@user).deliver_later

        format.html { redirect_to(@user, notice: 'User was successfully created.') }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end

Body:
What you want to do is not easy on rails admin because you cannot modify the controllers nor do you have access to them without monkey patching them.

I actually made a fork of rails admin for this functionality checkout the commit with the changes:
https://github.com/aliada-mx/rails_admin/commit/6251554efd1d83cdb418f42683ee55a4e27c2474
Just touched two files

And example usage

class User
   after_save :on_admin_updates
   attr_accessor :edited_in_rails_admin

   def on_admin_updates
      return unless edited_in_rails_admin
      self.edited_in_rails_admin = false

     UserMailer.welcome_email(self.id)
  end
end

A bit clunky i know, PR´s welcome.


问:
How can I set a domain on one of my functions on a graph?
I've got a code that plots a graph of two functions on Python. I was just wondering that if there was a way to have my x function only on the domain between 0 and 0.8 so it wouldn't carry on after the intersection with h-but I still want h to carry on. Is there any way I can modify this? Thanks. This is my code:

```<code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib.legend_handler import HandlerLine2D

t = np.arange(0.0, 1.0, 0.001)
h = 0.1*np.sin(10*t)
x = 4*t-5*t**2

line1, = plt.plot(t, h, label='h(t)')
line2, = plt.plot(t, x, label='x(t)', linestyle='--')

plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})

plt.xlabel('time')
plt.ylabel('height')
plt.title('Fig 1.')
plt.grid(False)
plt.savefig("Plot.png")
plt.show()
</code>```

This is how it looks:

答:
Simply slice the two arrays:</p>

```<code>line2, = plt.plot(t[t<0.8], x[t<0.8], label='x(t)', linestyle='--')
</code>```

Body:
I've got a code that plots a graph of two functions on Python. I was just wondering that if there was a way to have my x function only on the domain between 0 and 0.8 so it wouldn't carry on after the intersection with h-but I still want h to carry on. Is there any way I can modify this? Thanks. This is my code:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.legend_handler import HandlerLine2D

t = np.arange(0.0, 1.0, 0.001)
h = 0.1*np.sin(10*t)
x = 4*t-5*t**2

line1, = plt.plot(t, h, label='h(t)')
line2, = plt.plot(t, x, label='x(t)', linestyle='--')

plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})

plt.xlabel('time')
plt.ylabel('height')
plt.title('Fig 1.')
plt.grid(False)
plt.savefig("Plot.png")
plt.show()

This is how it looks:

Body:
Simply slice the two arrays:

line2, = plt.plot(t[t<0.8], x[t<0.8], label='x(t)', linestyle='--')


问:
Sed not matching one or more patterns
I have this list of files:

```<code>$ more files
one_this_2017_1_abc.txt
two_that_2018_1_abc.txt
three_another_2017_10.abc.txt
four_again_2018_10.abc.txt
five_back_2018_1a.abc.txt
</code>```

I would like to get this output:

```<code>one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_YY.abc.txt
four_again_XXXX_YY.abc.txt
five_back_XXXX_YY.abc.txt
</code>```

I am trying to remove the year and the bit after the year and replace them with another string--this is to generate test cases.

I can get the year just fine, but it's that one or two character piece after it I can't seem to match.

This should work, right?

```<code>~/test_cases
$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[[:alnum:]]\{1,2\}_/_YY_/'
one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt
</code>```

Except it doesn't for the 2 character cases.

```<code>$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[[:alnum:]]\
{2\}_/_YY_/'
one_this_XXXX_1_abc.txt
two_that_XXXX_1_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt
</code>```

Doesn't work for the two character cases either, and this works not at all (but according to the docs it should):

```<code>$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[[:alnum:]]\+_/_YY_/'
one_YY_XXXX_1_abc.txt
two_YY_XXXX_1_abc.txt
three_YY_XXXX_10.abc.txt
four_YY_XXXX_10.abc.txt
five_YY_XXXX_1a.abc.txt
</code>```

Other random experiments that don't work:

```<code>$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[a-zA-Z0-9]\+_/_YY_/'
one_YY_XXXX_1_abc.txt
two_YY_XXXX_1_abc.txt
three_YY_XXXX_10.abc.txt
four_YY_XXXX_10.abc.txt
five_YY_XXXX_1a.abc.txt

$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[a-zA-Z0-9]\{1\}_/_YY_/'
one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt

$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[a-zA-Z0-9]\{2\}_/_YY_/'
one_this_XXXX_1_abc.txt
two_that_XXXX_1_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt
</code>```

Tried with both GNU sed version 4.2.1 under Linux and sed (GNU sed) 4.4 under Cygwin.

And yes, I realize I can pipe this through multiple sed calls to get it to work, but that regex SHOULD work, right?

答:
if your Input_file is same as shown sample then following may help you in same.

```<code>sed 's/\([^_]*\)_\([^_]*\)_\(.*_\)\(.*\)/\1_\2_XXXX_YY_\4/g'   Input_file
</code>```

Output will be as follows.

```<code>one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_YY_10.abc.txt
four_again_XXXX_YY_10.abc.txt
five_back_XXXX_YY_1a.abc.txt
</code>```

Title: Sed not matching one or more patterns

Body:
I have this list of files:

$ more files
one_this_2017_1_abc.txt
two_that_2018_1_abc.txt
three_another_2017_10.abc.txt
four_again_2018_10.abc.txt
five_back_2018_1a.abc.txt

I would like to get this output:

one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_YY.abc.txt
four_again_XXXX_YY.abc.txt
five_back_XXXX_YY.abc.txt

I am trying to remove the year and the bit after the year and replace them with another string--this is to generate test cases.

I can get the year just fine, but it's that one or two character piece after it I can't seem to match.

This should work, right?

~/test_cases
$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[[:alnum:]]\{1,2\}_/_YY_/'
one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt

Except it doesn't for the 2 character cases.

$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[[:alnum:]]\
{2\}_/_YY_/'
one_this_XXXX_1_abc.txt
two_that_XXXX_1_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt

Doesn't work for the two character cases either, and this works not at all (but according to the docs it should):

$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[[:alnum:]]\+_/_YY_/'
one_YY_XXXX_1_abc.txt
two_YY_XXXX_1_abc.txt
three_YY_XXXX_10.abc.txt
four_YY_XXXX_10.abc.txt
five_YY_XXXX_1a.abc.txt

Other random experiments that don't work:

$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[a-zA-Z0-9]\+_/_YY_/'
one_YY_XXXX_1_abc.txt
two_YY_XXXX_1_abc.txt
three_YY_XXXX_10.abc.txt
four_YY_XXXX_10.abc.txt
five_YY_XXXX_1a.abc.txt

$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[a-zA-Z0-9]\{1\}_/_YY_/'
one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt

$ cat files | sed -e 's/_[[:digit:]]\{4\}_/_XXXX_/' -e 's/_[a-zA-Z0-9]\{2\}_/_YY_/'
one_this_XXXX_1_abc.txt
two_that_XXXX_1_abc.txt
three_another_XXXX_10.abc.txt
four_again_XXXX_10.abc.txt
five_back_XXXX_1a.abc.txt

Tried with both GNU sed version 4.2.1 under Linux and sed (GNU sed) 4.4 under Cygwin.

And yes, I realize I can pipe this through multiple sed calls to get it to work, but that regex SHOULD work, right?

Body:
if your Input_file is same as shown sample then following may help you in same.

sed 's/\([^_]*\)_\([^_]*\)_\(.*_\)\(.*\)/\1_\2_XXXX_YY_\4/g'   Input_file

Output will be as follows.

one_this_XXXX_YY_abc.txt
two_that_XXXX_YY_abc.txt
three_another_XXXX_YY_10.abc.txt
four_again_XXXX_YY_10.abc.txt
five_back_XXXX_YY_1a.abc.txt


问:
Conversion of BitmapImage to Byte array
I want to convert a BitmapImage to ByteArray in a Windows Phone 7 Application. So I tried this but it throws the runtime Exception "Invalid Pointer Exception". Can anyone explain why what I'm trying to do throws an exception. And can you provide an alternative solution for this. </p>

<pre class="lang-cs prettyprint-override"><code>    public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
    {
        byte[] data;
        // Get an Image Stream
        using (MemoryStream ms = new MemoryStream())
        {
            WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

            // write an image into the stream
            Extensions.SaveJpeg(btmMap, ms,
                bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

            // reset the stream pointer to the beginning
            ms.Seek(0, 0);
            //read the stream into a byte array
            data = new byte[ms.Length];
            ms.Read(data, 0, data.Length);
        }
        //data now holds the bytes of the image
        return data;
    }
</code>```

答:
I'm not sure exactly what your problem is, but I know that the following code is a very minor change from code that I know works (mine was passing in a WriteableBitmap, not a BitmapImage):

public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
    byte[] data = null;
    using (MemoryStream stream = new MemoryStream())
    {
        WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
        wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
        stream.Seek(0, SeekOrigin.Begin);
        data = stream.GetBuffer();
    }

    return data;
}```

Title: Conversion of BitmapImage to Byte array

Body:
I want to convert a BitmapImage to ByteArray in a Windows Phone 7 Application. So I tried this but it throws the runtime Exception "Invalid Pointer Exception". Can anyone explain why what I'm trying to do throws an exception. And can you provide an alternative solution for this.

    public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
    {
        byte[] data;
        // Get an Image Stream
        using (MemoryStream ms = new MemoryStream())
        {
            WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

            // write an image into the stream
            Extensions.SaveJpeg(btmMap, ms,
                bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

            // reset the stream pointer to the beginning
            ms.Seek(0, 0);
            //read the stream into a byte array
            data = new byte[ms.Length];
            ms.Read(data, 0, data.Length);
        }
        //data now holds the bytes of the image
        return data;
    }


问:
Writing errors to a text file in a Web Service
I have a web service that has a default ErrorLog method for adding Logs to a Db Table. If there's an exception is caught on the ErrorLog Add or the Stored Procedure returns that it failed to add. I'd like to write the error to a textfile on the server, (in theory this should never happen).

Now before actually implementing this, I realize there's a good chance that multiple people could get an error, all of them fail, and all of them try to write to the same text file.

How can I implement a queue on the service, so that the messages get added to the queue and another service / job loops through this queue and adds the errors to the file?

I have tried looking for examples, most of them are very basic. The only thing I really want to know is how I should keep track of the queue? Do I simply create a static class?

Would the below work?

```<code>public class ErrorLogging
{

    public ErrorLogging(Error error)
    {
        if (ErrorLoggingQueue._GlobalQueue == null)
        {
            ErrorLoggingQueue._GlobalQueue = new Queue<Error>();
        }

        ErrorLoggingQueue._GlobalQueue.Enqueue(error);
    }
}

public static class ErrorLoggingQueue
{
    public static Queue<Error> _GlobalQueue;
}

// Assume that this class/method gets called every x minutes or seconds from  a job or something.
public class JobClass
{
    public void WriteErrors()
    {
        if (ErrorLoggingQueue._GlobalQueue != null)
        {
            while (ErrorLoggingQueue._GlobalQueue.Count != 0)
            {
                Error error = (Error)ErrorLoggingQueue._GlobalQueue.Dequeue();

                // Do stuff here
            }
        }
    }
}
</code>```

答:
Yes, static variable with a Queue will work and would be shared between requests. Just add locking for enqueue and dequeue to make those operation atomic. Something along these lines:</p>

```<code>class YourWebservice
{
    static Queue<Error> _GlobalQueue = new Queue<Error>();
    static readonly object queueLock = new object();
    static Thread errorLogger;

    public void SomeWebserviceMethod()
    {
        //Some code...
        //.
        //.

        //Here we want to log an error
        EnqueueError(new Error());
    }
    private void EnqueueError(Error err )
    {
        lock(queueLock)
        {
            _GlobalQueue?.Enqueue(err);
            if ( errorLogger==null || !(errorLogger?.IsAlive ?? false) )
            {
                errorLogger = new Thread(new ThreadStart(WriteErrors));
                errorLogger?.Start();
            }
        }
    }

    private static Error DequeueError()
    {
        try
        {
            lock (queueLock)
            {
                return  _GlobalQueue?.Dequeue();
            }
        }
        catch(Exception)
        {
            //if we got here it means queue is empty.
        }

        return null;
    }
    private static void WriteErrors()
    {
       Error error = DequeueError();
       while (error!=null)
       {
            //Log error here
            //...
            //..

            error = DequeueError();
       }
    }
}
</code>```

Body:
I have a web service that has a default ErrorLog method for adding Logs to a Db Table. If there's an exception is caught on the ErrorLog Add or the Stored Procedure returns that it failed to add. I'd like to write the error to a textfile on the server, (in theory this should never happen).

Now before actually implementing this, I realize there's a good chance that multiple people could get an error, all of them fail, and all of them try to write to the same text file.

How can I implement a queue on the service, so that the messages get added to the queue and another service / job loops through this queue and adds the errors to the file?

I have tried looking for examples, most of them are very basic. The only thing I really want to know is how I should keep track of the queue? Do I simply create a static class?

Would the below work?

public class ErrorLogging
{

    public ErrorLogging(Error error)
    {
        if (ErrorLoggingQueue._GlobalQueue == null)
        {
            ErrorLoggingQueue._GlobalQueue = new Queue<Error>();
        }

        ErrorLoggingQueue._GlobalQueue.Enqueue(error);
    }
}

public static class ErrorLoggingQueue
{
    public static Queue<Error> _GlobalQueue;
}

// Assume that this class/method gets called every x minutes or seconds from  a job or something.
public class JobClass
{
    public void WriteErrors()
    {
        if (ErrorLoggingQueue._GlobalQueue != null)
        {
            while (ErrorLoggingQueue._GlobalQueue.Count != 0)
            {
                Error error = (Error)ErrorLoggingQueue._GlobalQueue.Dequeue();

                // Do stuff here
            }
        }
    }
}

Body:
Yes, static variable with a Queue will work and would be shared between requests. Just add locking for enqueue and dequeue to make those operation atomic. Something along these lines:

class YourWebservice
{
    static Queue<Error> _GlobalQueue = new Queue<Error>();
    static readonly object queueLock = new object();
    static Thread errorLogger;

    public void SomeWebserviceMethod()
    {
        //Some code...
        //.
        //.

        //Here we want to log an error
        EnqueueError(new Error());
    }
    private void EnqueueError(Error err )
    {
        lock(queueLock)
        {
            _GlobalQueue?.Enqueue(err);
            if ( errorLogger==null || !(errorLogger?.IsAlive ?? false) )
            {
                errorLogger = new Thread(new ThreadStart(WriteErrors));
                errorLogger?.Start();
            }
        }
    }

    private static Error DequeueError()
    {
        try
        {
            lock (queueLock)
            {
                return  _GlobalQueue?.Dequeue();
            }
        }
        catch(Exception)
        {
            //if we got here it means queue is empty.
        }

        return null;
    }
    private static void WriteErrors()
    {
       Error error = DequeueError();
       while (error!=null)
       {
            //Log error here
            //...
            //..

            error = DequeueError();
       }
    }
}


问:
c++ ifstream , Reading from file crashes
At the beginning I apologize for my English.

I was trying to write a XML Parser that I encountered a weird problem.
to explain my problem I should say, I have a xml parser class that has an ifstream member. And this class has a function which reads until it reaches an open tag matching with the given input.

this is the parser class I was working on:

```<code>// XMLParser.cpp
#include <fstream>
#include "Stack.h"
using namespace std;

class XMLParser{
    private:
        int charReadRate = 3;
    public:
        ifstream *stream;

        XMLParser(string add){
            stream = new ifstream(add); // open input stream
        }
        void nextTag(string tag){
            // find the first occurance of open-tag with name 'tag'
            cout << "nextTag\n";
            char * readData;
            string tagName="";
            stream->read(readData, charReadRate);
            int len = string(readData).length();
            int i = 0;
//          cout << len << endl;
            while(true){
                if((*readData) == '<'){
                    readData++;
                    i++;
                    while(*readData != '>'){
                        tagName+=*readData;
                        readData++;
                        i++;
                        if(i>=len){
                            if(stream->eof()){
                                return ; // error didn't find
                            }
                            stream->read(readData, charReadRate);
//                          cout << readData << endl;
                            len = string(readData).length();
                            i = 0;
                        }else{
                            if(tagName == tag){
//                              cout << "find\n";
                                stream->seekg(i-len, ios::cur);
                                return;
                            }
                        }
                    }
                }else{
                    readData++;
                    i++;
                    if(i>=len){
                        if(stream->eof()){
                            return ; // error didn't find
                        }
                        stream->read(readData, charReadRate);
                        len = string(readData).length();
                        i = 0;
                    }
                }
            }
        }
};
</code>```

in the nextTag   function I read the file until I reach the open tag which name's matches with the given input.

and here is my main function

```<code>int main(){
    XMLParser parser("test.xml");
    cout << "ready\n";
    parser.nextTag("Log");
    char *c;
    parser.stream->read(c,3);
    cout << c << endl;
    return 0;
}
</code>```

I have figured out that the program crashes when the fifth line of the main function [parser.stream->read(c,3);] is executed.

I wonder why this happens?

答:
The char pointer you pass to ifstream::read is not initialized and thus points to an invalid memory region, causing your program to crash. You need it to point to a buffer you allocated:

```<code>int main(){
    XMLParser parser("test.xml");
    cout << "ready\n";
    parser.nextTag("Log");
    char c[3];
    parser.stream->read(c,3);
    cout << c << endl;
    return 0;
}
</code>```

Body:
At the beginning I apologize for my English.

I was trying to write a XML Parser that I encountered a weird problem.
to explain my problem I should say, I have a xml parser class that has an ifstream member. And this class has a function which reads until it reaches an open tag matching with the given input.

this is the parser class I was working on:

// XMLParser.cpp
#include <fstream>
#include "Stack.h"
using namespace std;

class XMLParser{
    private:
        int charReadRate = 3;
    public:
        ifstream *stream;

        XMLParser(string add){
            stream = new ifstream(add); // open input stream
        }
        void nextTag(string tag){
            // find the first occurance of open-tag with name 'tag'
            cout << "nextTag\n";
            char * readData;
            string tagName="";
            stream->read(readData, charReadRate);
            int len = string(readData).length();
            int i = 0;
//          cout << len << endl;
            while(true){
                if((*readData) == '<'){
                    readData++;
                    i++;
                    while(*readData != '>'){
                        tagName+=*readData;
                        readData++;
                        i++;
                        if(i>=len){
                            if(stream->eof()){
                                return ; // error didn't find
                            }
                            stream->read(readData, charReadRate);
//                          cout << readData << endl;
                            len = string(readData).length();
                            i = 0;
                        }else{
                            if(tagName == tag){
//                              cout << "find\n";
                                stream->seekg(i-len, ios::cur);
                                return;
                            }
                        }
                    }
                }else{
                    readData++;
                    i++;
                    if(i>=len){
                        if(stream->eof()){
                            return ; // error didn't find
                        }
                        stream->read(readData, charReadRate);
                        len = string(readData).length();
                        i = 0;
                    }
                }
            }
        }
};

in the nextTag   function I read the file until I reach the open tag which name's matches with the given input.

and here is my main function

int main(){
    XMLParser parser("test.xml");
    cout << "ready\n";
    parser.nextTag("Log");
    char *c;
    parser.stream->read(c,3);
    cout << c << endl;
    return 0;
}

I have figured out that the program crashes when the fifth line of the main function [parser.stream->read(c,3);] is executed.

I wonder why this happens?

Body:
The char pointer you pass to ifstream::read is not initialized and thus points to an invalid memory region, causing your program to crash. You need it to point to a buffer you allocated:

int main(){
    XMLParser parser("test.xml");
    cout << "ready\n";
    parser.nextTag("Log");
    char c[3];
    parser.stream->read(c,3);
    cout << c << endl;
    return 0;
}


问:
Angular iframe not loading correctly
I implemented a ifame inside my angular app, first it blocked the resource, then i added a pipe to access the resource and now the browser is blocking it because of mixed content because its not loading the content over https

stundenplan.component.ts:

```<code><div class="col-sm-9 content">
<div class="dashhead">
<div class="dashhead-titles">
<h6 class="dashhead-subtitle">TeamCloud</h6>
<h2 class="dashhead-title">Stundenplan</h2>
</div>

</div>

<hr class="m-t">

<div class="container">
  <iframe style="width: 100%; height: 900px;" frameborder="0" [src]="'http://******' | safeIframe"></iframe>
</div> <!-- /container -->

</div>
</code>```

safe-iframe.pipe.ts:

```<code>import { DomSanitizer } from '@angular/platform-browser';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'safeIframe'
})
export class SafeIframePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer){}
  transform(url:string) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

}
</code>```

error im getting when loading the page
Mixed Content: The page at 'https://teamcloud.******/stundenplan' was loaded over HTTPS, but requested an insecure resource 'http://******'. This request has been blocked; the content must be served over HTTPS

答:
This is a browser-restriction; when on a secure (HTTPS) page, browsers will refuse to load insecure active content (e.g.: scripts, iframes) by default. It's not a problem you solve with Angular. You basically have 3 options:

Override the browser default. Instructions for this will change from browser to browser, but it must be done by every user. Probably won't happen

Use an HTTPS url as your iframe source. If the content you want is not delivered over HTTPS, I'm afraid you'll have to go through some trouble such as setting up your own HTTPS proxy. Not fun

Access/serve the main page over HTTP, so the browser will have no mixed-content complaints when the iframe is also just HTTP

Title: Angular iframe not loading correctly

Body:
I implemented a ifame inside my angular app, first it blocked the resource, then i added a pipe to access the resource and now the browser is blocking it because of mixed content because its not loading the content over https

stundenplan.component.ts:

TeamCloud

Stundenplan

safe-iframe.pipe.ts:

import { DomSanitizer } from '@angular/platform-browser';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'safeIframe'
})
export class SafeIframePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer){}
  transform(url:string) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

}

error im getting when loading the page
Mixed Content: The page at 'https://teamcloud.******/stundenplan' was loaded over HTTPS, but requested an insecure resource 'http://******'. This request has been blocked; the content must be served over HTTPS