text:
Q: twilio php : gather information from user I want to store credit card information from user using twilio.
I have used these code to do so.
once the user enter card number , I want after gathering 16 digits , it should move to ask cvv from user
code:
<?php

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>

<Response>
 <Gather numdigits="16" action="gather1.php" method="GET">
   <Say>
            Please enter your account number,
            followed by the pound sign
    </Say>
    </Gather>

    <Gather numdigits="3" action="gather2.php" method="GET">
   <Say>
            Please enter your cvv  number,
            followed by the pound sign
    </Say>
    </Gather>

    <Gather numdigits="2" action="gather3.php" method="GET">
   <Say>
            Please enter your card expiration month,
            followed by the pound sign
    </Say>
    </Gather>
    <Gather numdigits="4" action="gather4.php" method="GET">
   <Say>
            Please enter your card expiration year,
            followed by the pound sign
    </Say>
    </Gather>

    <Say>We didn't receive any input. Goodbye!</Say>

</Response>

gather:php
      <?php

    // page located at http://example.com/process_gather.php
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response><Say>You entered " . $_REQUEST['Digits'] . "</Say>        </Response>";
?>
<response>
<say>
<Gather numDigits="1"  action="gather_handle.php" method="POST">
If the above information is correct, please press 1."
If the above information is not correct,please press 2.
</Gather>
</say>
</response>


text:
Q: Correct http verb to use for login API What would be the "correct HTTP verb" to use when developing a RESTful API to handle login information? This API would be accessible from various devices/platforms - mobile app, desktop web app, desktop native app, etc.

A: I assume that by API Login you mean a way to authenticate an API user and any calls to your API endpoints.
You could probably use OAuth or Basic Authentication to do that or let say you have an API endpoint at api\authenticate. The caller would POST to this endpoint with userID and password or some API key. The service would then return a cookie or authentication token that would be sent with every call to other API endpoints. The HP Cloud Identity service works pretty much the same way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to privately reference another project from a NuGet package? I'm looking for a way to 'privately' reference an MSBuild project so that it won't be shown to the user of the NuGet package. For example, suppose I have two libraries, LibFoo and LibBar. They're organized under a single solution, like this:
Foobar.sln
|
---- LibFoo.csproj
|
---- LibBar.csproj

Now, suppose LibFoo references LibBar. When I go to build LibFoo, LibBar is built as well. The resulting binaries are both included in LibFoo's output directory. When I nuget pack them and include everything in the directory as part of the NuGet package, LibBar's binaries are included as well.
Finally, when the end-user installs LibFoo, NuGet goes ahead and references everything in the package, including LibBar.
Is there any way to prevent this from happening?

A: I guess it is not possible to exclude a dll directly but you can specify explicitly which assemblies should be referenced. This in turn does what you want since all not specified assemblies won't be added as a reference.
Have a look at this section of the nuget docs.


text:
Q: Gulp uglify breaking angular application When trying to use gulp-ugily with my angular application, it is breaking, even though I am running it through gulp-ngmin.
Here is the gulp file:
var gulp = require('gulp'),
    concat = require('gulp-concat'),
    ngmin = require('gulp-ngmin'),
    uglify = require('gulp-uglify');

gulp.task('compress', function() {
    gulp.src('client/js/source/*.js')
        .pipe(concat('app.js'))
        .pipe(ngmin())
        .pipe(uglify())
        .pipe(gulp.dest('client/js'));
});

A: It helps to disable the mangle option in uglify, for it's messing with all the injection stuff and naming.
.pipe(uglify({ mangle: false }))

A: Maybe answering this for future users, as it seems the post is old.
Use ng-annotate to fix AngularJS problems when uglifying. Install it as any other library:
npm install gulp-ng-annotate --save-dev

And then use this in your gulpfile.js:
var gulp = require('gulp')
var concat = require('gulp-concat')
var uglify = require('gulp-uglify')
var ngAnnotate = require('gulp-ng-annotate')

gulp.task('js', function () {
  gulp.src(['src/**/module.js', 'src/**/*.js'])
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(gulp.dest('.'))
})

Hope this helped!
Source: https://medium.com/@dickeyxxx/best-practices-for-building-angular-js-apps-266c1a4a6917


text:
Q: "Recovering Dual Boot System with Missing Bootloader and 'grub_efi_secure_boot' Error" I am having an issue with my dual boot system, which consists of Parrot OS and Windows. Recently, I had a problem with my system boot order where it was showing "operating system could not be loaded because required file is missing or contains errors." The issue occurred because I did not properly shut down my laptop and did not charge it. I checked my UEFI boot order and it was showing Parrot and Windows bootloader, but after two shut downs it was only showing Windows. I tried to use the bcdedit command to create a copy of the Windows boot loader and edit it to point to the Parrot EFI, but it still showed the same error.
when i did the bcdedit command it shows parrot in the windows boot manager but when i selected it the output was this
I then tried to install another copy of Parrot OS alongside it, but it is not showing up in the UEFI boot order. Now, I have to manually select the EFI and load the GRUB file to enter the new OS. I am wondering if it is possible to recover my first Parrot OS and if it is possible to make the new OS show up again in the boot order. I also tried to get into the old Parrot OS by using the recovery mode in the new Parrot OS (GRUB command line), but it showed an error message saying command 'grub_efi_secure_boot' not found.

Can anyone help me sort out this issue?
i also used boot repair tool and it generated a report
https://paste.ubuntu.com/p/VkBjvBGFSn/


text:
Q: How to serve static files from the Snap monad? I have this Snap site with one top-level location:
snapSite :: Snap ()
snapSite = do
    ifTop myHomeHandler

In addition to this, how can I serve static files only if the request path ends with ".css" or ".txt"?
I noticed there is a pathWith function in Snap.Internal.Core that could work, but I'm not sure how to fit it into the Snap monad above.

A: "Snap.Util.FileServe [c]ontains web handlers to serve files from a directory."
The route will look something like this:
("/static", serveDirectory "static_directory_name")

For fine-tuning this process you can also use your own DirectoryConfig and use serveDirectoryWith.


text:
Q: Query is really annoying me I can't get my head around it I am new to SQL and I have the the following erd:

The query I am looking to perform is:
What quantity of vehicles can be used to service shipment x?|
Any Ideas??
I have:
select count(VehicleType) from Vehicle where in
 (select VEHICLETYPE, SHIPMENT_TYPE from can_carry
 where SHIPMENT_TYPE in
 (select SHIPMENT_TYPE from Shipment where ContractNo = x and ShipmentNo = x  );

but I feel like it is wrong

A: You havent a VEHICLETYPE in first condition and one missing ).
So this is valid your valid SQL:
select count(VehicleType) from Vehicle where VEHICLETYPE in
(select VEHICLETYPE, SHIPMENT_TYPE from can_carry
 where SHIPMENT_TYPE in
 (select SHIPMENT_TYPE from Shipment where ContractNo = x and ShipmentNo = x))

But this SQL is PERFKILLER! :)
I mean that you selecting 3 sets of results! So this will have a horrible execution plan.
You can write a better query with using JOIN. More about execution plans here.


text:
Q: Difference between build and "assign" for a child association? I'm curious what the difference is between using "build" or just directly assigning a child for associations?
Assume I have a @user instance already, and I just want to create the child association to an organization:
Approach 1:
@organization = Organization.new
@organization.build_user(@user.attributes)

Approach 2:
@organization = Organization.new
@organization.user = @user

Both do the same thing, right?

A: If an Organization has a User, then assigning an association directly requires @user to be a User object to work or else it's prone to throwing an error. build handles the association and sets the foreign keys automatically. e.g.
Will work:
@organization.build_user({username: "User"})

Will work:
@organization.user = User.new(username: "User")

Won't work:
@organization.user = {username: "User"}


text:
Q: Jersey REST client following URI returned in previous response I am using the Jersey Client API (2.0) to interact with a web service.  One of the calls results in a json object that has a 'next' value.  This value points at the resource that we should query to obtain the next set of items in a long list.
{
  "results":[.....]
  "next":"/path/to/next/resource?someparam=someval&etc"
}

I'm wondering if there is a clean way to target this new URL...  Yes, I can parse the URL to get the query portion of it, then break apart each parameter and then reverse the process to configure the WebTarget, but this seems like a lot of additional work given that I've already got the URL that I need to hit.
I've tried just passing the above into the path() method, but that doesn't work b/c JerseyWebTarget encodes the path.
If it matters, I do want to still inherit the filters/etc... from the source WebTarget.
So I'm looking for something like this:
WebTarget source = ....;
ListResult listResult = source.request().get();
display(listResult);
while (listResult.hasNext()){
  listResult = source.path(listResult.getNextUrl()).request().get();
  display(listResult);
}

but where the path() call allows passing of the full relative URL...
EDIT - add example:
For reference, here is what I've had to do to make this work (if the URL contains more than just a relative path and a query parameter string, it will break):
    String nextUrl = previous.getNextUrl();
    int qPos = nextUrl.indexOf('?');
    int pathLen = qPos >= 0 ? qPos : nextUrl.length();

    WebTarget nextTarget = rootWebTarget.path(nextUrl.substring(0, pathLen));
    if (qPos > 0){
        MultivaluedMap<String, String> params = UriComponent.decodeQuery(nextUrl.substring(qPos+1), true);

        for(Map.Entry<String, List<String>> entry : params.entrySet()){
            nextTarget = nextTarget.queryParam(entry.getKey(), entry.getValue().toArray());
        }

    }


