问:
Can RabbitMQ (or similar message queuing system) be used to single thread requests per user?
The issue is we have some modern web applications that are integrated with a legacy system that was never designed to support multiple concurrent requests from a single user.  Basically there are certain types of requests that the legacy system can only handle one-at-a-time from a single user.  It can handle multiple concurrent requests coming from different users, but for technical reasons cannot handle multiple from a single user.  In these situations, the user's first request will complete successfully, but any subsequent requests from that same user that come in while the first request is still executing will fail.

Because our apps are ajax enabled, multi-tab/multi-browser friendly, and just the fact that there are multiple apps - there are certain scenarios where a user could wind up having more than one of these types of requests being sent to the legacy system at the same time.

I'm trying to determine if something like RabbitMQ could be positioned in front of the legacy system and leveraged to single-thread requests per user/IP.  The thinking being that the web apps would send all requests to MQ, and they'd stack into per-user queues and pass on to the legacy system one at a time.

I don't know if there would be concerns about the potential number of queues this could create - we have a user-base of approx 4,000.

And I know we could somewhat address this in the web apps individually, but since there are multiple apps it'd be duplicating logic across them, and you'd still have the potential for two different apps to fire off concurrent requests.

Any feedback would be appreciated.  Thanks-

答:
I'm not sure a unique queue per user will work as you would need to have a backend worker process listening for messages on that queue that would need to be dynamically created.

Below is one option but it does have a performance bottleneck potential as a single backend process would be handling all requests sequentially. You could use multiple worker processes but you wouldn't know if one had completed before the other causing a race condition if your app requires a specific sequence of actions.

You could simply put all transactions (from all users) into a single queue and have a backend process pull off of that queue and service the request. If there needs to be a response back to the user once the request was serviced, then the worker process could respond back to a separate queue with a correlationID that could be used to send the response date back to the correct user.

I've done this before with ExpressJS apps where the following flow would happen:

The user/process/ajax makes a request

Express takes the payload from the request object and sends it to a RabbitMQ queue with a unique correlationId (e.g. UUID).

Express then takes the response object and stores it in a responseStore object with the key being the correlationId

Meanwhile, a backend worker process pulls the item from the queue, does some work and then sends a message to a different response queue with the same correlationId

The ExpressJS application has a connection to the response queue and when it receives a message, it takes the correlationId from the response and looks for a response object stored with same correlationId in the responseStore. If it finds it, it takes the payload from the message and does something like response.send(payload) or response.json(payload)

To do this, you should also have a mechanism that stores the creation time of the response object in the responseStore along with the response object. Then have a separate process that will check the responseStore and clean up old response objects after a certain timeout in case there are issues with the backend process completing.

Look here for more info on RPC with RabbitMQ:

https://www.rabbitmq.com/tutorials/tutorial-six-javascript.html

Hope this helps.


来源: stackexchange

问:
Using designated initializers with unnamed nested data types
I'm wondering if it is possible to use designated initializers in unnamed data members of structs...   (Yikes, a mouthful, but yes, it is the cleanest way to do what I'm trying to do...).   If I have:

```<code>typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main.a64 = { 0, 0 }, .otherval = 3 };
</code>```

and I try to compile, I get the error:

```<code>tst3.c:16: error: unknown field ‘a64’ specified in initializer
</code>```

I've also tried using .main..a64, but I'm getting other issues.   This is with gcc 4.4.  Unfortunately, the MainStruct is used all over the code, so naming the union would involve changing hundreds of files, so I'd like to avoid that.   I'd also like to avoid any assumptions about position of MainStruct within OtherStruct if possible.

答:
You need to change the syntax a bit, initializing .main within the initializer for instance:

```<code>typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main = {.a64 = { 0, 0 }}, .otherval = 3 };
</code>```

Here is a working test program:

```<code>#include <stdio.h>
#include <stdint.h>

typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main = {.a64 = { 5, 10 }}, .otherval = 3 };

int main(void)
{
    printf("%d, %d\n", (int) instance.main.a64[0], (int) instance.main.a64[1]);
    printf("%d\n", instance.otherval);

}
</code>```

Compiled with gcc -std=c11 -Wall -Wextra -Wpedantic, here is the program output:

```<code>5, 10
3
</code>```

Update

This use of designated initializers should also work with at least C99, though C99 does not support unnamed structures or unions. Here is an example:

```<code>#include <stdio.h>

struct Inner {
    int x;
    int arr[2];
};

struct Outer {
    char id[100];
    struct Inner state;
};

int main(void)
{
    struct Outer instance = { .id = "first",
                              .state = {.x = 5, .arr[0] = 1, .arr[1] = 2 }};

    printf("instance id: %s\n", instance.id);
    printf("instance state.x = %d\n", instance.state.x);
    printf("instance state.arr[0] = %d\n", instance.state.arr[0]);
    printf("instance state.arr[1] = %d\n", instance.state.arr[1]);

    return 0;
}
</code>```

Compiled with gcc -std=c99 -Wall -Wextra -Wpedantic, here is the program output:

```<code>instance id: first
instance state.x = 5
instance state.arr[0] = 1
instance state.arr[1] = 2
</code>```

Final Note

It turns out that OP's original syntax of:

```<code>OtherStruct_t instance = { .main.a64 = { 0, 0 }, .otherval = 3 };
</code>```

should also work on both C99 and C11, but is not supported in older standards which do not allow initialization of subobjects.

Unnamed unions are not supported in C99, but are available as a GNU extension. Further investigation has turned up this bug report which suggests that designated initializers for unnamed structs and unions were fixed in gcc 4.6. As workaround, it was suggested at this link to enclose the offending initializer in braces; it is also mentioned that this workaround is a bit finicky and position dependent, which may explain why it does not work here for OP.

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if it is possible to use designated initializers in unnamed data members of structs...   (Yikes, a mouthful, but yes, it is the cleanest way to do what I'm trying to do...).   If I have:

typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main.a64 = { 0, 0 }, .otherval = 3 };

and I try to compile, I get the error:

tst3.c:16: error: unknown field ‘a64’ specified in initializer

I've also tried using .main..a64, but I'm getting other issues.   This is with gcc 4.4.  Unfortunately, the MainStruct is used all over the code, so naming the union would involve changing hundreds of files, so I'd like to avoid that.   I'd also like to avoid any assumptions about position of MainStruct within OtherStruct if possible.

Body:
You need to change the syntax a bit, initializing .main within the initializer for instance:

typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main = {.a64 = { 0, 0 }}, .otherval = 3 };

Here is a working test program:

#include <stdio.h>
#include <stdint.h>

typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main = {.a64 = { 5, 10 }}, .otherval = 3 };

int main(void)
{
    printf("%d, %d\n", (int) instance.main.a64[0], (int) instance.main.a64[1]);
    printf("%d\n", instance.otherval);

}

Compiled with gcc -std=c11 -Wall -Wextra -Wpedantic, here is the program output:

5, 10
3

Update

This use of designated initializers should also work with at least C99, though C99 does not support unnamed structures or unions. Here is an example:

#include <stdio.h>

struct Inner {
    int x;
    int arr[2];
};

struct Outer {
    char id[100];
    struct Inner state;
};

int main(void)
{
    struct Outer instance = { .id = "first",
                              .state = {.x = 5, .arr[0] = 1, .arr[1] = 2 }};

    printf("instance id: %s\n", instance.id);
    printf("instance state.x = %d\n", instance.state.x);
    printf("instance state.arr[0] = %d\n", instance.state.arr[0]);
    printf("instance state.arr[1] = %d\n", instance.state.arr[1]);

    return 0;
}

Compiled with gcc -std=c99 -Wall -Wextra -Wpedantic, here is the program output:

instance id: first
instance state.x = 5
instance state.arr[0] = 1
instance state.arr[1] = 2

Final Note

It turns out that OP's original syntax of:

OtherStruct_t instance = { .main.a64 = { 0, 0 }, .otherval = 3 };

should also work on both C99 and C11, but is not supported in older standards which do not allow initialization of subobjects.

Unnamed unions are not supported in C99, but are available as a GNU extension. Further investigation has turned up this bug report which suggests that designated initializers for unnamed structs and unions were fixed in gcc 4.6. As workaround, it was suggested at this link to enclose the offending initializer in braces; it is also mentioned that this workaround is a bit finicky and position dependent, which may explain why it does not work here for OP.


问:
How to show PlacePicker location on a Google Map?
My app uses the google maps api and the google places api. Everything works perfectly until I search for a certain place, when I search for a place and then select it from the results a dialog box (which should not show) shows up and prompts the user if they want to select that place or change the address. After clicking "select" the app removes the places UI and turns into a regular map, without ever going to the place selected. My code is below. </p>

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private static final int PLACE_PICKER_REQUEST = 1000;
    private GoogleApiClient mClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        int PLACE_PICKER_REQUEST = 1;
        PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

        try {
            startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
        } catch (GooglePlayServicesRepairableException e) {
            e.printStackTrace();
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }
        mClient = new GoogleApiClient
                .Builder(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .build();

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
            Place place = PlacePicker.getPlace(data, this);
            StringBuilder stBuilder = new StringBuilder();
            String placename = String.format("%s", place.getName());
            String latitude = String.valueOf(place.getLatLng().latitude);
            String longitude = String.valueOf(place.getLatLng().longitude);
            String address = String.format("%s", place.getAddress());
            stBuilder.append("Name: ");
            stBuilder.append(placename);
            stBuilder.append("\n");
            stBuilder.append("Latitude: ");
            stBuilder.append(latitude);
            stBuilder.append("\n");
            stBuilder.append("Logitude: ");
            stBuilder.append(longitude);
            stBuilder.append("\n");
            stBuilder.append("Address: ");
            stBuilder.append(address);

        }
    }
}

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
    @Override
    protected void onStart() {
        super.onStart();
        mClient.connect();
    }
    @Override
    protected void onStop() {
        mClient.disconnect();
        super.onStop();
    }

}
</code>```

答:
You need to use the data Intent to get the location of the Place that the user selected, add a Marker to the map, and move the camera so that it's centered over the selected Place:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
            Place place = PlacePicker.getPlace(data, this);
            String placeName = String.format("Place: %s", place.getName());
            String placeAddress =  String.format("Address: %s", place.getAddress());
            LatLng toLatLng = place.getLatLng();

            // Add Marker
            marker = mMap.addMarker(new MarkerOptions().position(toLatLng)
                    .title(placeName).snippet(placeAddress)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));

            // Move Camera to selected place
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

        }
    }
}
</code>```

