text:
Q: How to install MongoDB 4.4 on Alpine 3.11 I want to install MongoDB 4.4 on Alpine 3.11, but it appears that Alpine has removed the MDB package because of BSD license.
I have to build the image myself, but I have some errors...
Firstly, I clone de git repository :
git clone --branch v4.4 --single-branch --depth 1 https://github.com/mongodb/mongo.git /tmp/mongo

Then I install some packages :
apk add --no-cache --virtual build-pack \
        boost-build=1.69.0-r1 \
        boost-filesystem=1.71.0-r1 \
        boost-iostreams=1.71.0-r1 \
        boost-program_options=1.71.0-r1 \
        boost-python3=1.71.0-r1 \
        boost-system=1.71.0-r1 \
        build-base=0.5-r1 \
        busybox=1.31.1-r9 \
        curl-dev=7.67.0-r0 \
        cmake=3.15.5-r0 \
        db=5.3.28-r1 \
        isl=0.18-r0 \
        libbz2=1.0.8-r1 \
        libc-dev=0.7.2-r0 \
        libgcc=9.2.0-r4
        libpcrecpp=8.43-r0 \
        libsasl=2.1.27-r5 \
        libssl1.1=1.1.1d-r3 \
        libstdc++=9.2.0-r4 \
        linux-headers=4.19.36-r0 \
        g++=9.2.0-r4 \
        gcc=9.2.0-r4 \
        gmp=6.1.2-r1 \
        jsoncpp=1.9.2-r0  \
        jsoncpp-dev=1.9.2-r0 \
        mpc1=1.1.0-r1 \
        mpfr4=4.0.2-r1 \
        musl=1.1.24-r2 \
        musl-dev=1.1.24-r2 \
        openssl-dev=1.1.1d-r3 \
        pcre=8.43-r0 \
        pkgconf=1.6.3-r0 \
        python3=3.8.2-r0 \
        py3-cheetah=3.2.4-r1 \
        py3-crypto=2.6.1-r5 \
        py3-openssl=19.1.0-r0 \
        py3-psutil=5.6.7-r0 \
        py3-yaml=5.3.1-r0 \
        scons=3.1.1-r0 \
        snappy=1.1.7-r1 \
        xz-libs=5.2.4-r0 \
        yaml-cpp=0.6.3-r0 \
        yaml-cpp-dev=0.6.3-r0 \
        zlib=1.2.11-r3

I have this error when I use this command python3 buildscripts/scons.py MONGO_VERSION=4.4 --prefix=/opt/mongo mongod --disable-warnings-as-errors :
src/mongo/util/processinfo_linux.cpp:50:10: fatal error: gnu/libc-version.h: No such file or directory
...
scons: building terminated because of errors.
build/opt/mongo/util/processinfo_linux.o failed: Error 1

Any idea ?
Thanks.
EDIT : I have tried 4.2.5 version, I have this error message and :
In file included from src/third_party/mozjs-60/platform/x86_64/linux/build/Unified_cpp_js_src29.cpp:11:
src/third_party/mozjs-60/extract/js/src/threading/posix/Thread.cpp: In function 'void js::ThisThread::GetName(char*, size_t)':
src/third_party/mozjs-60/extract/js/src/threading/posix/Thread.cpp:210:8: error: 'pthread_getname_np' was not declared in this scope; did you mean 'pthread_setname_np'?
 210 |   rv = pthread_getname_np(pthread_self(), nameBuffer, len);
     |        ^~~~~~~~~~~~~~~~~~
     |        pthread_setname_np
scons: *** [build/opt/third_party/mozjs-60/platform/x86_64/linux/build/Unified_cpp_js_src29.o] Error 1
scons: building terminated because of errors.
build/opt/third_party/mozjs-60/platform/x86_64/linux/build/Unified_cpp_js_src29.o failed: Error 1

With these packages :
apk add --no-cache --virtual build-pack \
        build-base=0.5-r1 \
        cmake=3.15.5-r0 \
        curl-dev=7.67.0-r0 \
        libgcc=9.2.0-r4 \
        libssl1.1=1.1.1d-r3 \
        libstdc++=9.2.0-r4 \
        linux-headers=4.19.36-r0 \
        g++=9.2.0-r4 \
        gcc=9.2.0-r4 \
        openssl-dev=1.1.1d-r3 \
        musl=1.1.24-r2
        python3=3.8.2-r0 \
        py3-cheetah=3.2.4-r1 \
        py3-crypto=2.6.1-r5 \
        py3-openssl=19.1.0-r0 \
        py3-psutil=5.6.7-r0 \
        py3-yaml=5.3.1-r0 \
        scons=3.1.1-r0 \
        libc-dev=0.7.2-r0

A: Just run:
apk update && apk add openrc


text:
Q: Paypal Express Checkout API not charging the money after payment I'm using the Paypal Express Checkout API for processing Paypal and VISA payments.
My code redirects the user to the paypal page, and after presents form where authentication occurs.   Then I proceed with authentication and click the Pay Now button.
I am redirected to the return URL. Apparently everything seems to be ok, but I never receive the money on the merchant account and the money is never charged from the buyer account.
Here is my code for requesting the the token:
private function _proceed_to_paypal($total_amount = false, $id_order = false, $description = false) {

    if ($total_amount === false || $id_order === false) {
        return false;
    }

    $this->load->library('paypal_functions');

    $this->paypal_functions->init();

    // ==================================
    // PayPal Express Checkout Module
    // ==================================

    //'------------------------------------
    //' The paymentAmount is the total value of
    //' the shopping cart, that was set
    //' earlier in a session variable
    //' by the shopping cart page
    //'------------------------------------
    $paymentAmount = $total_amount;

    //'------------------------------------
    //' The currencyCodeType and paymentType
    //' are set to the selections made on the Integration Assistant
    //'------------------------------------
    $currencyCodeType = "EUR";
    $paymentType = "Sale";

    //'------------------------------------
    //' The returnURL is the location where buyers return to when a
    //' payment has been succesfully authorized.
    //'
    //' This is set to the value entered on the Integration Assistant
    //'------------------------------------
    $returnURL = site_url('payment/success');

    //'------------------------------------
    //' The cancelURL is the location buyers are sent to when they hit the
    //' cancel button during authorization of payment during the PayPal flow
    //'
    //' This is set to the value entered on the Integration Assistant
    //'------------------------------------
    $cancelURL = site_url('payment/cancel');

    //'------------------------------------
    //' Calls the SetExpressCheckout API call
    //'
    //' The CallShortcutExpressCheckout function is defined in the file PayPalFunctions.php,
    //' it is included at the top of this file.
    //'-------------------------------------------------
    $resArray = $this->paypal_functions->CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $description);
    $ack = strtoupper($resArray["ACK"]);
    if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING") {
        $this->paypal_functions->RedirectToPayPal($resArray["TOKEN"]);
    } else  {

        $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
        $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
        $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
        $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);

        echo "SetExpressCheckout API call failed. ";
        echo '
';
        echo "Detailed Error Message: " . $ErrorLongMsg;
        echo '
';
        echo "Short Error Message: " . $ErrorShortMsg;
        echo '
';
        echo "Error Code: " . $ErrorCode;
        echo '
';
        echo "Error Severity Code: " . $ErrorSeverityCode;
        echo '
';
    }

}

The paypal_functions Lib:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class Paypal_functions {

private $PROXY_HOST = '127.0.0.1';
private $PROXY_PORT = '808';

// signals the test mode
private $SandboxFlag = false;

/* Paypal credentials */
private $API_UserName="xxx";
private $API_Password="xxx";
private $API_Signature="xxx";

// BN Code  is only applicable for partners
private $sBNCode = "PP-ECWizard";

private $USE_PROXY = false;
private $version = 0;

private $API_Endpoint;
private $PAYPAL_URL;

private $gv_ApiErrorURL;

/*
' Define the PayPal Redirect URLs.
'   This is the URL that the buyer is first sent to do authorize payment with their paypal account
'   change the URL depending if you are testing on the sandbox or the live PayPal site
'
' For the sandbox, the URL is       https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
' For the live site, the URL is        https://www.paypal.com/webscr&cmd=_express-checkout&token=
*/

public function init() {
    if ($this->SandboxFlag == true) {
        $this->API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
        $this->PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
    } else {
        $this->API_Endpoint = "https://api-3t.paypal.com/nvp";
        $this->PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
    }

    $this->USE_PROXY = false;
    $this->version= "93";

}

/* An express checkout transaction starts with a token, that
   identifies to PayPal your transaction
   In this example, when the script sees a token, the script
   knows that the buyer has already authorized payment through
   paypal.  If no token was found, the action is to send the buyer
   to PayPal to first authorize payment
   */

/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose:  Prepares the parameters for the SetExpressCheckout API Call.
' Inputs:
'       paymentAmount:      Total value of the shopping cart
'       currencyCodeType:   Currency code value the PayPal API
'       paymentType:        paymentType has to be one of the following values: Sale or Order or Authorization
'       returnURL:          the page where buyers return to after they are done with the payment review on PayPal
'       cancelURL:          the page where buyers return to when they cancel the payment review on PayPal
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
public function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $description) {
    //------------------------------------------------------------------------------------------------------------------------------------
    // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation

    $nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
    $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
    $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;

    $nvpstr = $nvpstr . "&SOLUTIONTYPE=" . 'Sole';
    $nvpstr = $nvpstr . "&LANDINGPAGE=" . 'Billing';

    //'---------------------------------------------------------------------------------------------------------------
    //' Make the API call to PayPal
    //' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
    //' If an error occured, show the resulting errors
    //'---------------------------------------------------------------------------------------------------------------
    $resArray = $this->hash_call("SetExpressCheckout", $nvpstr);
    $ack = strtoupper($resArray["ACK"]);
    if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
    {
        $token = urldecode($resArray["TOKEN"]);
        $_SESSION['TOKEN']=$token;
    }

    return $resArray;
}