text:
Q: Trigger.io on iOS 7 hangs at launch image I just updated my trigger.io app to use the latest stable platform version (v2.0.1) so that it would hopefully work well on iOS 7. Unfortunately now it hangs on the launch image. The error I get on the iPhone console is below. Any ideas on how to get this working?
Oct  1 19:52:42 Strax mobile_installation_proxy[235] <Warning>: LaunchServices: Please include the kCFBundleIdentifierKey in the options dictionary when installing an app.
Oct  1 19:52:42 Strax mobile_installation_proxy[235] <Warning>: LaunchServices: installing app for existing placeholder (null)
Oct  1 19:52:42 Strax installd[62] <Notice>: 0x25d000 handle_install_for_ls: Install of "/var/mobile/Media/PublicStaging/device-ios.app" requested by mobile_installation_proxy
Oct  1 19:52:42 Strax installd[62] <Notice>: 0x25d000 MobileInstallationInstall_Server: Installing app com.redacted.redacted
Oct  1 19:52:43 Strax securityd[79] <Error>: OCSPResponse: now > latestNextUpdate
Oct  1 19:52:43 Strax SpringBoard[33] <Warning>: Killing com.redacted.redacted for termination assertion
Oct  1 19:52:43 Strax installd[62] <Notice>: 0x25d000 install_application: Performing developer delta patch
Oct  1 19:52:43 Strax com.apple.launchd[1] (UIKitApplication:com.redacted.redacted[0x9168][331]) <Notice>: (UIKitApplication:com.redacted.redacted[0x9168]) Exited: Killed: 9
Oct  1 19:52:43 Strax backboardd[28] <Warning>: Application 'UIKitApplication:com.redacted.redacted[0x9168]' exited abnormally with signal 9: Killed: 9
Oct  1 19:52:43 Strax installd[62] <Notice>: 0x25d000 MobileInstallationInstall_Server: Staging: 0.05s; Waiting: 0.00s; Installation: 0.53s; LS Sync: 0.00s; Overall: 0.58s
Oct  1 19:52:43 Strax lsd[75] <Warning>: LaunchServices: Updating identifier store
Oct  1 19:52:43 Strax SpringBoard[33] <Error>: libMobileGestalt MobileGestalt.c:835: nike-ipod is static and will never generate a notification
Oct  1 19:52:43 Strax SpringBoard[33] <Error>: libMobileGestalt MobileGestalt.c:835: still-camera is static and will never generate a notification
Oct  1 19:52:43 Strax SpringBoard[33] <Error>: libMobileGestalt MobileGestalt.c:835: magnetometer is static and will never generate a notification
Oct  1 19:52:43 Strax SpringBoard[33] <Error>: libMobileGestalt MobileGestalt.c:835: any-telephony is static and will never generate a notification
Oct  1 19:52:43 Strax SpringBoard[33] <Error>: libMobileGestalt MobileGestalt.c:835: stand-alone-contacts is static and will never generate a notification
Oct  1 19:52:51 Strax MobileStorageMounter[350] <Error>: 0x3d85e18c digest_disk_image: Could not open /var/run/mobile_image_mounter/3zeNth.dmg: No such file or directory
Oct  1 19:52:51 Strax MobileStorageMounter[350] <Error>: 0x3d85e18c reload_mount_map: /Developer - could not create digest
Oct  1 19:52:51 Strax mobile_storage_proxy[349] <Error>: 0x3d85e18c handle_lookup_image: Entry 2 of 4 did not have a digest
Oct  1 19:52:51 Strax MobileStorageMounter[350] <Error>: 0x3d85e18c handle_mount_disk_image: A disk image of type Developer is already mounted
Oct  1 19:52:51 Strax mobile_storage_proxy[349] <Error>: MobileStorageMount:355 Could not extract mount path from response message
Oct  1 19:52:51 Strax mobile_storage_proxy[349] <Error>: 0x3d85e18c handle_mount_image: Could not mount the disk image
Oct  1 19:52:51 Strax mobile_storage_proxy[349] <Error>: 0x3d85e18c main: Could not mount the image
Oct  1 19:52:51 Strax com.apple.debugserver-300.2[351] <Warning>: debugserver-300.2 for armv7.
Oct  1 19:52:51 Strax com.apple.debugserver-300.2[351] <Warning>: Connecting to com.apple.debugserver service...
Oct  1 19:52:51 Strax com.apple.debugserver-300.2[351] <Warning>: Got a connection, waiting for process information for launching or attaching.
Oct  1 19:52:54 Strax assistantd[352] <Notice>: connection 4 total: 1, connected: 0, added new subflow [cid=1, state=Waiting, ifindex=7]
Oct  1 19:52:54 Strax awdd[353] <Error>: CoreLocation: CLClient is deprecated. Will be obsolete soon.
Oct  1 19:52:54 Strax assistantd[352] <Notice>: connection 4 total: 1, connected: 1, new connected subflow [cid=1, state=Connected, ifindex=7, preferred, mp_capable]
Oct  1 19:52:54 Strax assistantd[352] <Notice>: connection 4 total: 2, connected: 1, added new subflow [cid=2, state=Waiting, ifindex=2]
Oct  1 19:52:54 Strax securityd[79] <Error>: OCSPResponse: now > latestNextUpdate
Oct  1 19:52:54 Strax securityd[79] <Error>: OCSPResponse: now > latestNextUpdate
Oct  1 19:52:55 Strax securityd[79] <Error>: OCSPResponse: now + maxAge > latestNextUpdate, using latestNextUpdate
Oct  1 19:52:55 Strax com.apple.debugserver-300.2[351] <Warning>: About to launch process for bundle ID: com.redacted.redacted
Oct  1 19:52:55 Strax securityd[79] <Error>: OCSPResponse: now > latestNextUpdate
Oct  1 19:52:55 Strax kernel[0] <Debug>: launchd[354] Container: /private/var/mobile/Applications/1150A554-1046-4DB4-BA37-AC55DA01DED5 (sandbox)
Oct  1 19:52:55 Strax com.apple.debugserver-300.2[351] <Warning>: In completion handler, got pid for bundle id, pid: 354.
Oct  1 19:52:55 Strax com.apple.debugserver-300.2[351] <Warning>: Got a connection, launched process /Developer/usr/bin/debugserver.
Oct  1 19:53:03 Strax Forge[354] <Warning>: [INFO] New app version, removing any reload update files.
Oct  1 19:53:03 Strax kernel[0] <Debug>: 004804.545582 wlan.A[652] AppleBCMWLANNetManager::checkRealTimeTraffic():  now 4804.545565708 num entries 4
Oct  1 19:53:03 Strax kernel[0] <Debug>: 004804.545628 wlan.A[653] AppleBCMWLANCore::dumpWmeCounters():  per TIDs tx counters: 16180 12261 0 0 0 6379 234 0, per TIDs rx counters: 50102 0 0 0 0 0 76 0
Oct  1 19:53:03 Strax kernel[0] <Debug>: 004804.545668 wlan.A[654] AppleBCMWLANCore::dumpWmeCounters():                AWDL: Tx 0 0 0 0 0 0 0 0,                   Rx: 0 0 0 0 0 0 0 0
Oct  1 19:53:03 Strax Forge[354] <Warning>: [INFO] Checking for reload update
Oct  1 19:53:04 Strax Forge[354] <Warning>: [INFO] creating link from /var/mobile/Applications/1150A554-1046-4DB4-BA37-AC55DA01DED5/Library/Application Support/Forge/assets-D653E065-1D29-4DCD-9D75-1E5A5B798680/forge to ../../../../device-ios.app/assets/forge
Oct  1 19:53:04 Strax Forge[354] <Warning>: [INFO] creating link from /var/mobile/Applications/1150A554-1046-4DB4-BA37-AC55DA01DED5/Library/Application Support/Forge/assets-D653E065-1D29-4DCD-9D75-1E5A5B798680/src to ../../../../device-ios.app/assets/src
Oct  1 19:53:04 Strax Forge[354] <Warning>: [INFO] Loading default page in webview.
Oct  1 19:53:04 Strax Forge[354] <Warning>: [INFO] No reload update available.
Oct  1 19:53:04 Strax Forge[354] <Warning>: [INFO] Loading local url in webview: file:///var/mobile/Applications/1150A554-1046-4DB4-BA37-AC55DA01DED5/Library/Application%20Support/Forge/assets-D653E065-1D29-4DCD-9D75-1E5A5B798680/src/index.html
Oct  1 19:53:05 Strax Forge[354] <Warning>: [INFO] Registering for parse push notifications, subscribing to default channel.
Oct  1 19:53:05 Strax Forge[354] <Warning>: [DEBUG] Returning to javascript: {
        event = "internal.connectionStateChange";
        params =     {
            connected = 1;
            wifi = 1;
        };
    }
Oct  1 19:53:11 Strax lockdownd[51] <Notice>: 002c1000 _select_socket: receive secure message timeout!
Oct  1 19:53:20 Strax cplogd[341] <Warning>: Exiting.


text:
Q: Gain Access To variables defined within functions Within Js Functions, a variable can be defined but from console that variable doesn't exist is there anyway to access or edit it?
Example:(This code would be in the website)
function whatever () {
var x = 10
}

then in console if you type
x
it will say 'undefined'

A: x is limited to the scope of its function. If you want to reference it outside of the function, you can either declare it outside the function:
var x = 10
function whatever () {
  // ...
}

Or you can make it a global variable by declaring it with the window object:

function whatever () {
    window.x = 10
}

whatever()

console.log(x)

A: What you're talking about is called scope. From Mozilla's docs:
function exampleFunction() {
    var x = "declared inside function";  // x can only be used in exampleFunction
    console.log("Inside function");
    console.log(x);
}

console.log(x);  // Causes error

However:
var x = "declared outside function";

exampleFunction();

function exampleFunction() {
    console.log("Inside function");
    console.log(x);
    x = "something else";
}

console.log("Outside function");
console.log(x);

In other words, declaring variables outside the function allow access, and you can change them from within.
Alternatively, building on their example, you can use a return value in the function to assign a variable its value.
function exampleFunction() {
    return "Inside function";
}

const x = exampleFunction();
console.log(x);


text:
Q: Libgdx trailing fireworks I am working with Libgdx and trying to create fireworks that leave trail behind them as the pixels fall down.
Every render() step a Pixmap object is erased, a current state of fireworks particles is drawn on it, then texture is created from this pixmap and drawn on SpriteBatch, something like this:
pixmap.setColor(0, 0, 0, 0);
pixmap.fill();
pixmap.setColor(fireworks.red, fireworks.green, fireworks.blue, fireworks.alpha)
for (int i=0; i<Constants.FIREWORKS_PARTICLES; i++){
    pixmap.drawPixel(fireworks.x[i], fireworks.y[i]);
}
texture.draw(pixmap, 0, 0);
batch.draw(texture, ...);
Is there an efficient way to take all the pixels from previous pixmap drawing and lower their alpha value (And if it is lower than some threshold - make it 0) before adding the new frame, so it will look like a slowly disappearing trail behind the fireworks?

*

*There is more animated stuff, so I can't do anything "global" (Like changing GL accumulator values or getting the entire screen buffer with glFramebufferTexture2DOES)

*I've tried iterating over pixmap.getPixels() ByteBuffer (And changing every 4th byte), but  it isn't working for me (Guess not familiar enough with BytesBuffers to make it tick)

*There was a topic with a suggestion about drawing an alpha-blended version of previous image and I've tried several variations of this technique, but couldn't find how to decrease alpha on older image and blend it with current batch (or texture).

Would highly appreciate any help (and general thoughts about the way I chose to draw the fireworks).


text:
Q: How to send data from listview from one fragment to another I have a couple listview items and I need when I click on particular listview to go to Fragment_2 with a value of listview that is clicked. I try code below on Fragment_1 I get the proper value an it show in Tosat notification, but in Fragment_2 bundle is always null.
In onCreate method in Fragment_1
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String value = ((TextView) view.findViewById(R.id.username)).getText().toString();
                MainFragment fragment = new MainFragment ();
                Bundle bundle = new Bundle();
                bundle.putString("view", value);
                Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
                fragment.setArguments(bundle);