Body:
My app uses the google maps api and the google places api. Everything works perfectly until I search for a certain place, when I search for a place and then select it from the results a dialog box (which should not show) shows up and prompts the user if they want to select that place or change the address. After clicking "select" the app removes the places UI and turns into a regular map, without ever going to the place selected. My code is below.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private static final int PLACE_PICKER_REQUEST = 1000;
    private GoogleApiClient mClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        int PLACE_PICKER_REQUEST = 1;
        PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

        try {
            startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
        } catch (GooglePlayServicesRepairableException e) {
            e.printStackTrace();
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }
        mClient = new GoogleApiClient
                .Builder(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .build();

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
            Place place = PlacePicker.getPlace(data, this);
            StringBuilder stBuilder = new StringBuilder();
            String placename = String.format("%s", place.getName());
            String latitude = String.valueOf(place.getLatLng().latitude);
            String longitude = String.valueOf(place.getLatLng().longitude);
            String address = String.format("%s", place.getAddress());
            stBuilder.append("Name: ");
            stBuilder.append(placename);
            stBuilder.append("\n");
            stBuilder.append("Latitude: ");
            stBuilder.append(latitude);
            stBuilder.append("\n");
            stBuilder.append("Logitude: ");
            stBuilder.append(longitude);
            stBuilder.append("\n");
            stBuilder.append("Address: ");
            stBuilder.append(address);

        }
    }
}

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
    @Override
    protected void onStart() {
        super.onStart();
        mClient.connect();
    }
    @Override
    protected void onStop() {
        mClient.disconnect();
        super.onStop();
    }

}

Body:
You need to use the data Intent to get the location of the Place that the user selected, add a Marker to the map, and move the camera so that it's centered over the selected Place:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
            Place place = PlacePicker.getPlace(data, this);
            String placeName = String.format("Place: %s", place.getName());
            String placeAddress =  String.format("Address: %s", place.getAddress());
            LatLng toLatLng = place.getLatLng();

            // Add Marker
            marker = mMap.addMarker(new MarkerOptions().position(toLatLng)
                    .title(placeName).snippet(placeAddress)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));

            // Move Camera to selected place
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

        }
    }
}


问:
Why can't 32bit binary process go beyond 4GB limit?
Have experienced out of memory (OOM) issues with 32bit binaries and 32 bit Perl while attempting to load more 2-3GB of data into memory on Linux.

Always wondered why an OS with Demand Paging capabilities , cannot swap out resident pages to disk and load more pages to grow beyond 4GB limitation ?

Probably there would be frequent Page-Faults happening (impacting performance) but should never hit OOM issue ?

答: It's because the 32 bit processor can only address 32 bits while accessing memory,  3 GB (3 × 10243 bytes) is the limit for this operation.</p>


问:
Submit handler is working but its very slow
Hello guys I am submitting my form using submit handler and its working but its very slow. Please help me to make it fast. Thanks in advance
Following is my javascript code for login form......

```<code>       var handleLoginForm = function () {

       $('.login-form').validate({
        errorElement: 'label', //default input error message container
        errorClass: 'help-inline', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            },
             user_type: {
                required: true
            },
            remember: {
                required: false
            }
        },

        messages: {
            username: {
                required: "Username is required."
            },
            password: {
                required: "Password is required."
            },
              user_type: {
                required: "User Type is Required."
            }
        },

        invalidHandler: function (event, validator) { //display error alert on form submit
            $('.alert-error', $('.login-form')).show();
        },

        highlight: function (element) { // hightlight error inputs
            $(element)
                .closest('.control-group').addClass('error'); // set error class to the control group
        },
        data: $('#form_modulesadd').serialize(),

        success: function (label) {
            label.closest('.control-group').removeClass('error');
            label.remove();
        },

        errorPlacement: function (error, element) {
            error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
        },

           submitHandler: function (form) {
           $( ".login-form input" ).submit();
            window.location.href = "check.php";

        }
    });
</code>```

It was fast when i was submitting the form using php but I must have to use javascript to submit this form......

答:
I solved the same problem by changing the implementation of submitHandler like below. I just take the first item [0] of the forms selector.</p>

```<code>submitHandler: function (form) {
    $(".login-form input")[0].submit();
    ...
}
</code>```

Body:
Hello guys I am submitting my form using submit handler and its working but its very slow. Please help me to make it fast. Thanks in advance
Following is my javascript code for login form......

       var handleLoginForm = function () {

       $('.login-form').validate({
        errorElement: 'label', //default input error message container
        errorClass: 'help-inline', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            },
             user_type: {
                required: true
            },
            remember: {
                required: false
            }
        },

        messages: {
            username: {
                required: "Username is required."
            },
            password: {
                required: "Password is required."
            },
              user_type: {
                required: "User Type is Required."
            }
        },

        invalidHandler: function (event, validator) { //display error alert on form submit
            $('.alert-error', $('.login-form')).show();
        },

        highlight: function (element) { // hightlight error inputs
            $(element)
                .closest('.control-group').addClass('error'); // set error class to the control group
        },
        data: $('#form_modulesadd').serialize(),

        success: function (label) {
            label.closest('.control-group').removeClass('error');
            label.remove();
        },

        errorPlacement: function (error, element) {
            error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
        },

           submitHandler: function (form) {
           $( ".login-form input" ).submit();
            window.location.href = "check.php";

        }
    });

It was fast when i was submitting the form using php but I must have to use javascript to submit this form......

Body:
I solved the same problem by changing the implementation of submitHandler like below. I just take the first item [0] of the forms selector.

submitHandler: function (form) {
    $(".login-form input")[0].submit();
    ...
}


问:
Jasypt with spring 4.0
I am using spring security in my application through XML configuration.

This is my password encoder bean

```<code><b:bean id="passwordEncoder"
    class="org.springframework.security.crypto.password.StandardPasswordEncoder">
    <b:constructor-arg value="ThisIsASecretSoChangeMe" />
</b:bean>
</code>```

I want to replace it with Jasypt encryption.
How to integrate jasypt 1.9 with spring security 4.0.1.RELEASE?

答:
If you are using spring-boot use this dependeny in pom

```<code>        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>${jasypt-spring-boot-starter.version}</version>
        </dependency>
</code>```

and in your application.yml or application.properties file just put the Encrypted password enclosed with ENC() instead of plainpassword. Example

```<code>password:
    encrypted:
        password: ENC(nZ3U2bdJ05FHp1LYQbAVvDKkVs8Pi3Ke)

jasypt:
    encryptor:
        password: IfYouAreGoodAtSomethingNeverDoItForFree
</code>```

Before this you need to generate this encrypted password from your plaintext password and the jasypt.encryptor.password(similar to salt, in this case IfYouAreGoodAtSomethingNeverDoItForFree). This can be done by something like this

```<code>java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="PasswordToBeEncrypted" password=<SecretKeyToEncryptDecrypt> algorithm=PBEWithMD5AndDES
</code>```

or torough a java code. Here is a rough draft.

```<code>public class Md5Test {
    public static void main(String[] args) throws NoSuchAlgorithmException {

        String password = "plaintextpassword";

        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("IfYouAreGoodAtSomethingNeverDoItForFree  ");
        String myEncryptedText = textEncryptor.encrypt(password);
        System.out.println(myEncryptedText);
        BasicTextEncryptor textDecryptor = new BasicTextEncryptor();
        textDecryptor.setPassword("IfYouAreGoodAtSomethingNeverDoItForFree  ");
        String plainText = textDecryptor.decrypt("QBPaH8HKE8JDaeIpJk66Kc8nGHtBfY+L");
        System.out.println(plainText);
    }
  }
</code>```

Title: Jasypt with spring 4.0

Body:
I am using spring security in my application through XML configuration.

This is my password encoder bean

I want to replace it with Jasypt encryption.
How to integrate jasypt 1.9 with spring security 4.0.1.RELEASE?

Body:
If you are using spring-boot use this dependeny in pom

        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>${jasypt-spring-boot-starter.version}</version>
        </dependency>

and in your application.yml or application.properties file just put the Encrypted password enclosed with ENC() instead of plainpassword. Example

password:
    encrypted:
        password: ENC(nZ3U2bdJ05FHp1LYQbAVvDKkVs8Pi3Ke)

jasypt:
    encryptor:
        password: IfYouAreGoodAtSomethingNeverDoItForFree

Before this you need to generate this encrypted password from your plaintext password and the jasypt.encryptor.password(similar to salt, in this case IfYouAreGoodAtSomethingNeverDoItForFree). This can be done by something like this

java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="PasswordToBeEncrypted" password=<SecretKeyToEncryptDecrypt> algorithm=PBEWithMD5AndDES

or torough a java code. Here is a rough draft.

public class Md5Test {
    public static void main(String[] args) throws NoSuchAlgorithmException {

        String password = "plaintextpassword";

        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("IfYouAreGoodAtSomethingNeverDoItForFree  ");
        String myEncryptedText = textEncryptor.encrypt(password);
        System.out.println(myEncryptedText);
        BasicTextEncryptor textDecryptor = new BasicTextEncryptor();
        textDecryptor.setPassword("IfYouAreGoodAtSomethingNeverDoItForFree  ");
        String plainText = textDecryptor.decrypt("QBPaH8HKE8JDaeIpJk66Kc8nGHtBfY+L");
        System.out.println(plainText);
    }
  }