/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose:  Prepares the parameters for the SetExpressCheckout API Call.
' Inputs:
'       paymentAmount:      Total value of the shopping cart
'       currencyCodeType:   Currency code value the PayPal API
'       paymentType:        paymentType has to be one of the following values: Sale or Order or Authorization
'       returnURL:          the page where buyers return to after they are done with the payment review on PayPal
'       cancelURL:          the page where buyers return to when they cancel the payment review on PayPal
'       shipToName:     the Ship to name entered on the merchant's site
'       shipToStreet:       the Ship to Street entered on the merchant's site
'       shipToCity:         the Ship to City entered on the merchant's site
'       shipToState:        the Ship to State entered on the merchant's site
'       shipToCountryCode:  the Code for Ship to Country entered on the merchant's site
'       shipToZip:          the Ship to ZipCode entered on the merchant's site
'       shipToStreet2:      the Ship to Street2 entered on the merchant's site
'       phoneNum:           the phoneNum  entered on the merchant's site
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
public function CallMarkExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL,
                                  $cancelURL, $shipToName, $shipToStreet, $shipToCity, $shipToState,
                                  $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
                                ) {
    //------------------------------------------------------------------------------------------------------------------------------------
    // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation

    $nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
    $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
    $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
    $nvpstr = $nvpstr . "&ADDROVERRIDE=1";
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTONAME=" . $shipToName;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET=" . $shipToStreet;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET2=" . $shipToStreet2;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCITY=" . $shipToCity;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTATE=" . $shipToState;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" . $shipToCountryCode;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOZIP=" . $shipToZip;
    $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOPHONENUM=" . $phoneNum;

    $_SESSION["currencyCodeType"] = $currencyCodeType;
    $_SESSION["PaymentType"] = $paymentType;

    //'---------------------------------------------------------------------------------------------------------------
    //' Make the API call to PayPal
    //' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
    //' If an error occured, show the resulting errors
    //'---------------------------------------------------------------------------------------------------------------
    $resArray=hash_call("SetExpressCheckout", $nvpstr);
    $ack = strtoupper($resArray["ACK"]);
    if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
    {
        $token = urldecode($resArray["TOKEN"]);
        $_SESSION['TOKEN']=$token;
    }

    return $resArray;
}

/*
'-------------------------------------------------------------------------------------------
' Purpose:  Prepares the parameters for the GetExpressCheckoutDetails API Call.
'
' Inputs:
'       None
' Returns:
'       The NVP Collection object of the GetExpressCheckoutDetails Call Response.
'-------------------------------------------------------------------------------------------
*/
public function GetShippingDetails( $token ) {
    //'--------------------------------------------------------------
    //' At this point, the buyer has completed authorizing the payment
    //' at PayPal.  The function will call PayPal to obtain the details
    //' of the authorization, incuding any shipping information of the
    //' buyer.  Remember, the authorization is not a completed transaction
    //' at this state - the buyer still needs an additional step to finalize
    //' the transaction
    //'--------------------------------------------------------------

    //'---------------------------------------------------------------------------
    //' Build a second API request to PayPal, using the token as the
    //'  ID to get the details on the payment authorization
    //'---------------------------------------------------------------------------
    $nvpstr="&TOKEN=" . $token;

    //'---------------------------------------------------------------------------
    //' Make the API call and store the results in an array.
    //' If the call was a success, show the authorization details, and provide
    //'     an action to complete the payment.
    //' If failed, show the error
    //'---------------------------------------------------------------------------
    $resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
    $ack = strtoupper($resArray["ACK"]);
    if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING")
    {
        $_SESSION['payer_id'] = $resArray['PAYERID'];
    }
    return $resArray;
}

/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose:  Prepares the parameters for the GetExpressCheckoutDetails API Call.
'
' Inputs:
'       sBNCode:    The BN code used by PayPal to track the transactions from a given shopping cart.
' Returns:
'       The NVP Collection object of the GetExpressCheckoutDetails Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
public function ConfirmPayment( $FinalPaymentAmt )
{
    /* Gather the information to make the final call to
       finalize the PayPal payment.  The variable nvpstr
       holds the name value pairs
       */

    //Format the other parameters that were stored in the session from the previous calls
    $token              = urlencode($_SESSION['TOKEN']);
    $paymentType        = urlencode($_SESSION['PaymentType']);
    $currencyCodeType   = urlencode($_SESSION['currencyCodeType']);
    $payerID            = urlencode($_SESSION['payer_id']);

    $serverName         = urlencode($_SERVER['SERVER_NAME']);

    $nvpstr  = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=' . $paymentType . '&PAYMENTREQUEST_0_AMT=' . $FinalPaymentAmt;
    $nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE=' . $currencyCodeType . '&IPADDRESS=' . $serverName;

     /* Make the call to PayPal to finalize payment
        If an error occured, show the resulting errors
        */
    $resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);

    /* Display the API response back to the browser.
       If the response from PayPal was a success, display the response parameters'
       If the response was an error, display the errors received using APIError.php.
       */
    $ack = strtoupper($resArray["ACK"]);

    return $resArray;
}

/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose:  This function makes a DoDirectPayment API call
'
' Inputs:
'       paymentType:        paymentType has to be one of the following values: Sale or Order or Authorization
'       paymentAmount:      total value of the shopping cart
'       currencyCode:       currency code value the PayPal API
'       firstName:          first name as it appears on credit card
'       lastName:           last name as it appears on credit card
'       street:             buyer's street address line as it appears on credit card
'       city:               buyer's city
'       state:              buyer's state
'       countryCode:        buyer's country code
'       zip:                buyer's zip
'       creditCardType:     buyer's credit card type (i.e. Visa, MasterCard ... )
'       creditCardNumber:   buyers credit card number without any spaces, dashes or any other characters
'       expDate:            credit card expiration date
'       cvv2:               Card Verification Value
'
'-------------------------------------------------------------------------------------------
'
' Returns:
'       The NVP Collection object of the DoDirectPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/

public function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
                        $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
                        $countryCode, $currencyCode )
{
    //Construct the parameter string that describes DoDirectPayment
    $nvpstr = "&AMT=" . $paymentAmount;
    $nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
    $nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
    $nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
    $nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
    $nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
    $nvpstr = $nvpstr . "&CVV2=" . $cvv2;
    $nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
    $nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
    $nvpstr = $nvpstr . "&STREET=" . $street;
    $nvpstr = $nvpstr . "&CITY=" . $city;
    $nvpstr = $nvpstr . "&STATE=" . $state;
    $nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
    $nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];

    $resArray=hash_call("DoDirectPayment", $nvpstr);

    return $resArray;
}

/**
  * -------------------------------------------------------------------------------------------------------------------------------------------
  * hash_call: Function to perform the API call to PayPal using API signature
  * @methodName is name of API  method.
  * @nvpStr is nvp string.
  * returns an associtive array containing the response from the server.
  * -------------------------------------------------------------------------------------------------------------------------------------------
*/
public function hash_call($methodName,$nvpStr)
{
    //declaring of global variables
    /*
    global $API_Endpoint, $this->version, $API_UserName, $API_Password, $API_Signature;
    global $this->USE_PROXY, $PROXY_HOST, $PROXY_PORT;
    global $gv_ApiErrorURL;
    global $sBNCode;
    */

    //setting the curl parameters.
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$this->API_Endpoint);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);

    //turning off the server and peer verification(TrustManager Concept).
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_POST, 1);

    //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
   //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
    if($this->USE_PROXY)
        curl_setopt ($ch, CURLOPT_PROXY, $this->PROXY_HOST. ":" . $this->PROXY_PORT);

    //NVPRequest for submitting to server
    $nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($this->version) . "&PWD=" . urlencode($this->API_Password) . "&USER=" . urlencode($this->API_UserName) . "&SIGNATURE=" . urlencode($this->API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($this->sBNCode);

    //setting the nvpreq as POST FIELD to curl
    curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

    //getting response from server
    $response = curl_exec($ch);

    //convrting NVPResponse to an Associative Array
    $nvpResArray = $this->deformatNVP($response);
    $nvpReqArray = $this->deformatNVP($nvpreq);
    $_SESSION['nvpReqArray']=$nvpReqArray;

    if (curl_errno($ch))
    {
        // moving to display page to display curl errors
          //$_SESSION['curl_error_no']=curl_errno($ch) ;
          //$_SESSION['curl_error_msg']=curl_error($ch);

          //Execute the Error handling module to display errors.
    }
    else
    {
         //closing the curl
        curl_close($ch);
    }

    return $nvpResArray;
}

/*'----------------------------------------------------------------------------------
 Purpose: Redirects to PayPal.com site.
 Inputs:  NVP string.
 Returns:
----------------------------------------------------------------------------------
*/
public function RedirectToPayPal ( $token )
{
    //global $PAYPAL_URL;

    // Redirect to paypal.com here
    $payPalURL = $this->PAYPAL_URL . $token . '&useraction=commit';
    header("Location: ".$payPalURL);
    exit;
}

/*'----------------------------------------------------------------------------------
 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
  * It is usefull to search for a particular key and displaying arrays.
  * @nvpstr is NVPString.
  * @nvpArray is Associative Array.
   ----------------------------------------------------------------------------------
  */
public  function deformatNVP($nvpstr)
{
    $intial=0;
    $nvpArray = array();

    while(strlen($nvpstr))
    {
        //postion of Key
        $keypos= strpos($nvpstr,'=');
        //position of value
        $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

        /*getting the Key and Value values and storing in a Associative Array*/
        $keyval=substr($nvpstr,$intial,$keypos);
        $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
        //decoding the respose
        $nvpArray[urldecode($keyval)] =urldecode( $valval);
        $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
     }
    return $nvpArray;
}

}

PS - This is the result of echoing $nvpstr before:
$resArray = $this->hash_call("SetExpressCheckout", $nvpstr);

-
&PAYMENTREQUEST_0_AMT=0.01&
PAYMENTREQUEST_0_PAYMENTACTION=Sale&
RETURNURL=http://localhost/site/payment/success&
CANCELURL=http://localhost/site/payment/cancel&
PAYMENTREQUEST_0_CURRENCYCODE=EUR&
SOLUTIONTYPE=Sole&
LANDINGPAGE=Billing

Thanks in advance!

A: Sounds like you're only completing the first part of the process.  Express Checkout consists of 3 separate calls:

*

*SetExpressCheckout

*GetExpressCheckoutDetails

*DoExpressCheckoutPayment
No money is processed until you've completed the final DoExpressCheckoutPayment call.
Review the Express Checkout Integration Guide for more details on this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: htaccess getting values from a subdomain and redirecting to new url I have a url setup like so
sub.domain.com/leaderboards/showlist/APPNAME/SCORE/DEVICEID
I'm trying to use the htaccess in the root of the website not the sub domain to foward that url to
domain2.com/get/APPNAME/leaderboards/SCORE/DEVICEID
I'm able to get this to work when I use this code in the subdomain htaccess
RewriteRule ^showList/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ http://domain2.com/get/$1/leaderboard/$2/$3/ [NC,L]