In onCreate method in Fragment_2
 Bundle bundle = this.getArguments();
        if (bundle != null) {
            String myString = bundle.getString("view");
            Toast.makeText(getContext(), myString, Toast.LENGTH_SHORT).show();

UDPATE:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String value = ((TextView) view.findViewById(R.id.username)).getText().toString();
                MainFragment fragment = new MainFragment ();
                Bundle bundle = new Bundle();
                bundle.putString("view", value);
                Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
                fragment.setArguments(bundle);

                if (position == 0) {
                    Intent myIntent = new Intent(view.getContext(), MainActivity.class);
                    startActivityForResult(myIntent, 0);

                }

                if (position == 1) {
                    Intent myIntent = new Intent(view.getContext(), MainActivity.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 2) {
                    Intent myIntent = new Intent(view.getContext(), MainActivity.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 3) {
                    Intent myIntent = new Intent(view.getContext(), MainActivity.class);
                    startActivityForResult(myIntent, 0);
                }

                            // ETC .......
            }
        });

A: Just replace below code in onItemClick method.
            String value = ((TextView)
            view.findViewById(R.id.username)).getText().toString();
            Bundle bundle = new Bundle();
            bundle.putString("view", value);
            Intent myIntent = new Intent(view.getContext(), MainActivity.class);
            myIntent.putExtra(bundle);
            startActivityForResult(myIntent, 0);

On MainActivity replace your MainFragment like this,
            MainFragment fragment = new MainFragment ();
            fragment.setArguments(getIntent().getExtras());

            getSupportFragmentManager()
              .beginTransaction()
              .replace("your fragment container id here", fragment)
              .commit();

A: you are not committing fragment
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String value = ((TextView) view.findViewById(R.id.username)).getText().toString();
                MainFragment fragment = new MainFragment ();
                Bundle bundle = new Bundle();
                bundle.putString("view", value);
                Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
                fragment.setArguments(bundle);

// This line is important
getSupportFragmentManager().beginTransaction().add(R.id.container, fragment).commit();

A: You are starting the Activity "MainActivity.class" and passing your bundle to a Fragment class "MainFragment" but never actually starting the MainFragment.
So, it is obvious that your code won't work

A: You are calling activity so how can you get the data in the fragment and if you are doing like this :
First you are launching the activity by this
  Intent myIntent = new Intent(view.getContext(), MainActivity.class);
                startActivityForResult(myIntent, 0);

Then in this activity you are launching the fragment
getFragmentManager().beginTransaction().replace("your fragment container id here",
fragment).commit();

Than in this case pass the data to the intent first like this
  Intent myIntent = new Intent(view.getContext(), MainActivity.class);
     myIntent.putString("data","Put the data which you want to pass");
                startActivityForResult(myIntent, 0);

and pass this data to the fragment by using bundles
Hope it will work for you .


text:
Q: GoogleApiClient Sign In Fails I'm trying to use the Google Games turn based Api for my Android game. The code I use to connect my GoogleApiClient comes from Google's Api samples or documentation.
Inside of my implementation of onConnectionFailed I have tried two separate approaches:
    if (signInClicked || autoStartSignInFlow) {
        autoStartSignInFlow = false;
        signInClicked = false;
        resolvingConnectionFailure = true;

         // Attempt to resolve the connection failure using BaseGameUtils.
         // The R.string.signin_other_error value should reference a generic
         // error string in your strings.xml file, such as "There was
         // an issue with sign-in, please try again later."
        if (!BaseGameUtils.resolveConnectionFailure(this,
                apiClient, connectionResult,
                RC_SIGN_IN, R.string.signin_other_error)) {
            resolvingConnectionFailure = false;
        }
    }

The first approach above comes from the TBMP Skeleton sample. This results in a dialog being created with the message

Failed to sign in. Please check your network connection and try again.

and the connection is never made.
   if (connectionResult.hasResolution()) {
        // https://developers.google.com/android/guides/api-client under 'Handle connection
        // failures'. I don't know if this is solving the problem but it doesn't lead to
        // 'please check your network connection' message.
        try {
            if(LoggerConfig.ON) {
                Log.e(TAG, "onConnectionFailure, attempting to startResolutionForResult.");
            }
            resolvingConnectionFailure = true;
            connectionResult.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
        } catch (IntentSender.SendIntentException e) {
            // There was an error with the resolution intent. Try again.
            if(LoggerConfig.ON) {
                Log.e(TAG, "onConnectionFailure, there was an error with resolution intent");
            }
            apiClient.connect();
        }
    }

In the second approach it ends up calling startResolutionForResult which passes RESULT_SIGN_IN_FAILED to onActivityResult. From the documentation

Result code sent back to the calling Activity when signing in fails.
The attempt to sign in to the Games service failed. For example, this might happen if the network is flaky, or the user's account has been disabled, or consent could not be obtained.

This puzzles me since I have no problems getting the sign in flow to work in a sample. However, in my game I am never prompted to select a Google account before the sign in fails.
For the record I've tried all the steps here https://developers.google.com/games/services/android/troubleshooting and it still fails.
How can I resolve this error in order to sign in?

A: private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create the Google Api Client with access to the Play Games services
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES)
            // add other APIs and scopes here as needed
            .build();

    // ...
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}

for further reference, please check the link  link

A: Try private GoogleApiClient mGoogleApiClient;
 mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

Call mGoogleApiClient.connect(); in onStart() method.
@Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }


text:
Q: HAL_UART_Transmit_IT sending data twice I am trying to establish UART communication between a PC and a STM32f407-DISC1 board using an arduino nano as a middle man.
The PC sends 'r' to the arduino to indicate a request.
The request is then communicated to the stm32 with a GPIO interrupt, which then should be transmitting 480 bytes of data using HAL_UART_Transmit_IT.
It however sends the data twice, with only a single request made.
The code on the STM32 is generated by STM32CubeMX
Data request made by the arduino
void loop() {
    digitalWrite(4, 0); // Clear EXTI11 line.

    if (mySerial.available() && received < 480) {   // STM32 sending data and is not done.
        buff[received] = mySerial.read();           // Append received data to the buffer.
        received++;
    }
    if (received >= 480) {                          // If the buffer is full
        received = 0;                               // transmit it to PC.
        Serial.println(buff);
    }

    if (Serial.available()) {
        if (Serial.read() == 'r') {     // PC requests data from the STM32
            digitalWrite(4, 1);         // Triggers STM32 EXTI11 line.
            while (Serial.available())  // Empty the buffer.
                Serial.read();
        }
    }
}

data transmission on the STM32
void EXTI15_10_IRQHandler(void)
{
    // Make sure that the interrupt is the good one.
    if (HAL_GPIO_ReadPin(data_req_IRQ_GPIO_Port, data_req_IRQ_Pin)) {
        if (is_sending_data == FALSE)   // If no transmission is happening
            should_send_data = TRUE;    // raise transmission flag.
    }

    // IRQ handling stuff...
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef * huart) {
    is_sending_data = FALSE;    // Transmition is completed, unblock requests.
}

void main(void){
    // Init and other stuff...

    while (1) {
        if (should_send_data == TRUE) { // If data was requested
            HAL_GPIO_WritePin(LD5_GPIO_Port, LD5_Pin, GPIO_PIN_RESET);
            HAL_UART_Transmit_IT(&huart3, matrice, 480);    // Start transmission by interrupt.
            is_sending_data = TRUE;                         // Block requests.
            should_send_data = FALSE;                       // Clear flag.
        }
    // matrice acquisition stuff here
    }
}

A: Alright so I found a solution, but it involved just rethinking my approach, so sorry for those looking for an answer to this problem.
I removed the arduino middle man by replacing it with a USB to RS232 converter and made UART reception work by interrupt. The STM detects the 'r' character which triggers the data communication.
Here is the interrupt part:
void USART3_IRQHandler(void)
{
    if (USART3->SR & UART_IT_RXNE) {    // If a byte is received
        rxBuff[0] = (uint8_t) (huart3.Instance->DR & (uint8_t) 0xFF);   // Read it.
        __HAL_UART_FLUSH_DRREGISTER(&huart3);   // Clear the buffer to avoid errors.
        rx_new_char_flag = TRUE;    // Raise the new_char flag.
        return; // Stops the IRQHandler from disabling interrupts.
    }
}