ContentLicense: CC BY-SA 4.0


问:
Birthday with where clause
Can any one help me with this

Script

This is what i want to achive

table

```<code>id  name    tag_id  status      dob
== ======= ======== ========   ========
1   a       1        Married    02/23/1977
2   b       1        Single     02/23/1978
3   c       2        Single     02/23/1960
4   d       1        Married    02/23/1985
5   e       2        Married    02/23/1999
6   f       2        Diovice    02/23/1999
7   g       1        Married    02/28/1999
8   h       2        Married    02/28/1999
9   i       1        Married    03/12/1990
</code>```

I will love to get the present/ current birthday celebrant with mysql query
here is my code:

```<code>SELECT * FROM table
WHERE (MONTH(STR_TO_DATE(dob, '%d/%m/%Y'))=MONTH(CURDATE())
    AND (DAY(STR_TO_DATE(dob, '%d/%m/%Y'))=DAY(CURDATE())))
    OR (DAY(LAST_DAY(STR_TO_DATE(dob, '%d/%m/%Y')))=29
    AND (DAY(STR_TO_DATE(bob, '%d/%m/%Y'))=29)
    AND (DAY(LAST_DAY(CURDATE()))=28))
    AND ( STATUS = 'Married' OR STATUS = 'Single' )
    AND tag_id = 1
ORDER BY id ASC
</code>```

my problem is the above code is just returing all present bithday but what i want is like this:

result:

```<code>1   a       1        Married    02/23/1977
2   b       1        Single     02/23/1978
4   d       1        Married    02/23/1985
7   g       1        Married    02/28/1999
</code>```

Wrong result (produce by the above query):

```<code>1   a       1        Married    02/23/1977
2   b       1        Single     02/23/1978
4   d       1        Married    02/23/1985
7   g       1        Married    02/28/1999
8   h       2        Married    02/28/1999
</code>```

And what i want, i only want Birthday Celebrant for today that/ where is ID = 1. Like i specify with the first result.

答:
This later worked out for me, it might help others and i will love to see more improvement of this answer:</p>

```<code>SELECT * FROM table WHERE MONTH(STR_TO_DATE(dob, '%d/%m/%Y')) = MONTH(NOW()) AND DAY(STR_TO_DATE(dob, '%d/%m/%Y')) = DAY(NOW()) AND TAG_ID = 2 AND STATUS IN ('single','married')
</code>```

Title: Birthday with where clause

Body:
Can any one help me with this

Script

This is what i want to achive

table

id  name    tag_id  status      dob
== ======= ======== ========   ========
1   a       1        Married    02/23/1977
2   b       1        Single     02/23/1978
3   c       2        Single     02/23/1960
4   d       1        Married    02/23/1985
5   e       2        Married    02/23/1999
6   f       2        Diovice    02/23/1999
7   g       1        Married    02/28/1999
8   h       2        Married    02/28/1999
9   i       1        Married    03/12/1990

I will love to get the present/ current birthday celebrant with mysql query
here is my code:

SELECT * FROM table
WHERE (MONTH(STR_TO_DATE(dob, '%d/%m/%Y'))=MONTH(CURDATE())
    AND (DAY(STR_TO_DATE(dob, '%d/%m/%Y'))=DAY(CURDATE())))
    OR (DAY(LAST_DAY(STR_TO_DATE(dob, '%d/%m/%Y')))=29
    AND (DAY(STR_TO_DATE(bob, '%d/%m/%Y'))=29)
    AND (DAY(LAST_DAY(CURDATE()))=28))
    AND ( STATUS = 'Married' OR STATUS = 'Single' )
    AND tag_id = 1
ORDER BY id ASC

my problem is the above code is just returing all present bithday but what i want is like this:

result:

1   a       1        Married    02/23/1977
2   b       1        Single     02/23/1978
4   d       1        Married    02/23/1985
7   g       1        Married    02/28/1999

Wrong result (produce by the above query):

1   a       1        Married    02/23/1977
2   b       1        Single     02/23/1978
4   d       1        Married    02/23/1985
7   g       1        Married    02/28/1999
8   h       2        Married    02/28/1999

And what i want, i only want Birthday Celebrant for today that/ where is ID = 1. Like i specify with the first result.

Body:
This later worked out for me, it might help others and i will love to see more improvement of this answer:

SELECT * FROM table WHERE MONTH(STR_TO_DATE(dob, '%d/%m/%Y')) = MONTH(NOW()) AND DAY(STR_TO_DATE(dob, '%d/%m/%Y')) = DAY(NOW()) AND TAG_ID = 2 AND STATUS IN ('single','married')


问:
How to determine size in bytes of H2O frame in Python?
I am loading Spark dataframes into H2O (using Python) for building machine learning models. It has been recommended to me that I should allocate an H2O cluster with RAM 2-4x as big as the frame I will be training on, so that the analysis fits comfortably within memory. But I don't know how to precisely estimate the size of an H2O frame.

So supposing I have an H2O frame already loaded into Python, how do I actually determine its size in bytes? An approximation within 10-20% is fine.

答:
This will show a summary of the underlying representation in H2O's key-value store, including the full byte size:</p>

```<code>frame.describe(chunk_summary=True)
</code>```

Body:
This will show a summary of the underlying representation in H2O's key-value store, including the full byte size:

frame.describe(chunk_summary=True)


问:
Saving a loop's output in a vector in R
I have a .cvs file which consists of 4 columns and 120 rows.
I'm attempting to go through every row and where ever i see a "1" in the third column (which here is called "Dam") , i want to save that row in a matrix called "Dam.one"

Here's my code so far:

```<code>DamType = c( "Dam.one", "Dam.two", "Dam.three", "NoDam.one", "NoDam.two", "NoDam.three")

for (i in 1:120) {
    if (mercury.raw[i,]["Dam"] == 1) {
        if (mercury.raw[i,]["Type"] == 1){
            DamType["Dam.one"] <-  mercury.raw[i,]
}}}
</code>```

This is the first 6 entries of the data set:`

```<code>> mercury.raw
                    Lake Mercury Dam Type
1                ALLEN.P   1.080   1    1
2            ALLIGATOR.P   0.025   1    1
3        A.SAGUNTICOOK.L   0.570   0    2
4      BALCH&STUMP.PONDS   0.770   0    2
5           BASKAHEGAN.L   0.790   1    2
6          BAUNEAG.BEG.L   0.750   0    2
</code>```

I want DamType["Dam.one"]to be equal to:

```<code>                 Lake Mercury Dam Type
1                ALLEN.P   1.080   1    1
2            ALLIGATOR.P   0.025   1    1
</code>```

I don't know what is wrong with it.
Any help is appreciated.

答:
I suggest getting more familiar with R and common packages, such as dplyr.  </p>

```<code>library(dplyr)
dam_grouped <- mercury.raw %>% group_by(Dam)
</code>```

Title: Saving a loop's output in a vector in R

Body:
I have a .cvs file which consists of 4 columns and 120 rows.
I'm attempting to go through every row and where ever i see a "1" in the third column (which here is called "Dam") , i want to save that row in a matrix called "Dam.one"

Here's my code so far:

DamType = c( "Dam.one", "Dam.two", "Dam.three", "NoDam.one", "NoDam.two", "NoDam.three")

for (i in 1:120) {
    if (mercury.raw[i,]["Dam"] == 1) {
        if (mercury.raw[i,]["Type"] == 1){
            DamType["Dam.one"] <-  mercury.raw[i,]
}}}

This is the first 6 entries of the data set:`

> mercury.raw
                    Lake Mercury Dam Type
1                ALLEN.P   1.080   1    1
2            ALLIGATOR.P   0.025   1    1
3        A.SAGUNTICOOK.L   0.570   0    2
4      BALCH&STUMP.PONDS   0.770   0    2
5           BASKAHEGAN.L   0.790   1    2
6          BAUNEAG.BEG.L   0.750   0    2

I want DamType["Dam.one"]to be equal to:

                 Lake Mercury Dam Type
1                ALLEN.P   1.080   1    1
2            ALLIGATOR.P   0.025   1    1

I don't know what is wrong with it.
Any help is appreciated.

Body:
I suggest getting more familiar with R and common packages, such as dplyr.

library(dplyr)
dam_grouped <- mercury.raw %>% group_by(Dam)


问:
On click get input value using jQuery
I have the following:

```<code>$('.checkbox').click(function () {
      console.log(this);
      $.ajax({
        type:'POST',
        url: '/loadProducts',
        data: {},
        success: function(response) {
               console.log(response);
               $('.js-products').html(response);
        }});
    return false;
});
</code>```

Now where I do the console.log(this), it returns:

```<code><div class="ui checkbox checked">
    <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
    <label>Women</label>
</div>
</code>```

How do I get the input name (gender)? And whether the checkbox is checked out or not?

答:
This answer here show you how to retrieve the element by name. However, the tricky part here is that your have brackets within the name itself. So, to get around this, you need to add quotes " around the name like in the following example below.

Once you have the element, you can simple do .prop('checked') to retrieve the current value.

```<code>$('.checkbox').click(function () {
            console.log(this);
            var theValue = $('input[name="gender[women]"]').prop('checked'); //<--HERE IS HOW YOU GET THE VALUE
            console.log(theValue);

            $.ajax({
                type:'POST',
                url: '/loadProducts',
                data: {},
                success: function(response) {
                    console.log(response);
                    $('.js-products').html(response);
                }});
            return false;
        });
</code>```

Title: On click get input value using jQuery

Body:
I have the following:

$('.checkbox').click(function () {
      console.log(this);
      $.ajax({
        type:'POST',
        url: '/loadProducts',
        data: {},
        success: function(response) {
               console.log(response);
               $('.js-products').html(response);
        }});
    return false;
});

Now where I do the console.log(this), it returns:

    <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
    Women

How do I get the input name (gender)? And whether the checkbox is checked out or not?

Body:
This answer here show you how to retrieve the element by name. However, the tricky part here is that your have brackets within the name itself. So, to get around this, you need to add quotes " around the name like in the following example below.

Once you have the element, you can simple do .prop('checked') to retrieve the current value.

$('.checkbox').click(function () {
            console.log(this);
            var theValue = $('input[name="gender[women]"]').prop('checked'); //<--HERE IS HOW YOU GET THE VALUE
            console.log(theValue);

            $.ajax({
                type:'POST',
                url: '/loadProducts',
                data: {},
                success: function(response) {
                    console.log(response);
                    $('.js-products').html(response);
                }});
            return false;
        });


问:
Multiple @Binds with same return class but different key
All the following are used with dagger 2.10 and dagger.android package.

Say I have a class I'd like to inject in multiple activities.

```<code>public class DemoSharedClass {
  Activity activity;

  @Inject public DemoSharedClass(Activity activity) {
    this.activity = activity;
  }
}
</code>```

Then, using the latest Dagger APIs, my classes are defined as

```<code>public class DemoActivity extends DaggerActivity {
  @Inject DemoSharedClass demoSharedClass;

  // ...
}

public class Demo2Activity extends DaggerActivity {
  @Inject DemoSharedClass demoSharedClass;

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

Each activity has its module and subcomponent define as (exactement the same for Demo2Activity)

```<code>@Module(subcomponents = DemoActivitySubcomponent.class)
public abstract class DemoActivityModule {
  @Binds
  @IntoMap
  @ActivityKey(DemoActivity.class)
  abstract AndroidInjector.Factory<? extends Activity>
    bindDemoActivityInjectorFactory(DemoActivitySubcomponent.Builder builder);

  // This is set so SharedClass can be injected using its constructor
  // There is the same in Demo2ActivityModule
  @Binds abstract Activity bindActivity(DemoActivity demoActivity);
}

@Subcomponent
public interface DemoActivitySubcomponent extends AndroidInjector<DemoActivity> {
  @Subcomponent.Builder
  abstract class Builder extends AndroidInjector.Builder<DemoActivity> {}
}
</code>```

Finally, the app component is defined as

```<code>@Component(modules = {
    ApplicationModule.class,
    AndroidInjectionModule.class,
    DemoActivityModule.class,
    Demo2ActivityModule.class,
})
interface DemoApplicationComponent {
  DemoApplication injectApplication(DemoApplication application);
}
</code>```

Now, I get this error when I build the project:

```<code>Error:(11, 11) error: [dagger.android.AndroidInjector.inject(T)] android.app.Activity is bound multiple times:
@Binds android.app.Activity dagger.demo.DemoActivityModule.bindActivity(dagger.demo.DemoActivity)
@Binds android.app.Activity dagger.demo.Demo2ActivityModule.bindActivity(dagger.demo.Demo2Activity)
</code>```

I get the error, and I think this is because they are in the same scope, the app component.

I thought about creating a common module to both DemoSubcomponents which would look something like the following but with similar error.

```<code>@Module
public abstract class SharedClassModule {
  @Binds abstract Activity bindContext(DemoActivity demoActivity);
  @Binds abstract Activity bindContext(Demo2Activity demo2Activity);
}
</code>```

Question: how am I supposed to do it?

答:
You'll need a separate binding on each Subcomponent:

```<code>@Module interface DemoActivitySubcomponentModule {
  @Binds abstract Activity bindContext(DemoActivity demoActivity);
  // ...other bindings unique to DemoActivity and not DemoActivity2
}

@Subcomponent(modules={DemoActivitySubcomponentModule.class})
public interface DemoActivitySubcomponent extends
    AndroidInjector<DemoActivity> {
  @Subcomponent.Builder
  abstract class Builder extends AndroidInjector.Builder<DemoActivity> {}
}
</code>```

Because of @BindsInstance Builder seedInstance(DemoActivity) in AndroidInjector.Builder, which Dagger calls in AndroidInjector.Builder.create() from DispatchingAndroidInjector, Dagger does know how to provide a DemoActivity instance at least. However, there's no built-in binding between DemoActivity and Activity (or Context), so the binding has to be made on the subcomponent instead of the component. By putting the module with that binding on the appropriate @Subcomponent, you can ensure that within each respective subcomponent the Activity binding goes to the correct type that Dagger knows about.

Note that the @Binds @IntoMap @ActivityKey(...) binding in DemoActivityModule still needs to go onto the ApplicationComponent, so the ApplicationComponent can determine which subcomponent to create from the class of the Activity being injected. You specifically want the new DemoActivitySubcomponentModule to go onto DemoActivitySubcomponent so that it makes the Activity-to-DemoActivity in a place where DemoActivity2Subcomponent can't see it.

As a side note, the problem you're seeing is the conflict between the two bindings to Activity, which happen in the same component. It's not quite right to say the same scope, because (though you might choose to add a scope annotation like @ActivityScope to each subcomponent) there is no scope annotation that would help you here. The seedInstance will apply only within each currently-unscoped subcomponent, which will combine with bindings in the ancestor components as well as the subcomponent-specific modules.

Body:
All the following are used with dagger 2.10 and dagger.android package.

Say I have a class I'd like to inject in multiple activities.

public class DemoSharedClass {
  Activity activity;

  @Inject public DemoSharedClass(Activity activity) {
    this.activity = activity;
  }
}

Then, using the latest Dagger APIs, my classes are defined as

public class DemoActivity extends DaggerActivity {
  @Inject DemoSharedClass demoSharedClass;

  // ...
}

public class Demo2Activity extends DaggerActivity {
  @Inject DemoSharedClass demoSharedClass;

  // ...
}

Each activity has its module and subcomponent define as (exactement the same for Demo2Activity)

@Module(subcomponents = DemoActivitySubcomponent.class)
public abstract class DemoActivityModule {
  @Binds
  @IntoMap
  @ActivityKey(DemoActivity.class)
  abstract AndroidInjector.Factory<? extends Activity>
    bindDemoActivityInjectorFactory(DemoActivitySubcomponent.Builder builder);

  // This is set so SharedClass can be injected using its constructor
  // There is the same in Demo2ActivityModule
  @Binds abstract Activity bindActivity(DemoActivity demoActivity);
}

@Subcomponent
public interface DemoActivitySubcomponent extends AndroidInjector<DemoActivity> {
  @Subcomponent.Builder
  abstract class Builder extends AndroidInjector.Builder<DemoActivity> {}
}

Finally, the app component is defined as

@Component(modules = {
    ApplicationModule.class,
    AndroidInjectionModule.class,
    DemoActivityModule.class,
    Demo2ActivityModule.class,
})
interface DemoApplicationComponent {
  DemoApplication injectApplication(DemoApplication application);
}

Now, I get this error when I build the project:

Error:(11, 11) error: [dagger.android.AndroidInjector.inject(T)] android.app.Activity is bound multiple times:
@Binds android.app.Activity dagger.demo.DemoActivityModule.bindActivity(dagger.demo.DemoActivity)
@Binds android.app.Activity dagger.demo.Demo2ActivityModule.bindActivity(dagger.demo.Demo2Activity)

I get the error, and I think this is because they are in the same scope, the app component.

I thought about creating a common module to both DemoSubcomponents which would look something like the following but with similar error.

@Module
public abstract class SharedClassModule {
  @Binds abstract Activity bindContext(DemoActivity demoActivity);
  @Binds abstract Activity bindContext(Demo2Activity demo2Activity);
}

Question: how am I supposed to do it?

Body:
You'll need a separate binding on each Subcomponent:

@Module interface DemoActivitySubcomponentModule {
  @Binds abstract Activity bindContext(DemoActivity demoActivity);
  // ...other bindings unique to DemoActivity and not DemoActivity2
}

@Subcomponent(modules={DemoActivitySubcomponentModule.class})
public interface DemoActivitySubcomponent extends
    AndroidInjector<DemoActivity> {
  @Subcomponent.Builder
  abstract class Builder extends AndroidInjector.Builder<DemoActivity> {}
}

Because of @BindsInstance Builder seedInstance(DemoActivity) in AndroidInjector.Builder, which Dagger calls in AndroidInjector.Builder.create() from DispatchingAndroidInjector, Dagger does know how to provide a DemoActivity instance at least. However, there's no built-in binding between DemoActivity and Activity (or Context), so the binding has to be made on the subcomponent instead of the component. By putting the module with that binding on the appropriate @Subcomponent, you can ensure that within each respective subcomponent the Activity binding goes to the correct type that Dagger knows about.

Note that the @Binds @IntoMap @ActivityKey(...) binding in DemoActivityModule still needs to go onto the ApplicationComponent, so the ApplicationComponent can determine which subcomponent to create from the class of the Activity being injected. You specifically want the new DemoActivitySubcomponentModule to go onto DemoActivitySubcomponent so that it makes the Activity-to-DemoActivity in a place where DemoActivity2Subcomponent can't see it.

As a side note, the problem you're seeing is the conflict between the two bindings to Activity, which happen in the same component. It's not quite right to say the same scope, because (though you might choose to add a scope annotation like @ActivityScope to each subcomponent) there is no scope annotation that would help you here. The seedInstance will apply only within each currently-unscoped subcomponent, which will combine with bindings in the ancestor components as well as the subcomponent-specific modules.


问:
Python code failing to execute in Django app
In 'App1', I created 'Class1' in models.py. Works just fine.

In 'App2', I created 'Class2' in myfile.py, which inherits from 'Class1'. Works just fine.

In 'App3', I created 'Class3' in myfile.py, which inherits from 'Class1'.

In spite of Class3 being identical to Class2 in all but name and location, the code fails to execute. I know this because I slipped in print statements into App2.myfile.py and App3.myfile.py and, while there was output from App2.myfile.py, there was no output from App3.myfile.py.

Note that the myfile.py files are located in the root of their respective app.

Trying to get to the bottom of the problem, created a new project, copied over App1, App2 and App3 and ran it again. This time there no output from either of the print statements at all and - big surprise - my application stopped working.

1) Why is myfile.py failing to execute?

2) How did I get Project1.App2.myfile.py to execute in the first place???

Update:

The code was described accurately, albeit, implicitly. Below is App2.Class2.myfile.py. The code was stripped down to isolate the problem and the other relevant classes are written the same way.

App2.myfile.py:

```<code>print 'before App2.Class2'
class Class2
    pass