However this doesn't work in the root htaccess so I've tried a little bit of everything I found online and I can't figure out how to get the params like above. This is what it currently looks like and it doesn't do anything at all
RewriteCond %{HTTP_HOST} ^sub\.domain\.com$ [NC]
RewriteRule ^showList/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ http://domain2.com/get/$1/leaderboard/$2/$3 [NC,L]

From my understanding the RewriteCond should only include people on the sub domain and the rule should work the same as it does in the sub domain htaccess right?

A: I think the issue you're running into is that now you have the .htaccess file in a different directory.
The directive RewriteRule matches relative to the current directory so let's say the subdomain is in a folder called sub which is under the parent directory (which now contains the .htaccess), you'd need to match using RewriteRule ^sub/showList I believe.
Another way you could do it to keep things simple would be do your matches in RewriteCond against %{REQUEST_URI} and then use % backreferences to refer to those matches. See the example below:
RewriteCond %{HTTP_HOST} ^sub\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} ^/showList/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$
RewriteRule .* http://domain2.com/get/%1/leaderboard/%2/%3 [NC,L]


text:
Q: Dynamic Input Array with Image/file in Laravel 8 i am trying to do an update using dynamic for "education history" but there is an image also, i use eloquent to update too, for some reason the data is saved in the database but the image just tmp and cannot find in the folder.
    //count array data inputed
    for($incs=0; $incs < count($data_detail_user['institution_names']); $incs++) {
        // update education
        foreach( $data_detail_user['institution_names'] as $key => $file ){
                    // get old photo thumbnail
            $get_photo = Educations::where('id', $key)->first();

            // store photo
            $path = $file->store(
                'assets/education/thumbnail', 'public'
            );

            $education_user = Educations::find($incs);
            $education_user->detail_user_id = $detail_user['id'];
            $education_user->name = $data_detail_user['institution_names'][$incs];
            $education_user->course = $data_detail_user['education_courses'][$incs];
            $education_user->start = $data_detail_user['education_starts'][$incs];
            $education_user->graduate = $data_detail_user['education_graduates'][$incs];
            $education_user->address = $data_detail_user['education_addresses'][$incs];
            $education_user->regencies = $data_detail_user['education_regencies'][$incs];
            $education_user->provinces = $data_detail_user['education_provinces'][$incs];
            $education_user->country = $data_detail_user['education_countries'][$incs];
            $education_user->zip_code = $data_detail_user['education_zips'][$incs];
            $education_user->certificate = $data_detail_user['education_certificates'][$incs][$path];
            $education_user->save();

            $data_detail_user = 'storage/' .$get_photo['certificate'];
            if (File::exists($data_detail_user)) {
                File::delete($data_detail_user);
            } else {
                File::delete('storage/app/public/' .$get_photo['certificate']);
            }
        }
    }

[the error show Call to a member function store() on string]
this is the screenshoot of the error
[1]: https://i.stack.imgur.com/l96sm.png

A: $path = $request->file('path')->store('public/post');

I assume you have a directory where the image is suppose to be stored that's why i created the post directory after public.


text:
Q: Backendless - Trying to retrieve specific data from Users table I'm making an app for my final project in school..
I've made an Login page and inside the login page I need to retrieve a data from a specific column named Permissions and then check the permission to declare to which next Activity the app will take the user..
In simple words I need something like this:
public void login(View view){ //button
   if(Permission == admin){ // get the permission from the user that is logging in.. lets say from username = "Bob123"
      //do something..
      }
}

A: A possible solution is to:
create an instance of BackendlessUser in your application class:
    public static BackendlessUser user;

If you have added the permission column to the Users table and you have made the email an identity column in the schema you can use the following code to retrieve a BackendlessUser object and direct the user to the correct Activity based on his permission in the Users table:
public void login(String emailToLogin){
                DataQueryBuilder dataQueryBuilder = DataQueryBuilder.create();
                dataQueryBuilder.setWhereClause("email = " + "'" + emailToLogin + "'");
                Backendless.Data.of(BackendlessUser.class).find(dataQueryBuilder,
                        new AsyncCallback<List<BackendlessUser>>() {
                    @Override
                    public void handleResponse(List<BackendlessUser> response) {
                        if (response.get(0).getProperty("permission").equals("permissionOne")) {
                            Intent intent = new Intent(LoginActivity.this, permissionOneActivity.class);
                            startActivity(intent);
                        }//end if

                        else if (response.get(0).getProperty("permission").equals("permissionTwo")) {
                            Intent intent = new Intent(LoginActivity.this, permissionTwoActivity.class);
                            startActivity(intent);
                        }//end else if

                    }//end handleResponse

                    @Override
                    public void handleFault(BackendlessFault fault) {
                        //add error handling here...
                    }//end handleFault
                });}

In the code mentioned below, the response.get(0) will always return the correct user since we are getting the BackendlessUser object based on his email that we set to be a Unique Identifier.
"permissionOne" and "permissionTwo" is whatever you have called your permissions, eg. "permissionOne" takes you to the admin Activity and "permissionTwo" takes you to the clients Activity.
response.get(0).getProperty("permission").equals("permissionOne")

This code myUserObject.getProperty("myColumnName"); retrieves any property you want from the Users table in Backendless
Hope this helps somebody.


text:
Q: Android Soundpool - Touch events I'm making a drumpad app with eight imagebuttons that play the sounds on button press. I have been trying to figure out how to make the press of a button more responsive as the problem is that Soundpool plays the file only when the button is released.
I found out there is a way to make the button react to touch using onTouchEvent, but I have no idea how to implement that to my code. I have tried using both .ogg and .wav filetypes for the sounds, but that's not the issue. I'm also planning to create buttons that loop the soundfile when the key is held down, but my major issue is how to make all the buttons response to touch, not release. The code:
package com.example.user.soundboard;
import android.os.Bundle;
import android.view.View;
import android.view.MotionEvent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

SoundPool mySound, mySound2, mySound3, mySound4, mySound5, mySound6, mySound7, mySound8;

int hihatId, kickId, snareId, clapId, snare2Id, hihat2Id, kick2Id, openHatId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mySound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mySound2 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mySound3 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mySound4 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mySound5 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mySound6 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mySound7 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mySound8 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

    hihatId = mySound.load(this, R.raw.ogghat30, 1);
    hihat2Id = mySound.load(this, R.raw.ogghihat14, 1);
    kickId = mySound.load(this, R.raw.oggkick, 1);
    kick2Id = mySound.load(this, R.raw.oggkick2, 1);
    snareId = mySound.load(this, R.raw.oggsnare8, 1);
    snare2Id = mySound.load(this, R.raw.oggsnare8, 1);
    clapId = mySound.load(this, R.raw.oggclap5, 1);
    openHatId = mySound.load(this, R.raw.ogghat24, 1);

}

public void playHihat(View view) {
    mySound.play(hihatId, 1, 1, 1, 0, 1);
}

public void playHihat2(View view) {
    mySound.play(hihat2Id, 1, 1, 1, 0, 1);
}

public void playOpenHat(View view) {
    mySound.play(openHatId, 1, 1, 1, 0, 1);
}

public void playKick(View view) {
    mySound.play(kickId, 1, 1, 1, 0, 1);
}

public void playKick2(View view) {
    mySound.play(kick2Id, 1, 1, 1, 0, 1);
}

public void playSnare(View view) {
    mySound.play(snareId, 1, 1, 1, 0, 1);
}

public void playSnare2(View view) {
    mySound.play(snare2Id, 1, 1, 1, 0, 1);
}

public void playClap(View view) {
    mySound.play(clapId, 1, 1, 1, 0, 1);
}

For the ImageButtons I'm currently using onClick method in the Layout.
Thanks for the help!

A: Instead of OnClickListener you have to use OnTouchListener.
yourButton.setOnTouchListener(new OnTouchListener() {
   @Override
    public boolean onTouch(View v, MotionEvent event) {
       if(event.getAction() == MotionEvent.ACTION_UP){
           // Release sound on touch up
           return true;
       } else if(event.getAction() == MotionEvent.ACTION_DOWN){
           // Play sound
           return true;
       }
        return false;
    }
});

A: You can set onTouchEvenListener to your view so then you can play your sounds reacting that touch events.
Here you have an example:
yourButtonView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    //Fired when you touch the button
                    break;

                case MotionEvent.ACTION_MOVE:
                    //Fired once you are touching button and you move your finger without release the button
                    break;

                case MotionEvent.ACTION_UP:
                    //Fired when you stop touching the button
                    break;
            }
            return true;
        }
    });


text:
Q: Validate data in Radgrid before changing pages I want to validate the users changes on a page before allowing them to go to another page.  If the validation fails I want to stop the pager from changing the page.
For example:
protected void rgOrderItem_PageIndexChanged(object source, GridPageChangedEventArgs e)
{
    if (Mapvalues(false))
    {
        rgOrderItem.CurrentPageIndex = LastPageIndex;
        rgOrderItem.DataBind();
    }
}

This does not work.  The pager changes regardless.  Anyone know how to stop a page change event?
Thanks, Tony

A: Please try with the below code snippet.
protected void RadGrid1_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e)
{
    if (Mapvalues(false))
    {
        e.Canceled = true; //Prevent to execute pagging functionality
    }
}
protected void RadGrid1_PageIndexChanged(object sender, GridPageChangedEventArgs e)
{
    if (Mapvalues(false))
    {
        e.Canceled = true; //Prevent to execute pagging functionality
    }
}


text:
Q: CSS: change style to checkbox list I have a checkbox list. I would like to change the style in order to highlight items differently. Please see first and second link showing what I need.
My problem is that the html code doesn't change when an item is selected. I need something like class="selected", I guess...
http://dl.dropbox.com/u/72686/Picture%201.png
http://dl.dropbox.com/u/72686/viewsFilter2.png
thanks

A: Rohancragg's answer is good, but I'd encourage your urge to use a class name for control. You don't give HTML, but assuming there's a containing element around your label and checkbox, doing
$("#content input[type='checkbox'], #content label").click(function(){
  $(this).parent().toggleClass("selected");
});