and the gestion of that in the main
while (1) {
    if (rx_new_char_flag == TRUE) {
        rx_new_char_flag = FALSE;
        if (rxBuff[0] == 'r') {
            rxBuff[0] = 0;
            HAL_UART_Transmit_IT(&huart3, matrice, 480); // Start transmission by interrupt.
            }
        }

On the PC side, to optimize performance, instead of waiting for the full 480 bytes, I wait for only one character, if one is received I keep reading the serial port, as shown in the code bellow
int i = 0;
do {
    ReadFile(m_hSerial, &temp_rx[i], 1, &dwBytesRead, NULL);
    i++;
} while (dwBytesRead > 0 && i < 480);
for (int j = i; j < 480; j++)  // If the transmission is incomplete, fill the buffer with 0s to avoid garbage data.
    temp_rx[j] = 0;

if(i>=480)  // If all the bytes has been received, copy the data in the working buffer.
    std::copy(std::begin(temp_rx), std::end(temp_rx), std::begin(m_touch_state));

This works well with pretty decent performance, so that may be a permanent solution to my problem.


text:
Q: Moment js time zone date conversion issue I am using moment js to convert user system time to user specified time zone as per his preference. User system time zone is IST and he is specifing a different time zone. For setting the same I am using
moment.tz.setDefault("Pacific/Pago_Pago");

But in one of the scenario I am getting different dates. If I do
moment().startOf('day')
I am getting today's date as Thu Oct 28 2021 00:00:00 GMT+0530 (India Standard Time), But if I am doing
moment(endDate).startOf('day')

I am getting Thu Oct 27 2021 00:00:00 GMT+0530 (India Standard Time) Where end date is the result of last statement i.e. Thu Oct 28 2021 00:00:00 GMT+0530 (India Standard Time)
What I am doing wrong here.

A: The timezone used when a moment object is created stays as part of the object and is used for subsequent processing. The effect described will happen if the default timezone is changed after the initial moment object is created.
E.g.

// Set default to IST (+5:30)
moment.tz.setDefault('Asia/Kolkata');

// Create initial moment using default timezone
let start = moment().startOf('day');

// Changing the default here doesn't affect above moment
moment.tz.setDefault('Pacific/Pago_Pago');

// This still uses the initial +5:30 offset, not -11:00 for Pago Pago
let timestamp = start.toString();

// This uses the timestamp for the original timezone, but
// then gets start of day in new default timezone
let end = moment(timestamp).startOf('day');

console.log( `Start: ${start.toString()}\nEnd  : ${end.toString()}` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data-10-year-range.js"></script>


text:
Q: Let $G,H$ be two groups. Show that the order of $G$, $|G| = 16$. Let $G = U(\mathbb{Z}_{32})$ and let $H = \big\{[1],[31]\big\} \leq G$.
(i) Show that $|G| = 16$.

A: The invertible elements are the odd ones, which of course are exactly $16$. I fail to see the relevance of $H$.


text:
Q: Auto hiding windows after clicking in background I have a lot of small windows on my site and my script close them when user clicks on the background
$(document).mouseup(function (e)
{
    var container = $("#"+active);

    if (!container.is(e.target) && container.has(e.target).length === 0) {
        $('#'+active).fadeOut(200);
    }
});

The problem is they also hide when the user scrolls the site - how can I detect that the user is not just clicking the scroll bar?

A: You can bind the event specifically on body instead of only on document:
$(document.body).mouseup ...


text:
Q: TextArea and Multiline do not work in Unity 2022.1.0b10.2818 [TextArea] public string sds;

this code was supposed to make a string field expandable downwards but instead it directly hides it from the inspector. however the name of a string is still present. So it works at 50%. Strange.
SCREENSHOT HERE

A: You can try this:
[TextArea(10,10)]public string ss;

Second number confines the size of the area.
Secondly, if the text field is looking messed up then use it like this:
[NonReorderable]
[TextArea(10,10)]public string ss;

A: I had the same bug with this in unity 2022.2.0b7
Then Changed to minimum to 10 and it got resolved. It now shows atleast 10 minimum lines.
[SerializeField]
[TextArea(1, 12)]
public string Description;

[SerializeField]
[TextArea(10, 12)]
public string ChangeToDescription;


text:
Q: Proof that diffusion-"reaction" equations yield a non-negative solution First question: I wish to prove that there exists a unique, positive solution $\phi_g(x,t)$ to the following system of $G$ PDEs with initial and boundary conditions for $t \ge 0$, $0 \le x \le X$:
$$ \left[\frac{1}{v_g}\frac{\partial}{\partial t} - \frac{\partial}{\partial x} D_g(x) \frac{\partial}{\partial x} \right] \phi_g(x,t) + \sum_{g'=1}^G \Sigma_{r, g' \to g}(x) \phi_{g'}(x,t) = 0 $$
$$ \phi_g(x,0) = \phi_{g,0}(x) > 0$$
$$ \phi_g(0,t) - 2 D_g(0) \frac{\partial\phi_g}{\partial x}(0,t) = 0 $$
$$ \phi_g(X,t) + 2 D_g(X) \frac{\partial\phi_g}{\partial x}(X,t) = 0 $$
Here, $v_g, D_g(x) > 0$ for all $g$, $\Sigma_{r, g' \to g}(x) \ge 0$ when $g = g'$, and $\Sigma_{r, g' \to g}(x) \le 0$ when $g \ne g'$.
Basically, I want to show $\phi_g(x,t) > 0$ for all $g$ and for all $x,t$ in my domain.  Proving uniqueness/existence would be nice, but positivity/non-negativity is the thing I'm most interested in.  From physical intuition (and from having solved these problems for a variety of physical parameters), I'm fairly confident that there must exist a unique, positive solution.  However, I have no idea how to prove it.  If you have any thoughts on how I could approach this proof, or know of a good reference that might lead me to such a proof, I would be very grateful!!
In Hundsdorfer's "Numerical Solution of Time-Dependent Advection-Diffusion-Reaction Equations" book, this is touched on a little bit in Chapter 1 (sections 1 and 7), but he only explicitly proves things for problems in which there is no dependence on $x$.
(Side note: In my field of study, this is the neutron diffusion equation, but I've seen in literature that it's more commonly referred to in the chemistry setting as diffusion-reaction equations, so I'm using that name here in hopes of drawing more attention.)
EDIT: Sorry, I had a small typo describing the positivity/negativity of the physical parameters.  Fixed now.
EDIT2: Made it more clear which parameters are space-dependent.
EDIT3: Altered the initial condition a bit to make it easier.  We also have the following inequality:
$$ \sum_{g'=1}^G \Sigma_{r,g \to g'} \ge 0 $$
I think I have a rough proof for my first question, which I will post as an answer shortly, but now I also have a new, related question.
==========================================================================
New, related question: Can we show that the corresponding BVP
$$- \frac{\partial}{\partial x} D_g(x) \frac{\partial}{\partial x}  \phi_g(x) + \sum_{g'=1}^G \Sigma_{r, g' \to g}(x) \phi_{g'}(x) = q_g(x) $$
$$ \phi_g(0) - 2 D_g(0) \frac{\partial\phi_g}{\partial x}(0) = 0 $$
$$ \phi_g(X) + 2 D_g(X) \frac{\partial\phi_g}{\partial x}(X) = 0 $$
has a "positive" solution?  i.e., can we show that $\phi_g(x) > 0$ for all $x \in [0,X]$?  Here, $q_g(x)$ is a "positive" source.  That is, $q_g(x) \ge 0$ and
$$ \sum_g \int_0^X q_g(x) dx > 0 $$

A: Here's my first attempt at a proof of the positivity (with lots of help from a friend).  I think there are some "holes" in it, and I would appreciate any feedback on what those holes are and how to fill them in.
First, we note that $\phi_g(x,t)$, for any $g$, cannot have a negative minimum at $x = 0$ or $x=t$ -- the boundary conditions indicate that, if $\phi_g(0,t) < 0$ or $\phi_g(X,t) < 0$, then $\phi_g(x,t)$ is decreasing "into" the domain.  Thus, we can assume that, if there are any negative components to $\phi_g(x,t)$, the global minimum would occur at an interior location (i.e., not at $x = 0$ or $x = X$).
We note that at time $t = 0$, everything is positive.  Let $t_0$ denote the first time at which one (or more) of the $\phi_g(x,t)$ functions become zero-valued at some point $x_0$. Let $g_0$ be the index of that function.  $x_0$ is a global minimum point of $\phi_{g_0}(x,t_0)$.  Thus, at this time and at this point in space, the following must be true:
$$ \phi_{g_0}(x_0,t_0)  = 0 $$
$$ \phi_g(x_0,t_0) \ge 0 $$
$$ \frac{\partial}{\partial x} \phi_{g_0}(x_0,t_0)  = 0 $$
$$ \frac{\partial^2}{\partial x^2} \phi_{g_0}(x_0,t_0) > 0 $$
Moreover, since it has just decreased to zero,
$$ \frac{\partial}{\partial t} \phi_{g_0}(x_0,t_0) \le 0 $$
Now, we revisit the terms of the PDE.  The time derivative is $\le 0$.  The spatial derivative term is strictly negative due to the negative sign and the strict positivity of the second derivative.  The sum over $g'$ is negative unless all of the $\phi_g(x_0,t_0)$'s are zero; in that case, it is equal to zero.
Thus, we have something negative on the left hand side equal to zero on the right hand side.  This is a contradiction -- our assumption that one of the $\phi_g(x,t)$'s become zero-valued at some point is impossible.
The one case I think this proof/argument leaves out is what if all the $\phi_g(x,t)$ becomes identically zero for all $x$ at time $t = t_0$.  $\phi_g(x,t) = 0$ is a steady state solution for this problem as $t \to \infty$.  However, I feel like this is impossible as long as we have a positive initial condition and $t$ is finite.  Not sure how to show this explicitly though, I'll have to give it some more thought.


text:
Q: Very simple flex animation not moving along x axis I'm trying to use Animate in MXML to move a button along X or Y axis.
My button increase width when clicked, but does not move at all. What is wrong with this code ? It should be something really simple, but I can't find it.
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:mx="library://ns.adobe.com/flex/mx"
    xmlns:s="library://ns.adobe.com/flex/spark"
    initialize='init()'>

    <fx:Script>
        <![CDATA[
            public function init():void {}
        ]]>
    </fx:Script>

    <s:layout>
        <s:VerticalLayout id='l' horizontalAlign="left" />
    </s:layout>

    <fx:Declarations>
        <s:Animate id="mover" target="{button}" duration="1000">
            <s:SimpleMotionPath property="x" valueFrom="0" valueTo="100"/>
            <s:SimpleMotionPath property="y" valueTo="100"/>
            <s:SimpleMotionPath property="width" valueBy="20"/>
        </s:Animate>
    </fx:Declarations>

    <s:Button id="button" click="mover.play()" label="Button"/>

</s:Application>

I got this sample from Adobe docs. I think it should be related to layout or something like that, but all my tries of changing layout, including into a Canvas or other tricks does not change anything : the button still stay at the same place.
Thanks for your help !

A: The problem is caused by the use of the VerticalLayout. This layout, as well as the HorizontalLayout, ignores x/y properties of the objects that are being laid out.
If you remove your layout declaration altogether, it will then use the default BasicLayout which will honor the x/y properties and allow your animation to work.


text:
Q: IllegalArgumentException from creating a NotificationChannel Very occasionally, we're getting an IllegalArgumentException with an empty localized message on some devices while creating a notification channel. I found this answer, but the channel name is 100% certain not "", so not the issue in this case. It's working for almost all users, but sometimes this exception is thrown for a user. We cannot seem to link it to a device type or specific Android version either.
The code for creating the channel:
public void createNotificationChannel(String label, String description, int importance) {
    // Create the NotificationChannel only on API 26+
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(label, label, importance);
        channel.setDescription(description);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
}

The stack trace of the exception:
android.os.Parcel.createException(Parcel.java:2078)
android.os.Parcel.readException(Parcel.java:2042)
android.os.Parcel.readException(Parcel.java:1990)
android.app.INotificationManager$Stub$Proxy.createNotificationChannels(INotificationManager.java:3205)
android.app.NotificationManager.createNotificationChannels(NotificationManager.java:713)
android.app.NotificationManager.createNotificationChannel(NotificationManager.java:701)

Anyone has any ideas? I'd love to fix this issue!

A: NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);

        // Configure the notification channel
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{500, 500, 500, 500});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }

Try this piece of channel code. It is working code.


text:
Q: Check in packages folder contents When I check in my projects into VSTS -- aka VSO -- should I check in the packages folder contents?
I checked in a couple of projects into VSTS "without" the packages folder contents. I downloaded the those projects onto another computer and now I'm having a lot of trouble restoring packages.
Is it standard practice to check in projects with "packages" folders?

A: Typically checkin the .config file(s) in the root but nothing else. Then, make sure that vs is setup to restore nuget packages when you build.
On the solution, goto Tools->Options->Package Manager->Allow NuGet to download missing packages. That should work.
And, since I have to edit every answer I type as I get it wrong the first time ... here is a good outline of what you need to do to exclude those files in case you need it.
In most of our solutions, we checkin the /packages/repository.config file at the solution level and then all of the packages.config files in each project.


text:
Q: How to create a function similar to MorphologicalComponents? As everyone knows, MorphologicalComponents can create a list that shows only the difference between morphological clusters. But sometimes we need to find out the morphological properties as well as the original values.
For example:
l={{1,1,0,2,3},{1,2,0,2,2},{2,2,2,3,3}};

MorphologicalComponents[l,CornerNeighbors->False]
(*{{1,1,0,1,1},{1,1,0,1,1},{1,1,1,1,1}}*)

But of course that's not what I want. I would like to have a result like this:
{{1,1,0,2,3},{1,4,0,2,2},{4,4,4,5,5}}

There're several attemps, but none of them are satisfying. Are there any other elegant solutions?

My algorithm will require multiple MorphologicalComponents calculation, thus be quite slow in speed when there are a lot of diffenent values in a huge list.
So, I would like to have a solution requires only one calculation and be as fast as possible while as simple as possible (No fussying with Compile if the code is too long......)

A: Though I was not able to run your code, I thought my solution might be useful for you (as I think it runs a bit faster):
Clear[mylabeling];
mylabeling[list_List] :=
  Module[{maxlist = Max@list, temp, tempmap, lut},
   temp = Map[MorphologicalComponents[
        Image[ImageData@Binarize[Image@list, {#, #}]],
        CornerNeighbors -> False] &, Range[maxlist]];
   tempmap = Map[FromDigits[Reverse@#, maxlist] &,
     Transpose[temp, {3, 1, 2}], {2}];
   lut = Table[0, {Max@tempmap}];
   lut[[Union@Flatten@tempmap]] =
    Range[0, -1 + Length@Union@Flatten@tempmap, 1];
   Return[Map[lut[[#]] &, tempmap, {2}]];
  ];

Calling
mylabeling@{{1, 1, 0, 2, 3}, {1, 2, 0, 2, 2}, {2, 2, 2, 3, 3}}

gives
{{1, 1, 0, 2, 4}, {1, 3, 0, 2, 2}, {3, 3, 3, 5, 5}}

This is not strictly identical to what you have written above, but I think the essence of your problem is simply to split all levels of your integer valued input list, so the order of resulting labels should not matter. I did not do extensive testing, let me know if it works for you. Also, ParallelMap might be useful when doing the MorphologicalComponents mapping. There is no useful solution without multiple calls of this built-in function. However, I am sure that a more effective way would be to implement a special solution of the flood-fill algorithm, but this seems to be beyond your intention.

A: The output of my function is slightly different from the one you give, but I think it still meets your requirement?:
unitStepExpand = Simplify`PWToUnitStep@PiecewiseExpand@# &;

help = Function[{x, a}, #] &@unitStepExpand@If[x == a, 1, 0];

label[l_] := Module[{element = l // Flatten // Union // Rest, layer, coloredlayer},
  layer = MorphologicalComponents[#, CornerNeighbors -> False] &@help[l, #] & /@ element;
  coloredlayer = FoldList[Max@# (1 - UnitStep[-#] &)@#2 + #2 &, layer];
  Total@coloredlayer]

l = {{1, 1, 0, 2, 3}, {1, 2, 0, 2, 2}, {2, 2, 2, 3, 3}};
l // label // TraditionalForm


text:
Q: SELECT if any row within ID contains specific value I have a DB with IDs and their classification (and much more columns that are useless for now),
Due to differences in unused columns, one ID may have different classifications like:
ID        Classification

1001      A
1001      A

1002      A
1002      A
1002      B

What I need is to group IDs and put classification by the rule "If any of the lines within this ID is 'B'-classified, then the group (single row with this ID) is 'B'-classified, else - 'A'-classified.
So that ID 1001 = A, but ID 1002 = B.
I am aware of WHERE tab.field = ANY() function, but I have reciprocal situation - left part of comparison should be ANY, while right part should be hardcoded. I kind of assume, that as comparison result is boolean, than place of left\right parts is irrelevant, but I cannot figure out query-subquery relations.
Please help

A: You can use the count window function to do this.
select distinct id
,case when count(case when classification='B' then 1 end) over(partition by id) >=1 then 'B' else 'A' end as classified
from t

A: For the special case where the classification of interest is also the letter with the last alphabetical position, you can simply do:
SELECT
  ID,
  MAX(Classification)
FROM tab
GROUP BY ID;

A: You can simply find max of classification for each id:
select id,
    max(classification)
from your_table
group by id;


text:
Q: convert object of type bytearray to JSON serializable I'm reading data from json documents stored as azure blob on datalake storage and covert them to type bytearray. Once I process all of this data I need to convert the data back as string so it can be json serializable. I'm using the below code to accomplish this. But, not sure how to convert the data back as string for json serializable.
Code
import json
from azure.storage.blob import BlobServiceClient
from azure.identity import DefaultAzureCredential

account = "myAccount"
container = "myContainer"
blob_name = "myBlob.json"

default_credential = DefaultAzureCredential()
blob_service_client = BlobServiceClient(account, credential=default_credential)
container_client = blob_service_client.get_container_client(container)
blob_client = container_client.get_blob_client(blob_name)
data = bytearray(blob_client.download_blob().readall())

    batch_size = 1000

    process = json.loads(data)

    for batch in [process[i:i+batch_size] for i in range(0, len(process), batch_size)]:
    # process data

A: According to [JSON]: Introducing JSON, byte array is not among supported types. The closest thing would be a string, so you have to convert it (using its decode method):

>>> import json
>>>
>>> ba = bytearray(b"{\"1\":2}")
>>> ba
bytearray(b'{"1":2}')
>>> js = json.dumps(ba.decode())
>>> js
'"{\\"1\\":2}"'
>>> s = json.loads(js)
>>> s, type(s)
('{"1":2}', <class 'str'>)

But, if you're transferring data so in the other size you convert it back to byte array (the code suggests that your data is the input / output of an inference), JSON might not be the best choice (performance wise), so you might want to consider Pickle, or Google's ProtoBuf.


text:
Q: SQL Server json truncated (even when using NVARCHAR(max) ) DECLARE @result NVARCHAR(max);

SET @result = (SELECT * FROM table
               FOR JSON AUTO, ROOT('Data'))

SELECT @result;

This returns a json string of ~43000 characters, with some results truncated.
SET @result = (SELECT * FROM table
               FOR JSON AUTO, ROOT('Data'))

This returns a json string of ~2000 characters. Is there any way to prevent any truncation? Even when dealing with some bigdata and the string is millions and millions of characters?

A: I was able to get the full, non-truncated string by using print instead of select in SQL Server 2017 (version 14.0.2027):
DECLARE @result NVARCHAR(max);

SET @result = (SELECT * FROM table
           FOR JSON AUTO, ROOT('Data'))

PRINT @result;

Another option would be to download and use Azure Data Studio which I think is a multi-platform re-write of SSMS (similar to how Visual Studio was re-written as VS Code). It seems to spit out the entire, non-truncated json string as expected out of the box!

A: This will also work if you insert into a temp table - not presenting does not apply the truncate of SSMS.
Might be usefull if you need to calculate several values.
declare @json table (j nvarchar(max));
insert into @json select * from(select* from Table where Criteria1 for json auto)a(j)
insert into @json select * from(select* from Table where Criteria2 for json auto)a(j)
select * from @json

A: I know this is an old thread but I have had success with this issue by sending the result to an XML variable. The advantage of using an XML variable is that the size is not stated as character length but by size of the string in memory, which can be changed in the options. Therefore Brad C's response would now look like...
DECLARE @result XML
SET @result = (SELECT * FROM table
FOR JSON AUTO, ROOT('Data'))
SELECT @result

or...

PRINT @result;

A: Here is the answer to JSON truncation:
SQL divides the JSON result into chunks 2k in size (at least my SQL 2016 installation does), one chunk in the first column of each row in the result set.  To get the entire result, your client code has to loop through the result set and concatenate the first column of each record.  When you've gotten to the end of the rows, voila, your entire JSON result is retrieved, uncut.
When I first encountered the truncation problem I was baffled, and wrote off FOR JSON for several years as an unserious feature suited only to the smallest of datasets.  I learned that I need to read the entire recordset only from the FOR XML documentation, and never actually saw it mentioned in the FOR JSON docs.

A: The easiest workaround to avoid the truncation is to wrap the query in another select:
select (
     <your query> FOR JSON PATH [or FOR JSON AUTO]
) as json

A: We've seen similar issues in SSMS, without using a variable SSMS truncates at 2033.
With a variable the query actually works OK when you use an nvarcahr(max) variable, but it truncates the output in the query results view at 43697.
A possible solution I've tested is outputting Query results to a file, using BCP:
bcp  "DECLARE @result NVARCHAR(max); SET @result = (SELECT * FROM table FOR JSON AUTO, ROOT('Data')); SELECT @result as Result;" queryout "D:\tmp\exportOutput.txt" -S SQL_SERVER_NAME -T -w
See BCP docs for specifying server name\instance and authentication options

A: I didn't find and 'official' answer, but it seems that this is an error with the new 'FOR JSON' statement which is splitting the result in lines 2033 characters long.
As recommended here the best option so far is to iterate through the results concatenating the returned rows:
string result = "";
while (reader.Read())
{
    result += Convert.ToString(reader[0]);
}

BTW, it seems that the latest versions of SSMS are already applying some kind of workaround like this to present the result in a single row.

A: It's difficult to determine exactly what the problem you're having without posting the data, but I had a similar problem when I was attempting to export a query in JSON format. The solution that worked for me was to go to Query/Query Options/Results/Text/Set "Maximum number of characters displayed in each column:" to 8192 (max value AFAIK).
This probably won't help much with your first query, but that potentially could be broken into smaller queries and executed successfully. I would anticipate that you could effectively run your second query after changing that setting.

A: If your datalength is less than 65535 then you should use the suggestion of @dfundako who commented in the first post:

Try going to Tools, Options, Query Results, SQL Server, Results to Grid, and set Non-XML data to the max amount (I think 65535)

In my case the datalength was 21k characters so after exporting to grid I copied the value and it was fine, not truncated. Still it doesn't solve the the issue for those with bigger amount of data.

A: Try Visual Studio Code with Microsoft SQL extension. I got 6800 characters of JSON without truncation. It seems SSMS truncates results.


text:
Q: AWS ECR allow roles from secondary account I have an ECR in a prod account that I want to grant push access to from the dev role.
This is my current policy
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPushPull",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::account:role/rolename",
          "arn:aws:sts::account:assumed-role/rolename/instance",
          "arn:aws:sts::account:assumed-role/rolename/AWSCLI-Session"
        ]
      },
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:BatchGetImage",
        "ecr:CompleteLayerUpload",
        "ecr:DescribeImages",
        "ecr:DescribeRepositories",
        "ecr:GetDownloadUrlForLayer",
        "ecr:GetLifecyclePolicy",
        "ecr:GetLifecyclePolicyPreview",
        "ecr:GetRepositoryPolicy",
        "ecr:InitiateLayerUpload",
        "ecr:ListImages",
        "ecr:PutImage",
        "ecr:PutLifecyclePolicy",
        "ecr:SetRepositoryPolicy",
        "ecr:StartLifecyclePolicyPreview",
        "ecr:UploadLayerPart"
      ]
    }
  ]
}

Running aws sts get-caller-identity I can see I have the role checked out "arn:aws:sts::account:assumed-role/rolename/AWSCLI-Session" but I do not have access to push.
I receive the following until timeout.

The push refers to repository
[account.dkr.ecr.us-west-2.amazonaws.com/repo] 87e2ce75493a: Retrying
in 4 seconds

My non-prod account does exist in us-east-1. but my login command specifies west.
task: [docker:ecr-login] aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin accpunt.dkr.ecr.us-west-2.amazonaws.com
Any ideas what may be my problem on this repo?
(this works with my production account so the registry is valid)
Also this works when I use my dev account and allow the user IAM

A: In my case, it was the ec2 role had access to ECRs in its own account but did not have a resource giving it permission to external accounts. This is because AWS first checks resource policies but then checks the role's policy to ensure that action is also enabled for the role.


text:
Q: A few questions about the concept of work From Wikipedia: The work done by a constant force of magnitude F on a point that moves a displacement d in the direction of the force is the product:
$$W = Fd.$$
If I lift some object from a ground, the force to be put in above equation is the gravitational force $mg$.
But while I am moving the object upwards, against the gravity, I must pull the object with greater force than $mg$, right? So the net force is $F_{myforce}-mg$ which results in object being lifted. But this is not the case. Why? Does it matter how strongly I pull the object?
What work will I do if I move this object in absence of gravity (in space)? Will work done be zero or not?

A: You are getting confused between work done by a single force and total work done on a body. When you substitute $F=mg$ in the above equation[1], you are calculating the work done by the gravitational force, only the gravitational force and nothing else.
Substituting $F=F_{my force}$ will give you work done by you on the object. So if $F_{myforce}>mg$, the total work done(sum of the work done by all forces) on the body will be positive, which will show as the body's kinetic energy(velocity).
So from this, you can deduce that if you pull an object in zero gravity, you will do work, on the body. It will just be more than the work you would do on earth, ofcourse because there's no gravity.
[1]A more correct equation for work done would be $W= \vec F\cdot\vec s$, which involves scalar product of two vectors force($\vec F$) and displacement($\vec s$), because you have to take into account the signs(Work done can be negative too).

A: When you accelerate the object the applied force is greated than gravity. The formula is
$$ F = m ( g + \ddot{y} ) $$
where $\ddot{y}$ is the upwards acceleration. The work put in the system is equal to the work needed to lift the object (potential energy) plus the work needed to move the object (kinetic energy).
The work done is $F\, \Delta y$, the potential energy is $m g\, \Delta y$. If the final kinetic energy is zero (object rests after being lifted) then ${\rm Work} = F\, \Delta y = m g\,\Delta y$ indeed. If not at rest in the end, then the work will be
$$ {\rm Work} = F\, \Delta y = m g\;\Delta y + \frac{1}{2} m \dot{y}^2 $$
Without gravity take the above and set $g=0$.

A: Escape for a moment from the definition "work is equal to the force times the distance ('times' meaning scalar product of course)"
The meaning of "work"  may be interpreted as a transfer of energy, or specifically, the transfer in or out of a system's kinetic energy.$^1$
Your Question:

If I lift some object from a ground, the force to be put in above equation is the gravitational force mg

Not necessarily. You could insert any force or combinations of forces that are acting on the system. You just need to understand what is being said by the equation for each case. This is where understanding "work" in terms energy transfer may help. The force you exert lifting the object is transferring energy to the object/Earth system kinetic energy while the gravitational force (mg) is draining the kinetic energy from the object/Earth system.
If you need to know how to tell if the interaction is adding/subtracting from the system's kinetic energy: If the direction of the motion and the direction of the force (or force component) is in the same direction, then it adds to the kinetic energy, if they're oppositely aligned then the kinetic energy is drained. A little more technically, if the scalar product of the force and distance is positive/negative, then the change in kinetic energy is positive/negative respectively.

But while I am moving the object upwards, against the gravity, I must pull the object with greater force than mg, right?

Not correct: you can move the object at constant speed by keeping the gravitational force and the upward lifting force balanced. When the object is on the ground you will need to exceed this force to accelerate the object to lifting speed, and then lift with less force than the weight to slow it down to rest. Again, in the energy picture, if the net flow of energy is zero (forces balance) the kinetic energy will be a constant.$^2$

What work will I do if I move this object in absence of gravity (in space)? Will work done be zero or not?

If you apply a force on the object over some distance then work will be done. In other words, if you change the object's kinetic energy then work will be done.
Final note: I am not advocating an energy description over the force description. Being able to switch between perspectives will add to depth of understanding the physics involved.
$^1$ If the transfer is of a microscopic nature or caused by a temperature difference, then stick to using "heat" to describe the energy transfer.
$^2$ It's actually the net energy current, a.k.a. net power, that has to be zero to keep the speed constant. You could have a net flow of zero and have a period of speeding up followed by a period of slowing down in such a way as to keep the average speed constant, but not the instantaneous speed everywhere constant.


text:
Q: Indexing new dataframes into new columns with pandas I need to create a new dataframe from an existing one by selecting multiple columns, and appending those column values to a new column with it's corresponding index as a new column
So, lets say I have this as a dataframe:
A B C D E F
0 1 2 3 4 0
0 7 8 9 1 0
0 4 5 2 4 0

Transform into this by selecting columns B through E:
A index_value
1 1
7 1
4 1
2 2
8 2
5 2
3 3
9 3
2 3
4 4
1 4
4 4

So, for the new dataframe, column A would be all of the values from columns B through E in the old dataframe, and column index_value would correspond to the index value [starting from zero] of the selected columns.
I've been scratching my head for hours. Any help would be appreciated, thanks!
Python3, Using pandas & numpy libraries.

A: Try using:
df = pd.melt(df[['B', 'C', 'D', 'E']])
# Or df['variable'] = df[['B', 'C', 'D', 'E']].melt()
df['variable'].shift().eq(df['variable'].shift(-1)).cumsum().shift(-1).ffill()
print(df)

Output:
    variable  value
0        1.0      1
1        1.0      7
2        1.0      4
3        2.0      2
4        2.0      8
5        2.0      5
6        3.0      3
7        3.0      9
8        3.0      2
9        4.0      4
10       4.0      1
11       4.0      4

A: This is just melt
df.columns = range(df.shape[1])
s = df.melt().loc[lambda x : x.value!=0]
s
    variable  value
3          1      1
4          1      7
5          1      4
6          2      2
7          2      8
8          2      5
9          3      3
10         3      9
11         3      2
12         4      4
13         4      1
14         4      4

A: #Another way

    A   B   C   D   E   F
0   0   1   2   3   4   0
1   0   7   8   9   1   0
2   0   4   5   2   4   0

# Select columns to include

start_colum ='B'
end_column ='E'
index_column_name ='A'

#re-stack the dataframe

df = df.loc[:,start_colum:end_column].stack().sort_index(level=1).reset_index(level=0, drop=True).to_frame()

#Create the "index_value" column

df['index_value'] =pd.Categorical(df.index).codes+1

df.rename(columns={0:index_column_name}, inplace=True)

df.set_index(index_column_name, inplace=True)

df

    index_value
A
1   1
7   1
4   1
2   2
8   2
5   2
3   3
9   3
2   3
4   4
1   4
4   4


text:
Q: Approximation of binomial distribution by central limit theorem Liz is standing on the real number line at position 0. She rolls a die repeatedly. If the roll is 1 or 2, she takes one step to the right (in the positive direction). If the roll is 3, 4, 5 or 6, she takes two steps to the right. Let $X_n$ be Liz's position after n flips. Estimate the probability that $X_{90}$ is at least 160.
So, I need to compute the probability $P(X_n \geq 160)$ and I think I have to  use the Central Limit theorem. For that I need $X_n \sim Bin (n, p)$. But I don't know how to get the binomial distribution from the given problem. Can somebody explain it to me? Appreciate any help.

A: For $90$ rolls let $N$ denote the number of rolls that show a $1$ or a $2$.
Then $X_{90}=N+2(90-N)=180-N$ so that $\{X_{90}\geq160\}=\{N\leq20\}$.
This with $N\sim\mathsf{Bin}(n=90,p=\frac13)$.

A: The Central Limit Theorem does apply to the Binomial distribution, but it applies to other distributions as well; it is not necessary to reduce the problem to one involving the Binomial distribution.
Let $X_i$ be the movement due to the the $i$th roll.  Then $P(X_i = 1) = 2/6$ and $P(X_i = 2) = 4/6$.  By direct computation, using the definitions of mean and variance, the mean of $X_i$ is $10/6$ and the variance is $2/9$.  So the mean of $\sum_{i=1}^{90} X_i$ is $\mu = 90 \cdot 10/6$ and the variance is $\sigma^2 = 90 \cdot 9 / 2$.  By the CLT, we can approximate $\sum_{i=1}^{90} X_i$ with a Normal distribution with mean $\mu$ and variance $\sigma^2$.


text:
Q: foo e bar - Tem algum significado especial? Na maioria dos exemplos de códigos em várias linguagens, eu vejo essas duas nomeações para variáveis - foo e bar. Existe algum significado especial para elas?

A: A origem do termo foo é obscura. A conexão com bar é normalmente tida como um termo usado por tropas americanas na segunda guerra mundial, vindo da sigla FUBAR que significa "Fucked Up Beyond All Repair" -  Que traduzindo para o português é a expressão (perdoe-me o palavrão) "Fodido além de todo o [possível] conserto" - Ou seja, quebrado/zoado de uma forma irrecuperável. Entretanto, essa origem, apesar de plausível, é tida como incerta.
A origem de "foo" isoladamente é um pouco mais antiga, mas pode ser atribuída aos quadrinhos Smokey Stover que começaram a ser publicados em 1935, quadrinho no qual a palavra "foo" era muito importante. Os quadrinhos eram recheados de itens absurdos, veículos bizarros, muitas peças e coisas esquisitas cujo funcionamento parecia ser improvável ou impossível, e muitas vezes simplesmente davam errado. Muitas dessas coisas tinham a sílaba foo no nome. Também havia vários diálogos sem sentido. Enfim, havia muita gambiarra lá!
Segundo os criadores de Smokey Stover, a palavra foo vem do chinês e significa "boa sorte". Em chinês, 福 (que pode ser transliterado como fu ou foo) significa felicidade. Foo também pode ter origem no francês feu (que significa "fogo"), sendo que o protagonista do Smokey Stover era um bombeiro que se dizia ser um foo fighter ao invés de um firefighter ("bombeiro" em inglês).
Em programação, os termos foo e bar começaram a aparecer por volta dos anos 1960, e também têm origem obscura, embora tenham aparecido juntos. A primeira aparição confirmada foi em 1965, embora eles possam ser um pouco mais antigos. Costumavam aparecer em códigos bastante gambiarrados, ou em coisas que eram reutilizadas um grande número de vezes em contextos e situações tão diferentes, que fica até difícil dar nome ou se definir a finalidade de tal coisa. Isso claramente remete ao que acontece no Smokey Stover e na sigla FUBAR - Uma coisa super confusa, bizarra e estranha que está tão zoada que não pode mais ser consertada.
Em resumo, foo e bar são apenas nomes genéricos para gambiarras.
Informação obtida em sua maioria na wikipedia: https://en.wikipedia.org/wiki/Foobar

A: Sobre os populares foo e bar, são termos em inglês bastante usados na programação para ilustrar exemplos (nome de variáveis, métodos, funções, classes...). Apenas isto. Não há significação especial. Trazendo para o português (mutatis mutandis), é como se fosse fulano ou sicrano da linguagem de programação, ou o x e y da matemática.
Origem
Há bastante teorias sobre a origem destes termos. Referências:
Wikipedia - foobar (PT-BR).
RFC3092 - Etymology of "Foo" (EN)
Algumas definições (do inglês)
Foo

An term used for unimportant variables in programming when the
  programmer is too lazy to think of an actual name.

http://www.urbandictionary.com/define.php?term=foo

Used very generally as a sample name for absolutely anything, esp.
        programs and files (esp. scratch files).

https://www.ietf.org/rfc/rfc3092.txt
Foobar

A common term found in unix/linux/bsd program help pages as space
  fillers for a word.  Or, can be used as a less intense or childish
  form of fubar. To run the program, simply cd to the directory you
  installed it in like this:  user@localhost cd foo/bar

http://www.urbandictionary.com/define.php?term=foobar


text:
Q: calling jquery function with one id for many instead of individual id Sorry if my title sounded crazy I wasn't exactly sure how to look it up.
I have a jquery function that's called with a mouse hover. I can do it fine if every html tag has a unique id. It just seems like a total waste of repetitiveness
The jquery I'm calling with the mouse over
$('#ex1').zoom();
$('#ex2').zoom();
$('#ex3').zoom();
$('#ex4').zoom();
$('#ex5').zoom();
$('#ex6').zoom();
$('#ex7').zoom();
$('#ex8').zoom();
$('#ex9').zoom();

my HTML

1

2

3

4

5

6

7

8

9

A: You have a class, use it!
$(".zoom").zoom();

A: In case .zoom is used somewhere else, you may use
$("[id^=ex]") which will select all elements which ID starts with ex or you can use class but more specific:
$("#grid li a.zoom") which will select only a elements in ul#grid that has zoom class.


text:
Q: OpenQA.Selenium.WebDriverException : unknown error: cannot find Chrome binary I am trying to run my tests on Azure Devops pipeline and I am getting the below mentioned error. Most solutions are asking to specify (hard-code) the binary path but that can not be implemented on servers. Furthermore, the tests run fine locally.
It seemed like the agents did not have chrome installed, but then again, these tests ran fine on the same agent pool a while back.
NUnit Adapter 3.15.0.0: Test execution complete
      X CreateAgentApp [< 1ms]
      Error Message:
       OneTimeSetUp: OpenQA.Selenium.WebDriverException : unknown error: cannot find Chrome binary

      X CreateProject [< 1ms]
      Error Message:
       OneTimeSetUp: OpenQA.Selenium.WebDriverException : unknown error: cannot find Chrome binary

      X CreateSPAApp [< 1ms]
      Error Message:
       OneTimeSetUp: OpenQA.Selenium.WebDriverException : unknown error: cannot find Chrome binary

I am initializing the ChromeDriver with the following options:
{
    ChromeOptions options = new ChromeOptions();
    options.AddArgument("--disable-features=VizDisplayCompositor");
    return options;
}

Secondly, is it possible to add a demand variable in pipeline settings to check Chrome existence.

A: Since demands syntax cannot detect the existence of Chrome.
I manually checked this site.and found Chrome and chromedriver.exe are installed in microsoft-hosted agent pools Hosted Windows 2019 with VS2019 and Hosted VS2017.
You can just run selenium ui tests against these agent pools.
Don't know how you set the chromedriver path? But I found a way to get the chromedriver.exe path of the agents using below powershell scripts.  And the path is
   C:\SeleniumWebDrivers\ChromeDriver on agent.
$driverpath = Get-ChildItem Env:ChromeWebDriver

For test purpose i hard code above driver path in my code. The tests ran as expected on hosted agents.
If you dont want to hard code the path, you can add a powershell task to output driver path, and replace the driver path in your test code with the parameters in your test .runsettings files
echo "##vso[task.setvariable variable=chromedriverpath;isOutput=true]$driverpath"

A: I had the same issue and found that chromedriver and Chrome versions should be compatible. MS hosted agents have both preinstalled as mentioned in other answers (refs: MS-Hosted Agents, Windows-2019/latest).
To ensure the versions work, there are few options depending on the scenario.
If chromedriver is expected to be in the output directory, e.g. using  Selenium.WebDriver.ChromeDriver, then either;

*

*use the same versions of chromedriver and Chrome of the build server (see refs above) in code; or

*copy chromedriver from the build server to the output directory during build using the environment variable $Env:ChromeWebDriver.

Copy-Item "$env:ChromeWebDriver/chromedriver.exe" -Force -Destination "**/bin/Release/*/"

Alternatively, set the driver path dynamically; maybe checking for the environment variable ChromeWebDriver.
pseudo-code for illustration only

...
var driverDir = Environment.GetEnvironmentVariable("ChromeWebDriver");
var driverPath = !string.IsNullOrWhiteSpace(driverDir)
    ? Path.Combine(driverDir, "chromedriver.exe")
    : "relative/path"; // see below

// init the driver or add to options
var driver = new ChromeDriver(driverPath)

...

For the relative path, see this question How can I instantiate a new ChromeDriver using a relative path in C#?


text:
Q: Generating function for $t$-residues of partitions using Heisenberg + $\hat{sl_t}$ representation theory Recall that for $t\geq2$, a partition is a $t$-core if none of its hooklengths is divisible by $t$. It is known that the $t$-cores are parametrized by ${\mathbb Z}^{t-1}$. More precisely, let $(n_0,\dots,n_{t-2})$ be a $(t-1)$-tuple of integers and set $n_{t-1}:=-\sum\limits_{i=0}^{t-2}n_i$. Define $r_i=\sum\limits_{k=0}^{t-1}(n_k^2+\epsilon(i,k)n_k)/2$ for all $t$-residues $i$, where $\epsilon(i,k)=\left\{\begin{array}{rr}1,&\,\,\mbox{if $i\geq k$}\\-1,&\,\,\mbox{if $i<k$}\end{array}\right.$. Then there is a unique partition which is a $t$-core and which has $r_i$ nodes of $t$-residue $i$ [MR1055707 Reviewed Garvan, Frank; Kim, Dongsu; Stanton, Dennis Cranks and $t$-cores. Invent. Math. 101 (1990), no. 1, 1–17]. Notice that $n_i=r_i-r_{i+1}$ for each residue $i$.
Let $r(n):=(r_0,r_1,\dots,r_{t-1})\in{\mathbb Z}^t$ depend on $n:=(n_0,n_1,\dots,n_{t-2})$ as above and set $x^{r(n)}:=x_0^{r_0}x_1^{r_1}\dots x_{t-1}^{r_{t-1}}$ for indeterminates $x_0,\dots,x_{t-1}$. So the generating function for the $t$-residues of $t$-cores is
$$
K_t(x):=\sum_{n\in{\mathbb Z}^{t-1}}x^{r(n)}.
$$
Let $P(y)=\prod_n(1-y^n)^{-1}$ be the partition generating function in the indeterminate $y$ and let $J=(1,\dots,1)$ be the all-$1$'s vector in ${\mathbb Z}^t$. Using the representation of partitions on an abacus with $t$ runners, the generating function for the $t$-residues of all partitions is
$$
P_t(x)=P(x^J)^tK_t(x).
$$
According to Ben Elias, this is the generating function of the Fock space representation of $\hat{sl_t}$. So it should have a product expansion using Heisenberg and $\hat{sl_t}$ representation theory. For example, in a previous question [Generating function related to 2-residues of partitions I noted that the generating function for the $2$-residues of partitions factorizes as
$$
\begin{aligned}
P_2(x)
&=P(x_0x_1)^2\sum_{n\in{\mathbb Z}}x_0^{n^2}x_1^{n^2+n}\\
&=\prod\limits_{n=1}^\infty\frac{(1+x_0^{2n-1}x_1^{2n})(1+x_0^{2n-1}x_1^{2n-2})(1+x_0^nx_1^n)}{(1-x_0^nx_1^n)}.
\end{aligned}
$$
This is a consequence of the Jacobi Triple Product Identity.
Question: can anyone explicitly factorize $P_t(x)$ and provide a self-contained explanation of the relevant representation theory?

A: Denote by $\tilde{\mathcal F}$ the Fock space representation of $\widehat{sl}_t$. In fact it is even a $\widehat{gl}_t$-module, and as such irreducible. Now \begin{equation}\widehat{gl}_t= \widehat{sl}_t\oplus Heis \Big/ (Z_{\widehat{sl}_t}-Z_{Heis}),\end{equation} where $Heis$ is the infinite dimensional Heisenberg, and the notation is meant to indicate that in the direct sum, one identifies the centres. This $Heis$-action on $\tilde{\mathcal F}$ is not the standard one, but is by a smaller subalgebra of the standard one (inside the standard Heisenberg acting on $\tilde{\mathcal F}$, one essentially takes only the generators with indices divisible by $t$). In terms of this decomposition, one has \begin{equation}\tilde{\mathcal F} = V(\omega_0)\otimes {\mathcal F},\end{equation} where $V(\omega_0)$ is the basic representation of $\widehat{sl}_t$, whereas ${\mathcal F}$ is the standard Fock space representation of $Heis$. Note they both have central charge one, so the action factors through the quotient taken above. Everything so far is explained in much greater detail in Tingley's Notes on Fock space (Section 3E) or Leclerc's Fock space representations... (2.2.8).
Your $P_t(x)$ is the character of $\tilde{\mathcal F}$. In terms of the decomposition above, we understand it as one factor of $P(x^J)$, and the rest.
Now we have to understand how the rest becomes the character of the basic representation $V(\omega_0)$ of $\widehat{sl}_t$. There are several known constructions of the basic rep; the relevant one here is the Frenkel-Kac construction. That says that, as a vector space at least, \begin{equation}V(\omega_0) \cong {\mathcal F}^{t-1}\otimes {\mathbb C}(Q),\end{equation}
where $\mathcal F$ is good old Fock space once again, and $Q$ is the finite root lattice of type $A_{t-1}$. This basically gives the rest of the formula, once the relevant weights are computed explicitly: you have $t-1$ more copies of $P(x^J)$, and $K_t(x)$  comes from the root lattice. The character of the basic representation is written in the form needed here for example in Theorem 20.23(d) of Carter's book Lie algebras of finite and affine type.
ADDED LATER
I believe $K_t(x)$ itself admits no simple product expansion for $t>2$. Set $t=3$; it is easy to see that an appropriate specialisation of $K_t(x)$ is the one-variable function
\begin{equation} L(q) = \sum_{m,n\in\mathbb Z} q^{m^2+mn+n^2}.
\end{equation}
As I learned from Garvan some years ago, this function $L(q)$ of a single variable $q$ has a zero inside the unit circle, at $q_0=-\exp(-\pi/\sqrt{3})$, by a remark hidden on top of p.697 in this paper (which uses the same notation, except that it also introduces $a(q)$ for $L(q)$). This prevents $L(q)$ from admitting a product expansion in terms of $(1-q^n)$'s raised to a polynomial exponent in $n$, since functions admitting such expansions have no zeroes inside the unique circle.


text:
Q: Error when saving @Lob with hibernate java mysql Technology:
hibernate 4.3.4.Final
spring-data-jpa 1.5.0.RELEASE
mysql-connector-java 5.1.30
c3p0 0.9.5-pre8
Some part of dao context:
<bean id="dataSource" destroy-method="close"
    class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass"
        value="${MyApp_Persistance.connection.driver_class}" />
    <property name="jdbcUrl" value="${MyApp_Persistance.connection.url}" />
    <property name="user" value="${MyApp_Persistance.connection.username}" />
    <property name="password" value="${MyApp_Persistance.connection.password}" />
</bean>

I have entity OrganizationDetail:
@Entity
@Table(name = "OrganizationDetails")
public class OrganizationDetail implements Serializable {
...
...
...

    @Lob
    private String address;

...

and when im trying to save entity into database i get:
Caused by: java.lang.AbstractMethodError: Method com/mchange/v2/c3p0/impl/NewProxyPreparedStatement.setCharacterStream(ILjava/io/Reader;J)V is abstract
    at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.setCharacterStream(NewProxyPreparedStatement.java)
    at org.hibernate.type.descriptor.sql.ClobTypeDescriptor$4$1.doBind(ClobTypeDescriptor.java:131)
    at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:90)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:281)
    at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:56)
    at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3248)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3183)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3525)
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:158)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:461)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:347)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:513)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:478)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:272)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy55.save(Unknown Source)
    at hr.myapp.service.impl.OrganizationServiceImpl.save(OrganizationServiceImpl.java:50)
    at hr.myapp.web.bean.OrganizationBean.saveOrganizationAction(OrganizationBean.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 76 more

Can anyone point me to right direction ? Is there any jar missing ?
I'm sure that this error pops up when i use @Lob annotation!

A: I had same problem with Java, Hibernate, Oracle 11g and @Lob annotation.
Searching on web i found that it is fixed by upgrading C3P0 to stable version 0.9.2.1.
Link to MVN Repository, useful if you are using Maven: http://mvnrepository.com/artifact/com.mchange/c3p0/0.9.2.1
If not using Maven just download from Sourceforge C3PO site:
http://sourceforge.net/projects/c3p0/files/c3p0-bin/c3p0-0.9.2.1/
That worked for me.


text:
Q: How to load database into helper and display in view with specific column footer_helper
<?php

function get_gadget_footer() {

//the database functions can not be called from within the helper
//so we have to explicitly load the functions we need in to an object
//that I will call ci. then we use that to access the regular stuff.
$ci=& get_instance();
$ci->load->database();

//select the required fields from the database
//$ci->db->select('name, type, setting');

//tell the db class the criteria
$ci->db->where('display', 'Footer');

//supply the table name and get the data
$query = $ci->db->get('gadgets');

foreach($query->result() as $row):

    $type['name'] = $row->name;
    $type['type'] = $row->type;
    var_dump($type);
endforeach;

return $type;

}

hi this is my helper page. var_dump($type) is returning me required result in form of array as:
var_dump($type)
 array (size=2)
 'name' => string 'Quick Links' (length=11)
 'type' => string 'Facebook

 Twitter

 Salyani

 B&W
' (length=123)

 array (size=2)
 'name' => string 'Social Network' (length=14)
 'type' => string 'Facebook

 Facebook

 Facebook

 Facebook
' (length=115)

Now in my view page. I want display specific record in div. Like  record of name
 record of type .
Since now i had done following:
view
 <?php
 $this->load->helper('footer_helper');
 $name = get_gadget_footer();
 ?>

  <?php

  foreach ($name as $dat){

  ?>

  <?php

  ?>

<?php echo $dat['name']; ?>

<?php $dat['type']; ?>

   <?php

  }
  ?>

But, its giving me error. Please help me.

A: In your helper you are restting the name/type of the array, not building it.
It should be something like;
<?php
//supply the table name and get the data
$query = $ci->db->get('gadgets');
$type = array();
foreach ($query->result() as $row) {
    $type[] = array('name' => $row->name, 'type' => $row->type);
}

return $type;


text:
Q: How can I use 32-bit Perl to thaw something frozen with 64-bit Storable? I'm trying to thaw a database BLOB that was frozen using Storable on a 64-bit Solaris (production) machine. When I try to thaw on a 32-bit Windows (development) PC I receive "Byte order is not compatible error".
perl -v (on solaris)
This is perl, v5.8.8 built for i86pc-solaris-64

perl -v (on Windows)
This is perl, v5.10.1 built for MSWin32-x86-multi-thread

Exact error is:
(Unable to read: Byte order is not compatible at blib\lib\Storable.pm (autosplit into  blib\lib\auto\Storable\thaw.al) line 415, at ../handlers/Search/actions/SearchSendQueue.pm line 124 )

line 124 of SearchSendQueue.pm:
my $object = thaw( $item->{object} );

Does anybody know how I can thaw this object on the 32-bit machine?
Note: The object is valid and working on the 64 bit production machine.
I've already tried "$Storable::interwork_56_64bit = 1;" as suggested on other forums.

A: Storable documentation says:

Storable writes a file header which contains the sizes of various C language types for the C compiler that built Storable (when not writing in network order), and will refuse to load files written by a Storable not on the same (or compatible) architecture.

In the same section, they suggest that the basic use of Storable is a local and FAST persistence method. However, you can use nstore to store the persisted structure in network byte order. The result will be that it reads and stores slower but works across all platforms.
So the suggestion is that you'll have to use the 64-bit machine to read and re-store the data in network order using nstore.

A: I know the docs indicate it's supposed to be possible, but I've never been able to get it to work except by using nfreeze/nstore* on the the 64-bit machine.


text:
Q: Dapper.NET mapping with Data Annotations So I have a class with a property like this:
public class Foo
{
  [Column("GBBRSH")
  public static string Gibberish { get; set;}
  ....
}

For saving data, I have it configured so that the update/insert statements use a custom function:
public static string GetTableColumnName(PropertyInfo property)
{
  var type = typeof(ColumnAttribute);
  var prop = property.GetCustomAttributes(type, false);

  if (propr.Count() > 0)
    return ((ColumnAttribute)prop.First()).Name;
  return property.Name;
}

This handles fine, but I noticed that when I go to retrieve the data, it isn't actually pulling data back via the function for this particular column. I noticed that the other data present was pulled, but the column in question was the only field with data that didn't retrieve.
1)  Is there a way to perhaps use the GetTableColumnName function for the retrieval part of Dapper?
2)  Is there a way to force Dapper.NET to throw an exception if a scenario like this happens? I really don't want to have a false sense of security that everything is working as expected when it actually isn't (I get that I'm using mapping that Dapper.NET doesn't use by default, but I do want to set it up in that manner).
edit:
I'm looking in the SqlMapper source of Dapper and found:
 private static IEnumerable<T> QueryInternal<T>(params) // my knowledge of generics is limited, but how does this work without a where T : object?
 {
   ...
   while (reader.Read())
   {
     yield return (T)func(reader);
   }
   ...
 }

so I learned about two things after finding this. Read up on Func and read up on yield (never used either before). My guess is that I need to pass reader.Read() to another function (that checks against column headers and inserts into objects appropriately) and yield return that?

A: You could change your select statement to work with aliases like "SELECT [Column("GBBRSH")] AS Gibberish" and provide a mapping between the attribute name and the poco property name.
That way, Dapper would fill the matching properties, since it only requires your POCO's to match the exact name of the column.


text:
Q: How to dynamically change Date Box Mode based on device I want to show a device specific date picker using the JQM Datebox plugin.
The AngularJS View by default contains Date Box mode option as - "datebox".
Then if device is iPhone, it should be changed to 'flipbox'.
Using following piece of code which is not working:
$("#Date1").data('options', '{"mode": "flipbox", "useNewStyle":true}')
$('#Date1').trigger('datebox', { 'method': 'dorefresh' });

A:
Here is a jsFiddle with the mode switch:  http://jsfiddle.net/ezanker/2ffpP/

In markup  I created the date input with a mode of datebox.
<input name="Date1" id="Date1" type="date" data-role="datebox" data-options='{"mode": "datebox"}' />

Then in code within the pageinit switch the mode with $('element').datebox({opt, value}) (api doc here: http://dev.jtsage.com/jQM-DateBox2/demos/api/events.html
$(document).on('pageinit', '#page1', function () {
    //check if iOS, if true run next line
    $('#Date1').datebox({"mode": "flipbox"});
});

In the fiddle I also included a couple of buttons to toggle the mode back and forth...


text:
Q: How to replace Java linewrap with HTML linewrap? I have a response that I get from a Java server that has some line wrap characters. I am binding it to a HTML span element and displaying it like so
{{error}}

Rendered as -
"This port is currently in use. /n/nWould you like to proceed?"

I'm trying to replace the /n/n with HTML understandable line break but not having any luck.
I tried replacing the "error" string with
replace("/n/n", "
")

and other variations of the above.
Also tried using
white-space: pre-line

But none of it works. I'm doubtful if this is because the string is rendered within quotes in the HTML but cant figure out why. Normally when I bind a string, it is displayed without quotes.
{{error}}

usually translates to
Some error

and not
"Some Error"

Could this be the problem? If it is, why is it happening? I don't see quotes anywhere else in the markup for bound text. Or is there a different solution for line wrap?
Any help is greatly appreciated.