print 'after App2.Class2'
</code>```

App2 is a very simple project:

unmodified apps.py file

models.py file containing one model

three python files (one of which is myfile.py) defining classes

empty init.py

There's nothing out of the ordinary in the code I wrote so I've omitted it. If you know a reason why specific code would cause such behavior, tell me.

When the development server is run, Project1.App2 outputs 'before App2.Class2' and 'after App2.Class2'. When copied over to Project2. App2 (the same code) produces no output.

Execution method:

1) run python manage.py runserver

2) observe output in Project1:

```<code>'Performing system checks...

before App2.Class2

after App2.Class2

System check identified no issues'
</code>```

Note the absence of 'before App3.Class2 after App3.Class3'

3) start new Django project (django-admin startproject Project2)

4) copy App1, App2, App3 from Project1 to Project2

5) run (python manage.py runserver)

6) observe output in Project2:

```<code>'Performing system checks...

System check identified no issues'
</code>```

答:
Tip: Reference the definitions in myfile.py in any app that App2 or App3 does not depend upon to prevent circular references. In models.py:

```<code>from App2.myfile import Class2
from App3.myfile import Class3
</code>```

This will force Django to recognize your code.

Protip: Stop wasting your time with the collective incompetence of Stack Overflow. You'll spend more time conforming to their ridiculous question protocols than you will fixing your own problems. Just look at the replies to the original question...

This will be my last contribution to your 'commune'-ity.

Body:
In 'App1', I created 'Class1' in models.py. Works just fine.

In 'App2', I created 'Class2' in myfile.py, which inherits from 'Class1'. Works just fine.

In 'App3', I created 'Class3' in myfile.py, which inherits from 'Class1'.

In spite of Class3 being identical to Class2 in all but name and location, the code fails to execute. I know this because I slipped in print statements into App2.myfile.py and App3.myfile.py and, while there was output from App2.myfile.py, there was no output from App3.myfile.py.

Note that the myfile.py files are located in the root of their respective app.

Trying to get to the bottom of the problem, created a new project, copied over App1, App2 and App3 and ran it again. This time there no output from either of the print statements at all and - big surprise - my application stopped working.

1) Why is myfile.py failing to execute?

2) How did I get Project1.App2.myfile.py to execute in the first place???

Update:

The code was described accurately, albeit, implicitly. Below is App2.Class2.myfile.py. The code was stripped down to isolate the problem and the other relevant classes are written the same way.

App2.myfile.py:

print 'before App2.Class2'
class Class2
    pass
print 'after App2.Class2'

App2 is a very simple project:

unmodified apps.py file

models.py file containing one model

three python files (one of which is myfile.py) defining classes

empty init.py

There's nothing out of the ordinary in the code I wrote so I've omitted it. If you know a reason why specific code would cause such behavior, tell me.

When the development server is run, Project1.App2 outputs 'before App2.Class2' and 'after App2.Class2'. When copied over to Project2. App2 (the same code) produces no output.

Execution method:

1) run python manage.py runserver

2) observe output in Project1:

'Performing system checks...

before App2.Class2

after App2.Class2

System check identified no issues'

Note the absence of 'before App3.Class2 after App3.Class3'

3) start new Django project (django-admin startproject Project2)

4) copy App1, App2, App3 from Project1 to Project2

5) run (python manage.py runserver)

6) observe output in Project2:

'Performing system checks...

System check identified no issues'

Body:
Tip: Reference the definitions in myfile.py in any app that App2 or App3 does not depend upon to prevent circular references. In models.py:

from App2.myfile import Class2
from App3.myfile import Class3

This will force Django to recognize your code.

Protip: Stop wasting your time with the collective incompetence of Stack Overflow. You'll spend more time conforming to their ridiculous question protocols than you will fixing your own problems. Just look at the replies to the original question...

This will be my last contribution to your 'commune'-ity.


问:
How to programmatically create DotNetNuke pages?
I'm working on a DotNetNuke site which will be used as a store.  Each product will have its own DotNetNuke page containing various modules.  I'd like to create a module that will allow an administrator to create new products.

What is the best way to go about this?  How do you programmatically create new DotNetNuke pages, populate them with modules, and configure the modules?

I'm sure this can be done, I just don't know how to get started.

答: I think the easiest thing to do would be to create a page level Template.  Setup a page with all the modules you want on it. Save it / Export it as a template.  Then your user who needs to create a new product clicks Add page.  Make the page. Then just configure the module that has your product / store logic in it.  Should do the trick.</p>

ContentLicense: CC BY-SA 2.5


问:
Limit Javascript COPY Button to a single DIV/Text Area
I am creating a webpage with a various number of scripts in text fields that my team can just click a button to copy whats in the text field so they can paste it into a device to run the script. However, since javascript runs the last script in the HTML code, the buttons all do what the last script says. I need to limit them to the divs the buttons are in. I have added a screenshot to show what it looks like but I am hoping there is a way this can be done.

I have given each of the text areas a name and the script specifically states to call that ID but when I click the button - it will only copy the field of the 3rd DIV

Screenshot of what the page looks like

```<code>    <div class="row">
      <div class="col-md-4 col-sm-4">
       <div class="panel panel-default">
        <div class="panel-heading">
         <b>IAD Config - 2400s ONLY</b>
        </div>

        <div class="panel-body">
         <textarea id="iad" rows="5">
          IAD Config
         </textarea>
        </div>

        <div class="panel-footer">
         <button id="iadcopy">Copy</button>
          <script>
             var input  = document.getElementById("iad");
             var button = document.getElementById("iadcopy");

             button.addEventListener("click", function (event) {
                 event.preventDefault();
                 input.select();
                 document.execCommand("copy");
             });
          </script>
        </div>
       </div>
      </div>

    <div class="row">
      <div class="col-md-4 col-sm-4">
       <div class="panel panel-default">
        <div class="panel-heading">
         <b>ACL</b>
        </div>

        <div class="panel-body">
         <textarea id="acl" rows="5">
          ACL script
         </textarea>
        </div>

        <div class="panel-footer">
         <button id="aclcopy">Copy</button>
          <script>
             var input  = document.getElementById("acl");
             var button = document.getElementById("aclcopy");

             button.addEventListener("click", function (event) {
                 event.preventDefault();
                 input.select();
                 document.execCommand("copy");
             });
          </script>
        </div>
       </div>
      </div>

    <div class="row">
      <div class="col-md-4 col-sm-4">
       <div class="panel panel-default">
        <div class="panel-heading">
         <b>NOC Username</b>
        </div>

        <div class="panel-body">
         <textarea id="noc" rows="5">
          ACL script
         </textarea>
        </div>

        <div class="panel-footer">
         <button id="noccopy">Copy</button>
          <script>
             var input  = document.getElementById("noc");
             var button = document.getElementById("noccopy");

             button.addEventListener("click", function (event) {
                 event.preventDefault();
                 input.select();
                 document.execCommand("copy");
             });
          </script>
        </div>
       </div>
      </div>
</code>```

答:
You were overwriting what input was with your inline javascript (which is usually a bad idea in general).  By making them unique variable names, it copies the correct one.  It would probably be a good idea to refactor this in a more programatic way, using jQuery to select the closest textarea to copy or give each pair the same class name in order to scope the targeting correctly.

Note - because you immediately add an event listener after declaring(and redeclaring button), while your approach isn't the best, it doesn't suffer from the same problems as redeclaring input.

         IAD Config - 2400s ONLY

         <textarea id="iad" rows="5">
          IAD Config
         </textarea>

         <button id="iadcopy">Copy</button>

         ACL

         <textarea id="acl" rows="5">
          ACL script
         </textarea>

         <button id="aclcopy">Copy</button>

         NOC Username

         <textarea id="noc" rows="5">
          ACL script
         </textarea>

         <button id="noccopy">Copy</button>

```

Body:
I am creating a webpage with a various number of scripts in text fields that my team can just click a button to copy whats in the text field so they can paste it into a device to run the script. However, since javascript runs the last script in the HTML code, the buttons all do what the last script says. I need to limit them to the divs the buttons are in. I have added a screenshot to show what it looks like but I am hoping there is a way this can be done.

I have given each of the text areas a name and the script specifically states to call that ID but when I click the button - it will only copy the field of the 3rd DIV

Screenshot of what the page looks like

         IAD Config - 2400s ONLY

         <textarea id="iad" rows="5">
          IAD Config
         </textarea>

         <button id="iadcopy">Copy</button>

         ACL

         <textarea id="acl" rows="5">
          ACL script
         </textarea>

         <button id="aclcopy">Copy</button>

         NOC Username

         <textarea id="noc" rows="5">
          ACL script
         </textarea>

         <button id="noccopy">Copy</button>

Body:
You were overwriting what input was with your inline javascript (which is usually a bad idea in general).  By making them unique variable names, it copies the correct one.  It would probably be a good idea to refactor this in a more programatic way, using jQuery to select the closest textarea to copy or give each pair the same class name in order to scope the targeting correctly.