(with #content just being some larger container they're all in, so you don't accidentally apply styles to things outside the area you're interested in) should work. Then in your CSS you can apply styles to several elements and not have to edit your jQuery just to change styles.
.selected { background-color:blue; }
.selected label { font-weight:bold; color:#ffffff; }

and so on.

A: This should prove useful to you, good stuff there.

A: You could use JQuery and style any elements that are jQuery(':checked') [Description: Matches all elements that are checked] (works for checkboxes and radio buttons).
You would assign a function to the .click event of all of the checkboxes in question - as in the example on the page:
$(":checkbox").click(countChecked);

To each checked checkbox you would want to use the .css( propertyName, value ) setter to manipulate the css attributes
Don't forget to also unstyle the checkboxes as they become unchecked...


text:
Q: Excel - enter time duration in mm:ss.00 format (without hrs or colons) I am trying to create an Excel spreadsheet that I can record times for competitors competing in an event. I need to show mm:ss.00 and I would love to be able to do this without entering in colons or hours.
I have tried this code in VBA and it works great however it only shows mm:ss not the split seconds. Does anyone know how I could edit this code to include the split seconds?
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Intrsct As Range, Cell As Range, s As String
    Dim mins As Long, secs As Long, t As Date

    Set Intrsct = Intersect(Range("G13:G104"), Target)
    If Intrsct Is Nothing Then Exit Sub

    Application.EnableEvents = False
        For Each Cell In Intrsct
            s = Cell.Text
            If s = "" Then
                Cell.NumberFormat = "@"
            ElseIf Len(s) > 4 Then
                Cell.Clear
                Cell.NumberFormat = "@"
             Else
                s = Right("0000" & s, 4)
                If s Like "####" Then
                    mins = CLng(Left(s, 2))
                    secs = CLng(Right(s, 2))
                    t = TimeSerial(0, mins, secs)
                    Cell.NumberFormat = "[mm]:ss"
                    Cell.Value = t
                Else
                    Cell.Clear
                    Cell.NumberFormat = "@"
                End If
            End If
        Next Cell
    Application.EnableEvents = True
End Sub

A: Format your cells with the following custom format 00\:00\.00.

A: It seems TimeSerial function accepts only integer values as its parameters, so the split seconds cannot by passed here. Same is valid for worksheet function TIME
But time is represented as number in this format:
Hours/24 + Minutes/(24*60) + Second/(24*60*60)
So if you get this number, you can use your custom format with second fraction for it! (In the screenshot mm:ss.00 is used)

See an example Excel Online file showing the difference between time values generated by TIME function and custom formula. (Unfortunately, Excel online does not support creating a custom number format and only mm:ss.0 is available there.)

A: It does not show the split seconds you enter because you do not allow it to.
As written, your macro can only have a value output if you entered four or less characters in the cell.
More than four, the macro clears the entry.
Four or less, it creates a time entry in the cell.
Notice that the entry will be minutes (the left two characters) and seconds (the right two characters) made from a four or less character s.
So if you actually do enter the split seconds, the entry gets cleared and no time is placed there.
Worse, the TimeSerial() creation step makes sure the result is ONLY mm:ss.
You need to revisit how to treat you entry string. You must pass at least six characters into the final steps.
To avoid any limitations mentioned with TimeSerial(), perhaps do the steps already there, though using the left two characters and the mid third and fourth characters of your string to create the TimeSerial() value, then add the right two characters (divided by (24*60*60*100) so it actually IS split seconds being added.
Or just take the string dividing each component by the appropriate divisor (minutes:  (24*60) and seconds:  (24*60*60)), place the value in the cell, and apply the mm:ss.00 formatting. Excel itself is happy to allow up to thousandths to be shown (mm:ss.000).


text:
Q: How to make recyclerview item bigger on click? Actually I wanna make the current focused recyclerview item bigger than others . So I tried to refer this question .But it couldn't solve my issue so I wonder how to solve this issue.
Code:
public MyViewHolder(final View root) {
        super(root);
        root.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // run scale animation and make it bigger
                    Animation anim = AnimationUtils.loadAnimation(root.getContext(), R.anim.scale_in_tv);
                    root.startAnimation(anim);
                    anim.setFillAfter(true);
                } else {
                    // run scale animation and make it smaller
                    Animation anim = AnimationUtils.loadAnimation(root.getContext(), R.anim.scale_out_tv);
                    root.startAnimation(anim);
                    anim.setFillAfter(true);
                }
            }
        });
        ButterKnife.bind(this, root);
    }


text:
Q: Spring Data query by nested collection method signature I have User and Role entities. There is a many to many relation between them. How can I define repository method for finding all users having a specified role? I tried findByRolesContaining, findByRolesContains but both seems not to work.
Do I need to use native query or is it possible with method declaration?
User entity
@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(nullable = false, unique = true)
    private String username;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_role",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Collection<Role> roles;

    private String firstName;

    private String lastName;

    private String password;

    private boolean enabled;

    // getters and setters ...
}

Role entity
@Entity
public class Role {

    public static final String SUPER_ADMIN = "SUPER_ADMIN";

    public static final String PROJECT_MANAGER = "PROJECT_MANAGER";

    public static final String DEVELOPER = "DEVELOPER";

    public static final String CLIENT = "CLIENT";

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "roles")
    private Collection<User> users;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "role_privilege",
            joinColumns = @JoinColumn(name = "role_id"),
            inverseJoinColumns = @JoinColumn(name = "privilege_id")
    )
    private Collection<Privilege> privileges;

    public Role() {

    }

    public Role(String name) {

        this.name = name;
    }

    public Long getId() {

        return id;
    }

    public void setId(Long id) {

        this.id = id;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public Collection<User> getUsers() {

        return users;
    }

    public void setUsers(Collection<User> users) {

        this.users = users;
    }

    public Collection<Privilege> getPrivileges() {

        return privileges;
    }

    public void setPrivileges(Collection<Privilege> privileges) {

        this.privileges = privileges;
    }
}

I need a method for my UserRepository interface like
List<User> findByRole(Role role);
Which will return all users who has role specified in the parameter (which is contained in User.roles collection.

A: I believe that simply findByRoles should be enough.
I would also recommend using @Query annotation with JPQL anytime you have problems with method names.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query


text:
Q: Ultrarelativistic limit for neutrinos: Why is this approximation working? In this section of the Wikipedia article on neutrino oscillations, a neutrino mass eigenstate $\left|\nu_i\right>$ is written as
$$\left|\nu_i(t)\right> = e^{-i(E_it-\vec p_i\cdot\vec{x})} \left|\nu_i(0)\right>$$
where $E_i$ is the energy of the mass eigenstate $i$ (rest energy + kinetic energy, as I understand). Then the first approximation is made, using $|\vec p_i| = p_i \gg m_i$ to obtain
$$E_i = \sqrt{p_i^2 + m_i^2} \approx p_i + \frac{m_i^2}{2p_i}.$$
I'm fine with that step since that is just a Taylor expansion. But the next approximation confuses me:
$$p_i + \frac{m_i^2}{2p_i} \approx E + \frac{m_i^2}{2E}$$
where $E$ is "the total energy of the particle". How is this energy $E$ different than the energy $E_i$ from above? Even if $E$ is the "total energy", this sounds like we would expect that $E_i$ is smaller than the "total" energy $E$. But our approximation gives $E_i \approx E + \frac{m_i^2}{2E}$, so $E_i$ should be larger than $E$.

A: You have a point that there is a bit of doublethink in the WP article and many texts confusing subtlety mavens as reviewed, and resolved, in  Lipkin 2006, published.  (NB This paper, however, prefers the equivalent fixed energy option, unlike the equivalent old-fashioned fixed momentum option used here.)
Much of the confusion arises from unstated assumptions and "dancing about QM" thinking, instead of pursuing full QM calculations which lose the reader. I would just state the PDG 2019 summary/mnemonic p 9, (14.38). I'm calling it "mnemonic", as it is a memorable picture of several simplistic summaries, starting from different assumptions, yielding the same answer (and meant to discourage you from different summaries yielding wrong mnemonics).
The conceit is that your wave packet consisting of, say, two mass eigenstates, with $m_1<m_2$ are produced in entanglement at the meson decay "source" at a  sloppy point, so with common momentum p. Since their masses differ, slightly, so do their energies and hence their velocities,
$$
E_i=\sqrt{p^2+m_i^2}\approx p+ \frac {m_i^2}{2p}.
$$
So the wavepacket simulacrum ~ $e^{-itE_1} +ae^{-itE_2}$  evolves  like
$$
e^{-it(p+m_1^2/2p)} \left (1+ ae^{-it(m_2^2-m_1^2)/2p}\right ),
$$
so with "total" energy $E\approx p$ unobservable in the pure collective phase of the wavepacket, and differing from the momentum by $O(m^2)$, so we might as well put it in the denominator of the interesting  oscillation phase following a in lieu of the momentum, since  this only contributes slop of $O(m^4)$!
Again, $t\approx L $ for the wave packet, so the interesting oscillating probability at the detection point  amounts to
$$
\left |1+ae^{-iL(m_2^2-m_1^2)/2E}\right |^2=1+a^2 + 2a \sin \left ( {L(m_1^2-m_2^2)\over 2E}\right ) ~.
$$


text:
Q: How to export some rows of a MySQL table from a WHERE clause? How to export some rows of a MySQL table with where clause from a PHP script?
I have a MySQL say test and I want to create a importable .sql file for rows where id are between 10 and 100, using PHP script.
I want to create a sql file say test.sql which can be imported to MySQL database.
Mycode:
$con=mysqli_connect("localhost", "root","","mydatabase");

$tableName  = 'test';
$backupFile = '/opt/lampp/htdocs/practices/phpTest/test.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName WHERE id BETWEEN 10 AND 500";

$result = mysqli_query($con,$query);

This creates a test.sql file, but when I try to import, it gives error #1064.
My script only creates a file with rows with columns name and table sturcute or insert query.

A: Mysql Shell command
mysqldump -u user -p password -h host Database Table --where="Condition"> /path/exportFile.sql

Example
mysqldump -u user -p 123456 -h host Database Student --where="age > 10"> /path/exportFile.sql

A: As mentioned in the comments you can use mysqldump the following way.
mysqldump --user=... --password=... --host=... DB_NAME --where=<YOUR CLAUSE> > /path/to/output/file.sql

If you want this to be in your php file you can do the following
exec('mysqldump --user=... --password=... --host=... DB_NAME --where=<YOUR CLAUSE> > /path/to/output/file.sql');

A: In very simply way go to your phpMyAdmin
select you database whose particular rows you want to export
click on "SQL" (To Run SQL query/queries on database)
Write sql query and execute it
Like select * from test table limit 500 now what ever result come
Just at the bottom see "Query results operations"
just click on  Export
All done :-)

A: If you have exported data using OUTFILE then you have to import it using INFILE COMMAND
$con=mysqli_connect("localhost", "root","","mydatabase");

$tableName  = 'test';
$backupFile = '/opt/lampp/htdocs/practices/phpTest/test.sql';
$query      = "LOAD DATA INFILE '$backupFile' INTO TABLE $tableName";

$result = mysqli_query($con,$query);

OR you can make csv file using
 $con=mysqli_connect("localhost", "root","","mydatabase");
 $tableName  = 'test';
 $backupFile = '/opt/lampp/htdocs/practices/phpTest/test.sql';
 $query      = 'SELECT * INTO OUTFILE '."'$backupFile'".'
                FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '.'\'"\'
                LINES TERMINATED BY \'\n\'
                FROM '.$tableName.' WHERE id BETWEEN 10 AND 500';

 $result = mysqli_query($con,$query);

and then import this file.
Hope this works...


text:
Q: What is the empty / null value for a generic type in Scala Hi I'm learning Scala recently and I am confused about the null/nothing in Scala, in the following code, I'm implementing a customer linked list with generic type, and practice with variance
Defined my abstract class

/**
 * head = first element of the list
 * tail = remainder of the list
 * isEmpty = is this list empty
 * add(int) => new list with this element added
 * toString => a string representation of the list
 */
abstract class MyList[+T] {
  val head: T
  val tail: MyList[T]
  val isEmpty: Boolean
  def add[A >: T](n: A): MyList[A]
  def printElements: String
  override def toString: String = s"[$printElements]"
}

Two types of node class - Empty and Cons
class Empty[+T] extends MyList[T] {
  override val head: T = ??? // what should I implement at here???
  override val tail: MyList[T] = null
  override val isEmpty: Boolean = true

  override def add[A >: T](elem: A): MyList[A] = new Cons(elem, this)
  override def printElements: String = ""
}

class Cons[+T](h: T, t: MyList[T]) extends MyList[T] {
  override val head: T = h
  override val tail: MyList[T] = t
  override val isEmpty: Boolean = false

  override def add[A >: T](elem: A): MyList[A] = new Cons(elem, this)
  override def printElements: String = {
    if (tail.isEmpty) s"$head"
    else s"$head, ${tail.printElements}"
  }
}

Here is my test
object ListTest2 extends App {
  val listOfIntegers: MyList[Int] = new Cons(1, new Cons(2, new Empty[Int]))
  val listOfString: MyList[String] = new Cons("1", new Cons("2", new Empty[String]))

  println(listOfIntegers)
  println(listOfString)
}

I tried to define an object Empty for the last node in this linked list.
//object Empty extends MyList[Nothing] {
//  override val head: Nothing = throw new NoSuchElementException
//  override val tail: MyList[Nothing] = null
//  override val isEmpty: Boolean = true
//
//  override def add[B >: Nothing](elem: B): MyList[B] = new Cons(elem, Empty)
//  override def printElements: String = ""
//}

But it run with exception during the initiation.

A: Returning null from tail is not so good idea. This can lead to NPE. It's better to fail early, so just throw (if this is your semantics of the method). Better semantics is to return an empty list.
head also can throw. This is the only way to create a value of arbitrary type T. If you can change the signature then it's better to return Option[T] i.e. None instead of null or exception.
Normally, in a trait or abstract class, abstract members (head, tail, isEmpty) should be def. Whether they are actually def, val or lazy val is implementation details (and should be specified in inheritors).

I tried to define an object Empty for the last node in this linked list...
But it run with exception during the initiation.

You can avoid exception if you make head a lazy val (or def)
override lazy val head: Nothing = throw new NoSuchElementException

def can be overridden with def, val, lazy val.


text:
Q: middleware vs middlewares I am contributing at an open source project, and we got a message (https://github.com/gin-gonic/gin/issues/252) about our grammar at source code and documentation (we are not native english speakers).
Part of the message:

The plural of "middleware" is not "middlewares" but simply
  "middleware" -- just like "software."

But then I found some uses of the word, with an s at the end. For example:

*

*https://docs.newrelic.com/docs/agents/ruby-agent/frameworks/rack-middlewares
Which one is the correct way to say and write it?
Thank you in advance.

A: "Middleware" sounds better and seems more correct, especially if you're referring to a nonspecific class of items, each of which is an example of middleware.  In the counterexample that you found, the page is referring to specific instances of middleware (in this case, those developed under the Rack project).  I suspect the Ruby page you found that refers to "Rack middlewares" is emphasizing that it supports Rack's middleware products (and not others).  Going further, "Rack middlewares" seems to imply support for only some Rack middleware products but not all of them.  If the Ruby project supported all Rack middleware products, it would sound peculiar to say "Rack middlewares" instead of "Rack middleware."
(As a side note, I don't think I will ever use the word "middleware" so many times in one paragraph.  That was fun.)

A: wares by itself is plural but when it is a compound (software, silverware, hardware, Tupperwaretm) it tends to be singular/non-count. In online forums it frequently appears in the plural (softwares) since non-native speakers often frequent such forums. You'll see the word "informations" used online as well, especially by speakers in whose native language it does appear in the plural. English-speakers tend to use the singular there.  (You can Google informations site:stackoverflow.com to find examples.)

A: Middleware is plural already, but if you need to emphasize plurality when you use it, you can say something like "pieces of middleware" or "middleware modules."  (This is similar to how you can say "pieces of software" instead of "softwares" and "lines of code" instead of "codes.")


text:
Q: How to get the site root URL when using Wordpress gutenberg wp object I just created my first gutenberg block plugin using the npm package create-guten-block.
The edit function looks like the code you see below. But it gives a 404 not found on the apiFetch() call because the website lives in a folder, not in the root of the domain. In other words: The structure of the hostname is http://localhost/websitename/ not websitename.local.
edit: ( props ) => {
    if ( ! props.attributes.categories ) {
        wp.apiFetch( {
           url: '/wp-json/wp/v2/categories'
        }).then(categories => {
            props.setAttributes( {
                categories: categories
            });
        });
    }
    return (
        true
    );
}

So what would be the equivalent to PHP's get_site_url()? Is that data somewhere stored in the wp object? If so, where? Because I need to prepend /wp-json/wp/v2/categories with the right site URL.

A: Just found the solution myself.
In the init hook of your Gutenberg block plugin you can have a function that creates a global data object for you to use in the Wordpress editor file block.js.
So, in init.php inside of the init hook you could add:
wp_localize_script(
    'custom_block',
    'cs_data',
    [
        'siteUrl'       => get_site_url()
    ]
);

This way the global object cs_data is available in block.js. So the Fetch call could use the dynamic path now like this.
wp.apiFetch( {
    url: cs_data.siteUrl + '/wp-json/custom-data/v1/post-types'
} ).then( postTypes => {
    props.setAttributes( {
      postTypes: postTypes
    } );
} );

Hope this helps.

A: Try updating your site_url or home_url
site_url() will always be the live location where you can reach the site wheras home_url() would be where you have set your homepage.
Try setting the home_url() to the "http://localhost/websitename" by visiting and editing the General > Settings "WordPress address (URL)" field.
You could also define the paths programmatically by editing the wp-config.php:
define( 'WP_HOME', 'http://localhost/websitename/' );
define( 'WP_SITEURL', 'http://websitename.local' );

Then you could use get_home_url() to retrieve the correct path.


text:
Q: Screen Sharing stopped working after Lion upgrade Screen Sharing stopped working after I upgraded to Lion. Trying to connect back home to my still yet not upgraded Snow Leopard machine.
Logs says

PM Screen Sharing: MVS Codec - bad rectangle size - clossing connection 0

Has anyone else notice this?

A: Not at all - I have three classes of macs that all worked flawlessly with the upgrade to Lion. They all share their screens with the basic VNC technology:

*

*basic OS X - turn on VNC or remote management - bonjour location is local

*basic plus MobileMe back to my mac for locating the mac over the internet

*basic plus Screens app from edovia to locate the mac over the internet

I haven't seen a good Apple writeup of the Lion changes - but when you log in with your OS account rather than with the VNC password - you get a distinct loginwindow process for that account whether or not that user is shown as logged in locally. This change could be causing you grief.
Put another way - screen sharing and log in is now a virtual concept - you are no longer limited to one mac log in session or tied tightly to the physical screen. User A can be using the mac and User B logs in remotely and gets their own workspace rather than seeing what A is doing or forcing A to log off.
The writeup inside the screens app is nice if you have purchased it.

A: I found that Screen Sharing was working, but I couldn't see the window showing the remote machine. I could only figure that out by being in the same room with the remote machine. :)
When I changed the display quality setting, choosing "Full Quality", then choosing "Adaptive Quality" again, Screen Sharing resized the window showing the remote machine, then I could see it. I don't know whether the old window was 0x0 size or off-screen.
I hope this helps.

A: I had a problem with connecting from my Lion MacBook to my SL iMac. It turned out that I needed to go into Sharing under System Preferences on the iMac, toggle off "Screen Sharing" and toggle on "Remote Management." Then they started connecting again.


text:
Q: Google Dart Error

import 'dart:math';
import 'dart:io';
void main() {
  int guess;
  Random rand = new Random(); //create a random number generator
  int answer = rand.nextInt(100); //gets a random integer from 0 to 99 do {
  print("Enter your guess:");
  String temp = stdin.readLineSync(); //read in from the keyboard guess = int.parse(temp); //convert String to integer
  if (guess < answer) {
    print("Too low!");
  } else if (guess > answer) {
    print("Too high!");
  }
}
while (guess != answer);
  print("You got it!");
}

What is wrong?? I deleted the } in
} while (guess != answer);
print("You got it!");

and now in the console it says
Enter your guess:
32
Breaking on exception: object of type NoSuchMethodError

A: Your guess variable is always null as it's never assigned (it's commented out), try changing your code to:
import 'dart:math';
import 'dart:io';