Note - because you immediately add an event listener after declaring(and redeclaring button), while your approach isn't the best, it doesn't suffer from the same problems as redeclaring input.

 <div class="row">
      <div class="col-md-4 col-sm-4">
       <div class="panel panel-default">
        <div class="panel-heading">
         <b>IAD Config - 2400s ONLY</b>
        </div>

        <div class="panel-body">
         <textarea id="iad" rows="5">
          IAD Config
         </textarea>
        </div>

        <div class="panel-footer">
         <button id="iadcopy">Copy</button>
          <script>
             var input1  = document.getElementById("iad");
             var button = document.getElementById("iadcopy");

             button.addEventListener("click", function (event) {
                 event.preventDefault();
                 input1.select();
                 document.execCommand("copy");
             });
          </script>
        </div>
       </div>
      </div>

    <div class="row">
      <div class="col-md-4 col-sm-4">
       <div class="panel panel-default">
        <div class="panel-heading">
         <b>ACL</b>
        </div>

        <div class="panel-body">
         <textarea id="acl" rows="5">
          ACL script
         </textarea>
        </div>

        <div class="panel-footer">
         <button id="aclcopy">Copy</button>
          <script>
             var input2  = document.getElementById("acl");
             var button = document.getElementById("aclcopy");

             button.addEventListener("click", function (event) {
                 event.preventDefault();
                 input2.select();
                 document.execCommand("copy");
             });
          </script>
        </div>
       </div>
      </div>

    <div class="row">
      <div class="col-md-4 col-sm-4">
       <div class="panel panel-default">
        <div class="panel-heading">
         <b>NOC Username</b>
        </div>

        <div class="panel-body">
         <textarea id="noc" rows="5">
          ACL script
         </textarea>
        </div>

        <div class="panel-footer">
         <button id="noccopy">Copy</button>
          <script>
             var input  = document.getElementById("noc");
             var button = document.getElementById("noccopy");

             button.addEventListener("click", function (event) {
                 event.preventDefault();
                 input.select();
                 document.execCommand("copy");
             });
          </script>
        </div>
       </div>
      </div>


答:
Just create a new dictionary with those keys and use those dictionaries as the keys’ values:</p>

```<code>top_dictionary = {
   'raw_data1': raw_data1,
   'raw_data2': raw_data2,
   'raw_data3': raw_data3
}
</code>```

Title: Creating a superset of Python dictionaries

Body:
I have multiple raw data dictionaries that look like this:

raw_data1 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data2 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data3 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}

I would like to combine these in a top level dictionary such that the key for each element is raw_data1/raw_data2/raw_data3 etc. and the value is the individual dictionary itself. Any thoughts how I can create such a dictionary?

Body:
Just create a new dictionary with those keys and use those dictionaries as the keys’ values:

top_dictionary = {
   'raw_data1': raw_data1,
   'raw_data2': raw_data2,
   'raw_data3': raw_data3
}


答:
Use $(this).find(":checkbox") to get the checkbox. Then you can use .attr('name') to get the name, and .is(":checked") to get whether it's checked.

You shouldn't return false because that prevents clicking on the checkbox from actually changing the box's state.