void main() {
   int guess;
   Random rand = new Random(); //create a random number generator
   int answer = rand.nextInt(100); //gets a random integer from 0 to 99
   do {
      print("Enter your guess:");
      String temp = stdin.readLineSync(); //read in from the keyboard
      guess = int.parse(temp); //convert String to integer <-- the assignment is what's missing here

      if (guess < answer) {
          print("Too low!");
      } else if (guess > answer) {
          print("Too high!");
      }
   } while (guess != answer);
   print("You got it!");
}

There is a related issue with the readLineSync here which you might want to have a look.

A: I guess it is because guess is null and null has no >/< operator.
guess is null because you never assign a value.
If guess and answer are not equal this makes a perfect endless loop:
while (guess != answer);
  print("You got it!");
}

A: Wow I failed. Man im tired seems I was typing way to sloppy/fast and left some of my code in the comments :( found it right after seeing this post sigh.. this is the correct working code
import 'dart:math';
import 'dart:io';
void main() {
  int guess;
  Random rand = new Random(); //create a random number generator
  int answer = rand.nextInt(100); //gets a random integer from 0 to 99
do {
  print("Enter your guess:");
  String temp = stdin.readLineSync(); //read in from the keyboard
guess = int.parse(temp); //convert String to integer
  if (guess < answer) {
    print("Too low!");
  } else if (guess > answer) {
    print("Too high!");
  }
}
while (guess != answer);
  print("You got it!");
}

Thats enough learning of Dart for today. Thanks everyone for the quick replies seems the Dart community is active!
im off to bed! have a great day


text:
Q: React-native app: navigation.navigate is not a function (In 'navigation.navigate("Home")', 'navigation.navigate' is undefined)

const handleLogin = () => {
    auth
      .signInWithEmailAndPassword(email, password)
      .then((userCredentials) => {
        const user = userCredentials.user;
        console.log("Logged in with:", user.email);
        navigation.navigate("Home");
      })
      .catch((error) => alert(error.message));
  };

How can I fix this? I want to make it so that when I press the Login button, user is identified and then I go from login screen to home screen.

A: First you need to create navigation object by useNavigation hook like this.
const navigation = useNavigation()

For using useNavigation you need to install @react-navigation/native
npm i @react-navigation/native

Then import useNavigation from @react-navigation/native
import {useNavigation} from '@react-navigation/native'

Then you can navigate easily
const navigation = useNavigation()
navigation.navigate("Home")


text:
Q: What is the idea of "Plugins" in wordpress? What is the idea of "Plugins" in wordpress or any other platform,
How is any support Php Script , Plugins.
The idea, requirements etc. ....
Regards

A: A plugin is a library that allows you to extend your wordpress installation with additional functionality.
There exist a lot of third-party plugins, you should have a detailed look at the wordpress website to get familiar with the concept and the different kinds of plugins you can use in wordpress:
https://wordpress.org/plugins/

A: A plugin is a add on for the software programme, it lets you alter the way it looks, feels and works.
Some plugins are made be users (open source) and some are made by the people who wrote the programme.
Sometime there free, but the better ones take a lot of time to make, so they let you pay a small amount for it.

A: Plugin (wiki)

In computing, a plug-in (or plugin, extension, or add-on / addon) is a
  software component that adds a specific feature to an existing
  software application. When an application supports plug-ins, it
  enables customization.

Plugins in WordPress

Plugins are tools to extend the functionality of WordPress. The core
  of WordPress is designed to be lean, to maximize flexibility and
  minimize code bloat. Plugins offer custom functions and features so
  that each user can tailor their site to their specific needs.

Follow the instructions on How to write a Plugin in WordPress.

A WordPress Plugin is a program, or a set of one or more functions,
  written in the PHP scripting language, that adds a specific set of
  features or services to the WordPress weblog, which can be seamlessly
  integrated with the weblog using access points and methods provided by
  the WordPress Plugin Application Program Interface (API).

Tip: Go to WordPress' Plugin Directory and download some plugins and read the source code so you'll get a clearer idea. Also I've built a little plugin WP Fiddle once and it's  available on WordPress' Plugin directory.


text:
Q: Basic Way to Open Files in Ruby I'm trying to open local xml file and output its content in terminal.
I've tried this;
puts File.new('file.xml', 'r')

and this;
puts File.open('file.xml', 'r')

output from both is, instead of printing xml file to the screen;
#<File:0x00000000....>

A: Try this
puts File.read('file.xml')

or
puts File.open('file.xml').read

Documentation: IO.read, IO#read

A: I would suggest you to use block with File#open method. As with block,you don't need to close the file explicitly.Perform all your task inside the block with the file. The file will be closed automatically,when block will be terminated.
File.open('doc.txt','r') do |file|
  puts file.read
end

# >> ,"11: Agriculture, Forestry, Fishing and Hunting",,
# >> ,,"111: Crop Production",
# >> ,,,"111110: Soybean Farming"
# >> ,,,"111120: Oilseed (except Soybean) Farming"


text:
Q: Finding the path with the maximum minimal weight I'm trying to work out an algorithm for finding a path across a directed graph. It's not a conventional path and I can't find any references to anything like this being done already.
I want to find the path which has the maximum minimum weight.
I.e. If there are two paths with weights 10->1->10 and 2->2->2 then the second path is considered better than the first because the minimum weight (2) is greater than the minimum weight of the first (1).
If anyone can work out a way to do this, or just point me in the direction of some reference material it would be incredibly useful :)
EDIT:: It seems I forgot to mention that I'm trying to get from a specific vertex to another specific vertex. Quite important point there :/
EDIT2:: As someone below pointed out, I should highlight that edge weights are non negative.

A: I am copying this answer and adding also adding my proof of correctness for the algorithm:
I would use some variant of Dijkstra's. I took the pseudo code below directly from Wikipedia and only changed 5 small things:

*

*Renamed dist to width (from line 3 on)

*Initialized each width to -infinity (line 3)

*Initialized the width of the source to infinity (line 8)

*Set the finish criterion to -infinity (line 14)

*Modified the update function and sign (line 20 + 21)

1  function Dijkstra(Graph, source):
2      for each vertex v in Graph:                                 // Initializations
3          width[v] := -infinity  ;                                // Unknown width function from
4                                                                  // source to v
5          previous[v] := undefined ;                              // Previous node in optimal path
6      end for                                                     // from source
7
8      width[source] := infinity ;                                 // Width from source to source
9      Q := the set of all nodes in Graph ;                        // All nodes in the graph are
10                                                                 // unoptimized – thus are in Q
11      while Q is not empty:                                      // The main loop
12          u := vertex in Q with largest width in width[] ;       // Source node in first case
13          remove u from Q ;
14          if width[u] = -infinity:
15              break ;                                            // all remaining vertices are
16          end if                                                 // inaccessible from source
17
18          for each neighbor v of u:                              // where v has not yet been
19                                                                 // removed from Q.
20              alt := max(width[v], min(width[u], width_between(u, v))) ;
21              if alt > width[v]:                                 // Relax (u,v,a)
22                  width[v] := alt ;
23                  previous[v] := u ;
24                  decrease-key v in Q;                           // Reorder v in the Queue
25              end if
26          end for
27      end while
28      return width;
29  endfunction

Some (handwaving) explanation why this works: you start with the source. From there, you have infinite capacity to itself. Now you check all neighbors of the source. Assume the edges don't all have the same capacity (in your example, say (s, a) = 300). Then, there is no better way to reach b then via (s, b), so you know the best case capacity of b. You continue going to the best neighbors of the known set of vertices, until you reach all vertices.
Proof of correctness of algorithm:
At any point in the algorithm, there will be 2 sets of vertices A and B. The vertices in A will be the vertices to which the correct maximum minimum capacity path has been found. And set B has vertices to which we haven't found the answer.
Inductive Hypothesis: At any step, all vertices in set A have the correct values of maximum minimum capacity path to them. ie., all previous iterations are correct.
Correctness of base case: When the set A has the vertex S only. Then the value to S is infinity, which is correct.
In current iteration, we set

val[W] = max(val[W], min(val[V], width_between(V-W)))

Inductive step: Suppose, W is the vertex in set B with the largest val[W]. And W is dequeued from the queue and W has been set the answer val[W].
Now, we need to show that every other S-W path has a width <= val[W]. This will be always true because all other ways of reaching W will go through some other vertex (call it X) in the set B.
And for all other vertices X in set B, val[X] <= val[W]
Thus any other path to W will be constrained by val[X], which is never greater than val[W].
Thus the current estimate of val[W] is optimum and hence algorithm computes the correct values for all the vertices.

A: You could also use the "binary search on the answer" paradigm. That is, do a binary search on the weights, testing for each weight w whether you can find a path in the graph using only edges of weight greater than w.
The largest w for which you can (found through binary search) gives the answer. Note that you only need to check if a path exists, so just an O(|E|) breadth-first/depth-first search, not a shortest-path. So it's O(|E|*log(max W)) in all, comparable to the Dijkstra/Kruskal/Prim's O(|E|log |V|) (and I can't immediately see a proof of those, too).

A: Use either Prim's or Kruskal's algorithm. Just modify them so they stop when they find out that the vertices you ask about are connected.
EDIT: You ask for maximum minimum, but your example looks like you want minimum maximum. In case of maximum minimum Kruskal's algorithm won't work.
EDIT: The example is okay, my mistake. Only Prim's algorithm will work then.

A: I am not sure that Prim will work here. Take this counterexample:
V = {1, 2, 3, 4}

E = {(1, 2), (2, 3), (1, 4), (4, 2)}

weight function w:
  w((1,2)) = .1,
  w((2,3)) = .3
  w((1,4)) = .2
  w((4,2)) = .25

If you apply Prim to find the maxmin path from 1 to 3, starting from 1 will select the 1 --> 2 --> 3 path, while the max-min distance is attained for the path that goes through 4.

A: This can be solved using a BFS style algorithm, however you need two variations:

*

*Instead of marking each node as "visited", you  mark it with the minimum weight along the path you took to reach it.

For example, if I and J are neighbors, I has value w1, and the weight of the edge between them is w2, then J=min(w1, w2).

*

*If you reach a marked node with value w1, you might need to remark and process it again, if assigning a new value w2 (and w2>w1). This is required to make sure you get the maximum of all minimums.

For example, if I and J are neighbors, I has value w1, J has value w2, and the weight of the edge between them is w3, then if min(w2, w3) > w1 you must remark J and process all it's neighbors again.

A: Ok, answering my own question here just to try and get a bit of feedback I had on the tentative solution I worked out before posting here:
Each node stores a "path fragment", this is the entire path to itself so far.
0) set current vertex to the starting vertex
1) Generate all path fragments from this vertex and add them to a priority queue
2) Take the fragment off the top off the priority queue, and set the current vertex to the ending vertex of that path
3) If the current vertex is the target vertex, then return the path
4) goto 1
I'm not sure this will find the best path though, I think the exit condition in step three is a little ambitious. I can't think of a better exit condition though, since this algorithm doesn't close vertices (a vertex can be referenced in as many path fragments as it likes) you can't just wait until all vertices are closed (like Dijkstra's for example)

A: You can still use Dijkstra's!
Instead of using +, use the min() operator.
In addition, you'll want to orient the heap/priority_queue so that the biggest things are on top.
Something like this should work: (i've probably missed some implementation details)
let pq = priority queue of <node, minimum edge>, sorted by min. edge descending
push (start, infinity) on queue
mark start as visited
while !queue.empty:
   current = pq.top()
   pq.pop()
   for all neighbors of current.node:
      if neighbor has not been visited
          pq.decrease_key(neighbor, min(current.weight, edge.weight))

It is guaranteed that whenever you get to a node you followed an optimal path (since you find all possibilities in decreasing order, and you can never improve your path by adding an edge)
The time bounds are the same as Dijkstra's - O(Vlog(E)).
EDIT: oh wait, this is  basically what you posted. LOL.


text:
Q: Store Quarter/Year in SQL Server I have a table which needs to store the quarter and year, and I need to know which is the best way to do this. I found this answer from 10 years ago on SO: Best way to store quarter and year in SQL Server. However, there are two suggestions given--one is storing quarter and year in separate columns and making them integers, the other being storing as a datetime and using the first day of the month for the day (i.e., 1/1/2021, 4/1/2021, etc.).
Considering this answer is 10 years old and there could be better ways now for storing this data, what is the best method?
FYI, this data will not be used for calculation purposes, but will probably be searched on.
Thanks!

A: I recommend always storing date related data as the datetime data type.
Storing them separately is the worst possible approach, searching becomes very difficult.  Try writing the query returning all quarters between 3Q2019 and 1Q2021 when your year and quarter are separate.
Breaking it into separate parts puts the responsibility on the developer to handle the year boundary appropriately, which many do not.
DateTime data type also includes validation (Q5 2020 would throw an error) to prevent data errors.
Use the right tool for the job.  DateTime data should always be stored in a DateTime datatype.


text:
Q: Free CI/build server with different Linux versions I would like to build my dynamic library on different Linux platforms (e.g. RHEL 5/6/7, ...). I use https://drone.io at the moment, but it provides only Ubuntu.
Could you recommend something please?
It'll be perfect, if it can provide some "cool" features, e.g.:

*

*free for open source projects

*github integration (hooks)

*CI/tests

*artifact download

A: Jenkins  or Travis-CI should suit your purposes


text:
Q: .animate() slider not working correctly I am not sure exactly how this works but I have a review slider and it just doesn't work correctly.
If I click the left arrow, it will slide once to the right, which is correct. When I click the right arrow it slides back to it's original position, but after that it won't let me do anything.
I just want it so every time I click it, it will move 750px either left or right on each click.
$(document).ready(function(){
    var boxL = $('.box-left');
    var boxR = $('.box-right');

    boxL.click(function(){
     $('.grid-container').animate({"right": 750}, "slow");
    })
    boxR.click(function(){
        $('.grid-container').animate({"left": 0}, "slow");
    })
})

A:

$(document).ready(function(){
    var boxL = $('.box-left');
    var boxR = $('.box-right');

    boxL.click(function(){
        $('.grid-container').animate({"left": "-=50"}, "slow");
    })
    boxR.click(function(){
        $('.grid-container').animate({"left": "+=50"}, "slow");
    })
})
.grid-container
{
  background-color: orange;
  height: 60px;
  margin-bottom: 20px;
  position: relative;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="grid-container">
</div>

<button class="box-left">Left</button>
<button class="box-right">Right</button>


text:
Q: Prevent div click from raising a server event The div is used like an Image button. Based on the selected value of the drop down, it does some work.
When the value of DropDown is 1, the div click should not trigger. No matter what the value is, the div click is hitting the C# code. What should I do , so that it hits only when the value is > 1.
ASPX:
<asp:UpdatePanel>
 <ContentTemplate>

  <asp:DropDownList ID="ddl" runat="server" ></asp:DropDownList>
 </ContentTemplate>
</asp:UpdatePanel>

JS:
function ShowPage(page) {
            var n = parseInt($("#ddl").val());

            switch (page) {
                case 'first':
                    if (n > 1)
                        return true;
                    else
                        return false;
                    break;
           }
        }

C#:
public void RaisePostBackEvent(string EventArg)
        {
            if(!string.IsNullOrEmpty(EventArg))
            {
                switch(EventArg)
                {
                    case "divFirst_Click":
                        divFirst_Click();
                        break;
                }
            }
        }


text:
Q: Sequence $f_n$ of continuous functions on $[0,1]$, such that $0 \le f_n \le 1$ and $\lim\limits_{n\to\infty}\int_{0}^{1} f_n(x)\,\mathrm dx=0$ Let $f_n$ be a sequence of continuous functions on $[0,1]$, such that $0 \le f_n \le 1$ and $$\lim_{n\to\infty}\int_{0}^{1} f_n(x)\,\mathrm dx=0.$$
a) The sequence ${f_n (x)}$ converges uniformly.
b) The sequence ${f_n (x)}$ converges for some $x$.
c) The sequence ${f_n (x)}$ might not converge for any $x$.
d) The sequence ${f_n (x)}$ converges for every $x$ but not necessarily uniformly.
The answer is c? I have no counter example in my hand.

A: Consider the following sequence of sets, constructed as follows. Let $I_1=[0,1]$. Split $[0,1]$ in half, and let $I_2$ and $I_3$ be the first and second halves. Split $[0,1]$ in fourths, and let $I_4,I_5,I_6,I_7$ be the fourths in order. Continue this way, split $[0,1]$ in $2^n$ths and let $I_{2^n},\cdots, I_{2^{n+1}-1}$ be the $2^n$ pieces in order.
Now let $$f_n(x)=\text{ an isosceles triangle over } I_n \text{ of height } 1$$
Then $$\int_0^1 f_n\to 0$$ but if $x\neq m2^{-k}$ then $$\tag 1 \limsup_{n\to\infty} f_n(x)=1 \; ; \;\liminf_{n\to\infty} f_n(x)=0$$
ADD To fix the above, we can do the following: let $\langle g_n\rangle $ be the same as $\langle f_n\rangle $, but with the triangles shifted so that the peaks of the triangles fall on the binary rational points. Thus, $g_1$ will look like (the right) half an isosceles triangle on $[0,1/2]$ plus (the left) half of an isosceles triangle on $[3/4,1]$, $g_2$ will be an isosceles triangle over $[1/2,3/4]$, $g_3$ will be the two halves at $[0,1/4]$,$[7/8,1]$, and so on. Then $\langle g_1,f_1,g_2,f_2,g_3,f_3,\ldots\rangle$ should do: now the rational binary points oscillate between $0$ and $1$.

A: How about this:
$f_1=1$ everywhere;
$f_2=1$ on the left half of $[0,1]$ and $0$ on the right half; $f_3=1$ on the right half and $0$ on the left;
$f_4$, $f_5$, $f_6$ are respectively equal to $1$ on the left third, the middle third, and the right third and $0$ elsewhere;
$f_7$, $f_8$, $f_9$, $f_{10}$ are equal to $1$ respectively on the first, second, third, and fourth quarters, and $0$ elsewhere;
and so on.
Then $f_n(x)$ diverges for every  $x$ as $n\to\infty$, but $\displaystyle\int_0^1 f_n\to0$.


text:
Q: How to read Base64 VLQ code? I'm trying to understand how css source map works. I've created a very simple scss file.
#navbar {
    color: black;
}

When I compile the above scss, I get the following map file.
{
"version": "3",
"mappings": "AAAA,OAAQ;EACP,KAAK,EAAE,KAAK",
"sources": ["test.scss"],
"file": "test.css"
}

when I decode "mappings", I get the following values.
0) [0,0,0,0], [7,0,0,8]
1) [2,0,1,-7], [5,0,0,5], [2,0,0,2], [5,0,0,5]

What are those values?

A: I found an example at http://www.thecssninja.com/javascript/source-mapping, under the section "Base64 VLQ and keeping the source map small".

The above diagram AAgBC once processed further would return 0, 0, 32, 16, 1 – the 32 being the continuation bit that helps build the following value of 16. B purely decoded in Base64 is 1. So the important values that are used are 0, 0, 16, 1. This then lets us know that line 1 (lines are kept count by the semi colons) column 0 of the generated file maps to file 0 (array of files 0 is foo.js), line 16 at column 1.

A: Even after reading the answers, explanations were still not so clear to me. Here is an explanation in plain english in case it helps someone:
something like ;;AAAA,IAAM,WAAW,SAAX;... means <line0 info>;<line1 info>;...
so for ;;AAAA;IAAM,WAAW,SAAX;..., line 0 and line 1 doesn't have any important info (empty spaces etc.)
then for line 2 we have AAAA,IAAM,WAAW,SAAX
we convert each of these groups to binary using the base64 character mapping:
BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

so we basically find the index in this BASE64_ALPHABET above, and convert the index to 6-bit binary (6 bit because we use base64). eg. index of A is 0, so in 6 bit binary its 000000. so AAAA would be 000000 000000 000000 000000
then if we do this with IAAM we get: 001000 000000 000000 001100.
then this bit representation is the VLQ encoded version of 4 numbers. we start from the left block, remove the sign and continuation bit, keep the bits. and continue adding it bits while continuation bit is 1.
eg. 001000 is (cont)0100(sign)
so cont = 0 (no other block will be added to this number)
sign=0 (its positive)
bits = 0100 --> so it is 4 in decimal

-- note that we only remove sign bit for the first time. so if we had
101000 001000
we would say
0100 (cont=1, sign=0) 01000 (cont=0)
so we would have had +010001000 = 136

when we keep doing this, we will get these 4 numbers (continuation bit should be 0 exactly 4 times).

*

*AAAA would map to (0,0,0,0)

*IAAM would map to (4,0,0,6)

*WAAW would map to (11,0,0,11)
...