$('.checkbox').click(function() {
  console.log(this);
  var checkbox = $(this).find(":checkbox");
  var name = checkbox.attr("name");
  var checked = checkbox.is(":checked");
  console.log(name + "is " + (checked ? "" : "not ") + "checked");
  $.ajax({
    type: 'POST',
    url: '/loadProducts',
    data: {},
    success: function(response) {
      console.log(response);
      $('.js-products').html(response);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
  <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
  <label>Women</label>
</div></code>```

Title: On click get input value using jQuery

Body:
Use $(this).find(":checkbox") to get the checkbox. Then you can use .attr('name') to get the name, and .is(":checked") to get whether it's checked.

You shouldn't return false because that prevents clicking on the checkbox from actually changing the box's state.

$('.checkbox').click(function() {
  console.log(this);
  var checkbox = $(this).find(":checkbox");
  var name = checkbox.attr("name");
  var checked = checkbox.is(":checked");
  console.log(name + "is " + (checked ? "" : "not ") + "checked");
  $.ajax({
    type: 'POST',
    url: '/loadProducts',
    data: {},
    success: function(response) {
      console.log(response);
      $('.js-products').html(response);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
  <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
  <label>Women</label>
</div>


问:
WorkFront (AtTask) assign Task
I am having my challenges using WorkFronts API.  My current problem is that I cannot figure out how to use their assign action method.  WorkFront's documentation says that the assign method accepts two arguments; objID and objCode.  Below is what I have currently.  I have tried other URL's, but I keep getting the same error message.  The error that is being returned is NullPointerException.  If anybody could help that would be great.  Also if you happen to have working examples that you could pass my way or some kind of documentation.  I have these two URL's; https://developers.workfront.com/api-docs/ and https://developers.workfront.com/api-docs/api-explorer/.  The API Explorer API shows you the assign action method on the Task object.</p>

```<code>    using (var apiManagementSystem = new HttpClient())
    {
        apiManagementSystem.BaseAddress = new Uri("https://xxxxxxx.preview.workfront.com/attask/api/");
        apiManagementSystem.DefaultRequestHeaders.Clear();

        var jsonMediaType = new MediaTypeWithQualityHeaderValue("application/json");
        apiManagementSystem.DefaultRequestHeaders.Accept.Add(jsonMediaType);
        apiManagementSystem.DefaultRequestHeaders.Add("SessionID", _sessionID);

        HttpContent httpContent = null;
        responseMessage = apiManagementSystem.PutAsync("v6.0/TASK/TASKID/assign?objID=TASKID&objCode=TASK&apiKey=ApiKey", httpContent).Result;

    }
</code>```

答:
You need to invoke the assign method under the object that you wish assign an object to (the work) to and then provide as arguments the ID and type of the object that you are assigning (the worker).

For example: <baseurl>/task/<taskID>/assign?objID=<userID>&objCode=USER

The above snippet would assign the user specified by userID to the task specified by taskID. Ensure that you pass the call as a PUT method.

Valid assignee object types are: users, roles, or teams.

Title: WorkFront (AtTask) assign Task

Body:
I am having my challenges using WorkFronts API.  My current problem is that I cannot figure out how to use their assign action method.  WorkFront's documentation says that the assign method accepts two arguments; objID and objCode.  Below is what I have currently.  I have tried other URL's, but I keep getting the same error message.  The error that is being returned is NullPointerException.  If anybody could help that would be great.  Also if you happen to have working examples that you could pass my way or some kind of documentation.  I have these two URL's; https://developers.workfront.com/api-docs/ and https://developers.workfront.com/api-docs/api-explorer/.  The API Explorer API shows you the assign action method on the Task object.

    using (var apiManagementSystem = new HttpClient())
    {
        apiManagementSystem.BaseAddress = new Uri("https://xxxxxxx.preview.workfront.com/attask/api/");
        apiManagementSystem.DefaultRequestHeaders.Clear();

        var jsonMediaType = new MediaTypeWithQualityHeaderValue("application/json");
        apiManagementSystem.DefaultRequestHeaders.Accept.Add(jsonMediaType);
        apiManagementSystem.DefaultRequestHeaders.Add("SessionID", _sessionID);

        HttpContent httpContent = null;
        responseMessage = apiManagementSystem.PutAsync("v6.0/TASK/TASKID/assign?objID=TASKID&objCode=TASK&apiKey=ApiKey", httpContent).Result;

    }


问:
Create Large CSV data using Google Cloud Dataflow
I need to create a large csv file of ~ 2 billion records with header. It takes a long time to create using standalone script however since records are not related , I understand Cloud dataflow can make it distributed spinning up multiple worker GCE machines of my choice. Does cloud dataflow always need to have an input. Here I am trying to programmatically generate data of following format

```<code>ItemId,   ItemQuantity, ItemPrice, Salevalue, SaleDate
item0001, 25          , 100      , 2500      , 2017-03-18
item0002, 50          , 200      , 10000     , 2017-03-25
</code>```

Note

ItemId can be postfixed with any random number between 0001 to 9999 ItemQuantity can be random value between (1 to 1000) ItemPrice can be random value between (1 to 100)  SaleValue = ItemQuantity*ItemPrice Date between 2015-01-01 to 2017-12-31

Any language is fine.

Continueing from question Generating large file using Google Cloud Dataflow

答:
Currently, there is not a very elegant way of doing this. In Python you would do this (same thing for Java, just the syntax changes):

```<code>def generate_keys():
  for i in range(2000):
    # Generate 2000 key-value pairs to shuffle
    yield (i, 0)

def generate_random_elements():
  for i in range(1000000):
    yield random_element()

p = beam.Pipeline(my_options)
(p
 | beam.Create(['any'])
 | beam.FlatMap(generate_keys)
 | beam.GroupByKey()
 | beam.FlatMap(generate_random_elements)
 | beam.WriteToText('gs://bucket-name/file-prefix'))
</code>```

In generate_keys() we are generating 2000 different keys, and then we run GroupByKey so that they will be shuffled to different workers. We need to do this, because the DoFn can not currently be split across several workers. (Once SplittableDoFn is implemented, this will be much easier).

As a note, when Dataflow writes results out to sinks, it commonly separates them into different files (e.g. gs://bucket-name/file-prefix-0000-00001, and so on), so you'll need to condense the files together.

Also, you can use --num_workers 10, or however many to spawn in Dataflow, or use autoscaling.

Body:
I need to create a large csv file of ~ 2 billion records with header. It takes a long time to create using standalone script however since records are not related , I understand Cloud dataflow can make it distributed spinning up multiple worker GCE machines of my choice. Does cloud dataflow always need to have an input. Here I am trying to programmatically generate data of following format

ItemId,   ItemQuantity, ItemPrice, Salevalue, SaleDate
item0001, 25          , 100      , 2500      , 2017-03-18
item0002, 50          , 200      , 10000     , 2017-03-25

Note

ItemId can be postfixed with any random number between 0001 to 9999 ItemQuantity can be random value between (1 to 1000) ItemPrice can be random value between (1 to 100)  SaleValue = ItemQuantity*ItemPrice Date between 2015-01-01 to 2017-12-31

Any language is fine.

Continueing from question Generating large file using Google Cloud Dataflow

Body:
Currently, there is not a very elegant way of doing this. In Python you would do this (same thing for Java, just the syntax changes):

def generate_keys():
  for i in range(2000):
    # Generate 2000 key-value pairs to shuffle
    yield (i, 0)

def generate_random_elements():
  for i in range(1000000):
    yield random_element()

p = beam.Pipeline(my_options)
(p
 | beam.Create(['any'])
 | beam.FlatMap(generate_keys)
 | beam.GroupByKey()
 | beam.FlatMap(generate_random_elements)
 | beam.WriteToText('gs://bucket-name/file-prefix'))

In generate_keys() we are generating 2000 different keys, and then we run GroupByKey so that they will be shuffled to different workers. We need to do this, because the DoFn can not currently be split across several workers. (Once SplittableDoFn is implemented, this will be much easier).

As a note, when Dataflow writes results out to sinks, it commonly separates them into different files (e.g. gs://bucket-name/file-prefix-0000-00001, and so on), so you'll need to condense the files together.

Also, you can use --num_workers 10, or however many to spawn in Dataflow, or use autoscaling.


问:
Append or remove data from JSON
The result i want to get:

```<code>[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]
</code>```

To add new data to JSON i tried this:

```<code>String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);
</code>```

But i don't get a proper result.

And how to remove a JSON data depend on the value of the ID ?

Thank's.

答:
The root object of the json is an array so you should use a JSONArray, not a JSONObject.

```<code>String jsonDataString = ALL MY JSON DATA HERE;
JSONArray mainObject = new JSONArray(jsonDataString);
JSONObject valuesObject = new JSONObject();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
mainObject.put(valuesObject);
</code>```

Title: Append or remove data from JSON

Body:
The result i want to get:

[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]

To add new data to JSON i tried this:

String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);

But i don't get a proper result.

And how to remove a JSON data depend on the value of the ID ?

Thank's.

Body:
The root object of the json is an array so you should use a JSONArray, not a JSONObject.

String jsonDataString = ALL MY JSON DATA HERE;
JSONArray mainObject = new JSONArray(jsonDataString);
JSONObject valuesObject = new JSONObject();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
mainObject.put(valuesObject);


问:
How to check if variable is defined?
I building E-shop and there will be diferent products categories, so each category product can have diferent columns. For example one product have color, other product from other category don't have color.
I want to do when I adding new product for which don't need use color column I want that in show page, this line below will be not displaying (Color:).

```<code><p>
  <strong>Color:</strong>
  <%= @product.color %>
</p>
</code>```

Product show.html.erb

```<code>  <p>
    <strong>Name:</strong>
    <%= @product.name %>
  </p>
  <br>
  <p>
    <strong>Description:</strong>
    <%= @product.description %>
  </p>
  <br>
  <p>
    <strong>Year of manufacture:</strong>
    <%= @product.year_of_manufacture %>
  </p>
  <br>
  <p>
   <strong>Color:</strong>
   <%= @product.color %>
 </p>
</code>```

Product form.html.erb

```<code>  <div class="form-group">
    <%= f.label :name %><br>
    <%= f.text_field :name, class: "form-control" %>
  </div>
  <br>
  <div class="form-group">
    <%= f.label :description %>
    <%= f.text_area :description, class: "form-control" %>
  </div>
  <br>
  <div class="form-group">
  <%= f.label :year_of_manufacture %>
  <%= f.text_field :year_of_manufacture, class: "form-control" %>
  </div>
  <br>
  <div class="form-group">
  <%= f.label :color %>
  <%= f.text_field :color, class: "form-control" %>
  </div>
</code>```

Thank you for help.

答:
In ruby, you can use respond_to? to see if you can call a method on a particular object. There's really no such thing as an "undefined variable" because variables like @foo and @blah are nil by default, and anything that follows a . is technically a method in ruby (such as @product.color)

Anyway, try this code:

```<code><% if @product.respond_to?(:color) && @product.color.present? %>
  <p>
    <strong>Color:</strong>
    <%= @product.color %>
  </p>
<% end %>
</code>```

Title: How to check if variable is defined?

Body:
I building E-shop and there will be diferent products categories, so each category product can have diferent columns. For example one product have color, other product from other category don't have color.
I want to do when I adding new product for which don't need use color column I want that in show page, this line below will be not displaying (Color:).

  Color:
  <%= @product.color %>

Product show.html.erb

    Name:
    <%= @product.name %>

    Description:
    <%= @product.description %>

    Year of manufacture:
    <%= @product.year_of_manufacture %>

   Color:
   <%= @product.color %>

Product form.html.erb

    <%= f.label :name %>

    <%= f.text_field :name, class: "form-control" %>

    <%= f.label :description %>
    <%= f.text_area :description, class: "form-control" %>

  <%= f.label :year_of_manufacture %>
  <%= f.text_field :year_of_manufacture, class: "form-control" %>

  <%= f.label :color %>
  <%= f.text_field :color, class: "form-control" %>

Thank you for help.

Body:
In ruby, you can use respond_to? to see if you can call a method on a particular object. There's really no such thing as an "undefined variable" because variables like @foo and @blah are nil by default, and anything that follows a . is technically a method in ruby (such as @product.color)

Anyway, try this code:

<% if @product.respond_to?(:color) && @product.color.present? %>
  <p>
    <strong>Color:</strong>
    <%= @product.color %>
  </p>
<% end %>


问:
Sigaction usage and interpretation
I am using sigaction for a signal and I am using a simple struct for that. I actually took it from the man page. Can someone explain to me what does the second line in the struct do? Also there is an error there:</p>

```<code>error: expected declaration specifiers or '...' before 'siginfo_t'

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <assert.h>
#include <getopt.h>

#include <signal.h>
#include <sys/time.h>

#define _POSIX_C_SOURCE 200112L
#define MAX_WORD 256

void parseFile (FILE * fp, FILE *sketcher);
void handle_timeout(int signal);

struct sigaction {
 void     (*sa_handler)(int);
    void     (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t   sa_mask;
    int      sa_flags;
    void     (*sa_restorer)(void);
};
</code>```

答:
You are not supposed to declare the struct sigaction yourself.  It is provided in the man page for your information, but it is actually declared by <signal.h>.

The second line in the struct defines a function pointer (as does the first, but with a different type).

Title: Sigaction usage and interpretation

Body:
I am using sigaction for a signal and I am using a simple struct for that. I actually took it from the man page. Can someone explain to me what does the second line in the struct do? Also there is an error there:

error: expected declaration specifiers or '...' before 'siginfo_t'

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <assert.h>
#include <getopt.h>

#include <signal.h>
#include <sys/time.h>

#define _POSIX_C_SOURCE 200112L
#define MAX_WORD 256

void parseFile (FILE * fp, FILE *sketcher);
void handle_timeout(int signal);

struct sigaction {
 void     (*sa_handler)(int);
    void     (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t   sa_mask;
    int      sa_flags;
    void     (*sa_restorer)(void);
};


问:
301 Redirect Best Practices - multiple sites to single site
I have around 15+ sites, and we want to drop these sites and merge them into only one site (create pages for each one in the new site).

The 15+ site's domains should be redirected to one site as below:

```<code>a.com -> z.com/a
b.com -> z.com/b
c.com -> z.com/c
..
</code>```

Also, we want to redirect (301) page by page from the old domains to the new the new domain to keep the page's ranking:

```<code> a.com/about-us     -> z.com/a/about-us
 b.com/about/abouus -> z.com/b/about-s
 c.com/contactus    -> z.com/c/contact-us
</code>```

Each one of the 15+ sites is running on its own server with a different platform while the new server is IIS.

Currently, I'm thinking of two approaches:

Point the old DNS records to the new server of z.com, and handle all the redirects on the server.

Keep the old site running, and configure redirect rules on each server to redirect each page to the matching page on the new site.

Which approach is better, any other approaches? So far I think the first approach is better since we will control all the redirects in one place - but from the performance wise, is it going to add more headache on the server?

答:
I think eventually you'll have to shutdown all the other sites as in the long term unlikely does it make sense to keep 15 sites running just to do the redirects.

So as I understand the question is rather on how to better organize the migration to the new system in the short term. So here are my thoughts on this:

how huge is your system

what's your QPS?

how many pages do you have across your sites farm?

do you need to remap URLS for a decent amount of pages?

what's the migration procedure? Will you switch your sites one-by-one or it's technically infeasible and they all need to be swtiched over at once?

If we're talking about a system handling 10 QPS and 1K pages or about a system handling
50K QPS and having 1B pages we need to dynamically remap system load may be a concern and p.2 may look better

rollbacks

note that DNS records can be cached by intermediate servers and if you need to quickly rollback to the previous version if something goes wrong it can be an issue

what kind of systems do you have

Is it actually possible to easily extract URLs from 15 diverse systems and put them to a single point without a risk to lose something valuable?

ease of maintenance

At first glance the first approach looks easier from the maintenance perspective, but I don't know what kind of system you use and how complex the redirection rules need to be.
If they are complex dynamic ones like a.com/product.php?id=1 => z.com/a/iPhone6S moving millions of such urls to a single point could be tricky

SEO

I don't follow the industry closely, but a few years ago both would work ok. I think it's worth consulting those keeping up to date with this industry - it changes very rapidly

Body:
I have around 15+ sites, and we want to drop these sites and merge them into only one site (create pages for each one in the new site).

The 15+ site's domains should be redirected to one site as below:

a.com -> z.com/a
b.com -> z.com/b
c.com -> z.com/c
..

Also, we want to redirect (301) page by page from the old domains to the new the new domain to keep the page's ranking:

 a.com/about-us     -> z.com/a/about-us
 b.com/about/abouus -> z.com/b/about-s
 c.com/contactus    -> z.com/c/contact-us

Each one of the 15+ sites is running on its own server with a different platform while the new server is IIS.

Currently, I'm thinking of two approaches:

Point the old DNS records to the new server of z.com, and handle all the redirects on the server.

Keep the old site running, and configure redirect rules on each server to redirect each page to the matching page on the new site.

Which approach is better, any other approaches? So far I think the first approach is better since we will control all the redirects in one place - but from the performance wise, is it going to add more headache on the server?


问:
The last symbol in array of type 'char' c++
I have an array of type 'char' with the last symbol '\0'.

```<code>#include<iostream>

void main()
{
    char a[4];

    a[0] = 'r';
    a[1] = 'r';
    a[2] = 'r';
    a[3] = '\0';

     for (int i = 0; i < 6; i++)
     {
         cout << a[i];
     }
     cout << endl;
 }
</code>```

So, when I try to output more symbols than this array has, It prints random symbols after '\0' symbol.

Output:

```<code>rrr ╠╠
</code>```

My question is: how can I create my array with no symbols after '\0' symbol ?

答:
First of all, the size ff this array is 4, so when you try to access any element out of range, you read a random memory.

Secondly, '\0' character is a string terminating symbol. You don't need to clear all of the elements followed by it. All of the standard  IO functions will not write after '\0'.
You can try:

```<code>cout << a;
</code>```

Without any loops.

Body:
I have an array of type 'char' with the last symbol '\0'.

#include<iostream>

void main()
{
    char a[4];

    a[0] = 'r';
    a[1] = 'r';
    a[2] = 'r';
    a[3] = '\0';

     for (int i = 0; i < 6; i++)
     {
         cout << a[i];
     }
     cout << endl;
 }

So, when I try to output more symbols than this array has, It prints random symbols after '\0' symbol.

Output:

rrr ╠╠

My question is: how can I create my array with no symbols after '\0' symbol ?

Body:
First of all, the size ff this array is 4, so when you try to access any element out of range, you read a random memory.

Secondly, '\0' character is a string terminating symbol. You don't need to clear all of the elements followed by it. All of the standard  IO functions will not write after '\0'.
You can try:

cout << a;

Without any loops.


问:
plpgpsql - differents forms of temporary table in order to do a sort
I'm trying to optimize a function that has 7 WITH temporary tables, acting as sort mechanisms, cascading from the initial temporary table/sort to the next one until the last one e.g the 7th temporary table/ sort.

Gist here: This kind of code must be forbidden.

I'm trying to replace the WITH sort with a real temporary table e.g CREATE TEMPORARY TABLE <table_name> AS SELECT col1 FROM another_table;. The aim is to increase performance as the query in its current form is very very slow.

This is the change I've proposed

```<code>CREATE OR REPLACE FUNCTION report.get_sa001(
  IN "date_D" timestamp without time zone,
  IN "date_F" timestamp without time zone,
  IN frequence integer)
RETURNS TABLE(
  "Period_date" timestamp without time zone,
  "Site" character varying,
  "Customer_code" character varying,
  "Internal_reference" character varying,
  "InvoiceNumber" character varying,
  "Value_in_currency" numeric,
  "Value_in_EUR" numeric,
  "Value_Budget_in_EUR" numeric,
  "Selling_price_CUR" numeric,
  "Selling_price_EUR" numeric,
  "Currency_code" character varying,
  "Selling_quantity" numeric,
  "Variance_price_CUR" numeric,
  "Variance_price_EUR" numeric,
  "Variance_value_CUR" numeric,
  "Variance_value_EUR" numeric,
  "Selling_date" timestamp without time zone) AS

$BODY$
DECLARE
  p_debut timestamp without time zone;
DECLARE
  p_fin timestamp without time zone;
BEGIN
  p_debut = dw.get_period_end("date_D", "frequence");
  p_fin = dw.get_period_end("date_F", "frequence");

  RETURN QUERY
    CREATE TEMPORARY TABLE "dates_1" AS
      SELECT
        p_debut::date + n AS "date",
        dw.period_frequency(p_debut::date + n) AS "frequency"
      FROM generate_series(0, p_fin::date - p_debut::date) AS x(n)
      WHERE (dw.period_frequency(p_debut::date + n) & frequence != 0);

  SELECT * FROM "dates_1"; -- Thanks to Vao Tsun
END;
$BODY$
  LANGUAGE plpgsql STABLE
  COST 100
  ROWS 1000;
</code>```

The creation of the function is fine but when running the function this way

```<code>SELECT * FROM report.get_sa001('2017-01-01'::date, '2017-01-31'::date, 32)
</code>```

This is what I have

```<code> ERROR: cannot open query CREATE TABLE AS like cursor
 État SQL :42P11
 Contexte : fonction PL/pgsql report.get_sa001(timestamp without time  zone,timestamp without time zone,integer), ligne 11 à RETURN QUERY
</code>```

I tried to replace the CREATE TEMPORARY TABLE with a SELECT * INTO TEMPORARY TABLE. The creation is ok again but I have the same error when running it.

Checking SO's archive, it sounds PLPGSQL forbids using temporary table (check here).

If you have any ideas, they are more than welcomed.

Thanks

答:
there is nothing wrong with using create temporary table in function:

```<code>t=# create or replace function so37() returns table (i int) as
$$
declare
begin
create temporary table a as select 2;
return query select * from a;
end;
$$ language plpgsql
;
CREATE FUNCTION
t=# select * from so37();
 i
---
 2
(1 row)
</code>```

but they have to be maintained, eg in your in current example you lack drop table if exists, or instead of create table you should insert into, because if you don't, second run will fail:

```<code>t=# select * from so37();
ERROR:  relation "a" already exists
CONTEXT:  SQL statement "create temporary table a as select 2"
PL/pgSQL function so37() line 4 at SQL statement
</code>```

And I believe CTE is a better alternative to creating temporary table in functions...

Body:
I'm trying to optimize a function that has 7 WITH temporary tables, acting as sort mechanisms, cascading from the initial temporary table/sort to the next one until the last one e.g the 7th temporary table/ sort.

Gist here: This kind of code must be forbidden.

I'm trying to replace the WITH sort with a real temporary table e.g CREATE TEMPORARY TABLE <table_name> AS SELECT col1 FROM another_table;. The aim is to increase performance as the query in its current form is very very slow.

This is the change I've proposed

CREATE OR REPLACE FUNCTION report.get_sa001(
  IN "date_D" timestamp without time zone,
  IN "date_F" timestamp without time zone,
  IN frequence integer)
RETURNS TABLE(
  "Period_date" timestamp without time zone,
  "Site" character varying,
  "Customer_code" character varying,
  "Internal_reference" character varying,
  "InvoiceNumber" character varying,
  "Value_in_currency" numeric,
  "Value_in_EUR" numeric,
  "Value_Budget_in_EUR" numeric,
  "Selling_price_CUR" numeric,
  "Selling_price_EUR" numeric,
  "Currency_code" character varying,
  "Selling_quantity" numeric,
  "Variance_price_CUR" numeric,
  "Variance_price_EUR" numeric,
  "Variance_value_CUR" numeric,
  "Variance_value_EUR" numeric,
  "Selling_date" timestamp without time zone) AS

$BODY$
DECLARE
  p_debut timestamp without time zone;
DECLARE
  p_fin timestamp without time zone;
BEGIN
  p_debut = dw.get_period_end("date_D", "frequence");
  p_fin = dw.get_period_end("date_F", "frequence");

  RETURN QUERY
    CREATE TEMPORARY TABLE "dates_1" AS
      SELECT
        p_debut::date + n AS "date",
        dw.period_frequency(p_debut::date + n) AS "frequency"
      FROM generate_series(0, p_fin::date - p_debut::date) AS x(n)
      WHERE (dw.period_frequency(p_debut::date + n) & frequence != 0);

  SELECT * FROM "dates_1"; -- Thanks to Vao Tsun
END;
$BODY$
  LANGUAGE plpgsql STABLE
  COST 100
  ROWS 1000;

The creation of the function is fine but when running the function this way

SELECT * FROM report.get_sa001('2017-01-01'::date, '2017-01-31'::date, 32)

This is what I have

 ERROR: cannot open query CREATE TABLE AS like cursor
 État SQL :42P11
 Contexte : fonction PL/pgsql report.get_sa001(timestamp without time  zone,timestamp without time zone,integer), ligne 11 à RETURN QUERY

I tried to replace the CREATE TEMPORARY TABLE with a SELECT * INTO TEMPORARY TABLE. The creation is ok again but I have the same error when running it.

Checking SO's archive, it sounds PLPGSQL forbids using temporary table (check here).

If you have any ideas, they are more than welcomed.

Thanks

Body:
there is nothing wrong with using create temporary table in function:

t=# create or replace function so37() returns table (i int) as
$$
declare
begin
create temporary table a as select 2;
return query select * from a;
end;
$$ language plpgsql
;
CREATE FUNCTION
t=# select * from so37();
 i
---
 2
(1 row)

but they have to be maintained, eg in your in current example you lack drop table if exists, or instead of create table you should insert into, because if you don't, second run will fail:

t=# select * from so37();
ERROR:  relation "a" already exists
CONTEXT:  SQL statement "create temporary table a as select 2"
PL/pgSQL function so37() line 4 at SQL statement

And I believe CTE is a better alternative to creating temporary table in functions...