now, each of these mean relative numbers. so we correct those:

*

*AAAA actually points to: (0,0,0,0)

*IAAM actually points to: (0+4, 0+0, 0+0, 0+6) = (4,0,0,6)

*WAAW actually points to: (4+11, 0+0, 0+0, 6+11) = (15,0,0,17) // we added it where IAAAM was actually pointing to

...
so numbers (n1, n2, n3, n4) here stand for

*

*n1: column in generated code

*n2: corresponding source file index in "sources" array of sourceMapping output

*n3: line number in original code

*n4: column number in original code

we already knew which line this referred to from the beginning. so using the information we have above, we learned:

*

*AAAA: line 2, column 1 of generated code points to sources[0], line 0, column 0

*IAAM: line 2, column 4 of generated code points to sources[0], line 0, column 6

*WAAW: line 2, column 15 of generated code points to sources[0], line 0, column 17
...

two good sources about this:

*

*more on VLQ encoding

*more on how to interpret/decode

A: Despite the examples I could find, I took me quite a while to understand how the coding / decoding really works. So I thought I'd learn best by trying to make something myself in a very explicit, step by step way. I started out with the explanation of VLQ at this blog,
I use the following Python functor to generate sourcemaps for Transcrypt.
The code is simple and I think gives good insight in how the coding/decoding works in principle.
To achieve speed despite its simplicity, it caches the first 256 numbers, which are used most often in generating a v3 sourcemap.
import math

class GetBase64Vlq:
    def __init__ (self):
        self.nBits32 = 5
        self.encoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
        self.prefabSize = 256
        self.prefab = [self (i, True) for i in range (self.prefabSize)]

    def __call__ (self, anInteger, init = False):
        if not init and 0 < anInteger < self.prefabSize:
            return self.prefab [anInteger]
        else:
            signed = bin (abs (anInteger)) [2 : ] + ('1' if anInteger < 0 else '0')
            nChunks = math.ceil (len (signed) / float (self.nBits32))
            padded = (self.nBits32 * '0' + signed) [-nChunks * self.nBits32 : ]
            chunks = [('1' if iChunk else '0') + padded [iChunk * self.nBits32 : (iChunk + 1) * self.nBits32] for iChunk in range (nChunks - 1, -1, -1)]
            return ''.join ([self.encoding [int (chunk, 2)] for chunk in chunks])

getBase64Vlq = GetBase64Vlq ()

Example of use:
while (True):
    print (getBase64Vlq (int (input ('Give number:'))))


text:
Q: Only one row user defined table can be passed to stored procedure SELECT
    @MaxSeq = (CASE
                  WHEN (SELECT COUNT(*) FROM app_Attachments
                        WHERE app_Attachments.AppId = @appID) <= 0
                     THEN 1
                     ELSE (SELECT (MAX(seq)+1)
                           FROM app_Attachments
                           WHERE app_Attachments.AppId = @appID)
               END)

DECLARE @Id INT;

SELECT @Id = (COALESCE((SELECT MAX(Id)+1 FROM app_Attachments), 1))

INSERT INTO app_Attachments (Id, AppID, AttName, AttContentType, AttData, AddedBy, AddedDate, Seq)
    SELECT
        @Id, AppId, ImgNames, ImgType, Bytes, @AddedBy, @AddedDate, @MaxSeq
    FROM
        @Attachments --user defined table

CREATE TYPE [dbo].[AppsAttachments] AS TABLE
       (
            [AppId] [INT] NULL,
            [Bytes] [VARBINARY](MAX) NULL,
            [ImgNames] [NVARCHAR](MAX) NULL,
            [ImgType] [NVARCHAR](200) NULL
       )

Insert into table using stored procedure that has user defined table as parameter only success if table passed has one row, it was working well when the primary key is set as identity, after I changed the primary key into manual integer to be entered the problem occurred

A: if Id is not identity, then you need to ensure the Id is not duplicates. Use Row_number() to generate a running sequence of number
insert into app_Attachments (Id,AppID,AttName,AttContentType,AttData,AddedBy,AddedDate,Seq)
select  @Id + ROW_NUMBER() OVER (ORDER BY AppId) - 1,
        AppId,
        ImgNames,
        ImgType,
        Bytes,
        @AddedBy,
        @AddedDate,
        @MaxSeq
from    @Attachments --user defined table

if you also need to increase the Seq as well, add a row_number() to the query


text:
Q: How to corretly load DataContext of Conditional Linq-to-SQL Stored Proc I have a Stored Proc that do a validation on a parameter
ex.
IF @SearchType = 'BNa'
BEGIN
    ... DO something
END
ELSE IF @SearchType = 'SNa'
BEGIN
    ... DO something
END

So by default the Stored Proc return a scalar value and if SearchType = something valid it will return a IMultipleValues.
The problem is that when I drop my Stored Proc in the DataContext designer, it creates the LINQ-to-SQL for a function that only returns a scalar int. It doesn't understands that the Strored Proc could return a IMultipleResults with a scalar value and a DataSet.
Anyone know how to made LINQ-to-SQL to extrapolate the possible return values?

A: I can't answer your question directly, but have you tried using SQL Profiler to work out how the designer retrieves the metadata for your stored procedure?
I'm thinking that in your situation it may not be possible for the designer to figure things out for you. SQL Profiler will let you figure this out for sure either way...
I've had quite a positive experience with using SqlMetal (instead of the designer). To save you Googling the documentation is at http://msdn.microsoft.com/en-us/library/bb386987.aspx.
One of the ways you can use SqlMetal is:

*

*Run SqlMetal to extract database metadata to a DBML file.

*Run some custom processing on the DBML file (which is easy to do as it's just XML).

*Run SqlMetal again to turn the updated DBML into code.

Using this approach, you could correct the metadata being used for your stored procedure (assuming it can't be determined correctly).
The winning thing about this approach for me is that you can modify your database whenever you need to, and easily regenerate the matching strongly typed code, while still retaining a high degree of control over what is generated.


text:
Q: How to detect if image is all black using flutter? I'm building an app that user required to send a selfie but some user just block the camera to take a picture and the result is all black, is there a way to detect if image is black?
I'm thinking of using face detection but I haven't tried it and its way to much for my simple app.

A: One way you can try is using palette_generator package to extract colors in the image and then computing average luminance of the image, like so.
import 'package:palette_generator/palette_generator.dart';

  Future<bool> isImageBlack(ImageProvider image) async {
    final double threshold = 0.2; //<-- play around with different images and set appropriate threshold
    final double imageLuminance = await getAvgLuminance(image);
    print(imageLuminance);
    return imageLuminance < threshold;
  }

  Future<double> getAvgLuminance(ImageProvider image) async {
    final List<Color> colors = await getImagePalette(image);
    double totalLuminance = 0;
    colors.forEach((color) => totalLuminance += color.computeLuminance());
    return totalLuminance / colors.length;
  }

A: Before use camera check if your app has permission for that.
For this porpouse i've recommend to use the permission handler
Few lines from official documentation
 var status = await Permission.camera.status;
    if (status.denied) {
      // We didn't ask for permission yet or the permission has been denied before but not permanently.
    }


text:
Q: Retrieving photos around a given location using the flickr API I'd like to retrieve photos around specified coordinates from flickr by using the python flickrapi wrapper to their API. My minimal example looks like this:
import flickrapi
api_key = "xxxx"
secret_api_key = "xxxx"
flickr = flickrapi.FlickrAPI(api_key, secret_api_key)

lat = 48.83417
lon = 2.221111
photo_list = flickr.photos.geo.photosForLocation(lat=lat, lon=lon, accuracy=11, format="json")

But, I get empty answers, i.e., photo_list looks like this:

'{"photos":{"page":1,"pages":0,"perpage":100,"total":"0","photo":[]},"stat":"ok"}'

Any ideas about what I might be doing wrong?
EDIT
Turns out, retrieving photos using flickr.photos.search() works just fine.

A: try with the 'search' call instead of the 'photosForLocation', flickr.photos.geo.forLocation is very specific, and will only return photos with an exact match on the latitude and longitude, apparently
    import flickrapi

    api_key = "<api_key>"
    secret_api_key = "<secret_api_key>"
    flickr = flickrapi.FlickrAPI(api_key, secret_api_key)

    lat = 48.83417
    lon = 2.221111
    photo_list = flickr.photos.search(api_key=api_key, lat=lat, lon=lon, accuracy=11, format='parsed-json')

    print(photo_list)

A: Turns out, retrieving photos using flickr.photos.search() works just fine.


text:
Q: How to rotate the titles for each subplots in Matplotlib? folks. Does anyone know how to ratate the title text for several subplots like this:
Rotate image titles or annotations.
A slight difference between the above images and my desired images is that, each face image in my whole figure was displayed by an individual subplot. And I want to add a rotated title for each subplot figure.
Thanks in advance for any suggestions and comments.

A: A minimal working answer for you. I hope it helps.
import numpy as np
import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(1, 2, sharey=False, figsize=(10,4))

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x)

ax1.plot(x, y)
ax1.set_title('Title 1', y=1.1, rotation = 45) # You can vary y and angle as per choice
ax2.plot(x, 1.5*y)
ax2.set_title('Title 2', y=1.1, rotation = 45)

Output


text:
Q: C# asp.net short if statement with multiple statements Edit
If anyone could enlighten me of what you call if statements like those would be great! Thanks!

Quick question about "short" if statements (not sure what you call them),
I have
<%= (LeadsUser.IsAdministrator || LeadsUser.IsEditor || LeadsUser.IsSubsidiarie) ? "Currently logged in as: " : "" %>
<%= LeadsUser.IsSubsidiarie ? "Lead admin" : "" %>
<%= LeadsUser.IsAdministrator ? "Lead editor" : "" %>
<%=  LeadsUser.IsEditor ? "Lead user" : "" %>
I know this is against DRY. I'm wondering can I combine those? Because some users are in multiple groups. I'd want it to say "Currnetly logged in as: Lead admin, lead editor", so depending on if LeadsUser.IsSubsidiarie is true aswell as IsAdministrator write ", lead editor" instead of "Lead editor".

A: Like most of the times when writing a question I figure it out myself.
I figured you could nest the if's like this:
<%= LeadsUser.IsSubsidiarie && LeadsUser.IsAdministrator ? "Lead admin, lead editor" : (!LeadsUser.IsSubsidiarie ? "Lead editor" : "") %>