问:
WordPress Button triggered ajax request
So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.

My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code

```<code>echo '<button id="ZapisPrace">Save</button>
<script>
jQuery("#ZapisPrace").click(function($){
    var data={
        action: "addToDB",
        info: "nomz"
    };
    jQuery.post(ajaxurl,data,function(response){
    alert("Response was "+ response);
    });
});
</script>';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
    echo '<script>console.log("AAA")</script>';
    wp_die();
}
</code>```

Using current version of WP so variable ajaxurl is pointing to the

/wordpress/wp-admin/admin-ajax.php

No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why?
Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.

PS: I am supposed to use the WP way of using ajax.

答:
Ok so I didn't figure out how code above works, however I managed to get it working trough different wp structure I found online:

BTW: I used onClick function here but it works even when replaced with jQuery click event.

```<code>add_action('wp_ajax_addToDB','pridajDoDB');

echo '<button onClick='triggerAjax()'>Save</button>?>';

<script>
function triggerAjax(){
    <?php $nonce = wp_create_nonce( 'subbmitData' );?>//used so ajax response can verify from where is the request coming
    jQuery.ajax({
        type: "post",url: "admin-ajax.php",data: { action: 'addToDB', _ajax_nonce: '<?php echo $nonce; ?>' },
        success: function(html){
                console.log(html);//this will console log everything that happens in ajax called php function. Echo works as well.
            }
        });
    }
</script>
<?php

function pridajDoDB(){
    check_ajax_referer( "subbmitData" );//this check from where is the request coming from
    //here database commands works but if you echo or console log something it will be just passed to success function above
    die();
}
?>
</code>```

Title: WordPress Button triggered ajax request

Body:
So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.

My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code

echo '<button id="ZapisPrace">Save</button>
';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
    echo '';
    wp_die();
}

Using current version of WP so variable ajaxurl is pointing to the

/wordpress/wp-admin/admin-ajax.php

No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why?
Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.

PS: I am supposed to use the WP way of using ajax.

Body:
Ok so I didn't figure out how code above works, however I managed to get it working trough different wp structure I found online:

BTW: I used onClick function here but it works even when replaced with jQuery click event.

add_action('wp_ajax_addToDB','pridajDoDB');

echo '<button onClick='triggerAjax()'>Save</button>?>';

<script>
function triggerAjax(){
    <?php $nonce = wp_create_nonce( 'subbmitData' );?>//used so ajax response can verify from where is the request coming
    jQuery.ajax({
        type: "post",url: "admin-ajax.php",data: { action: 'addToDB', _ajax_nonce: '<?php echo $nonce; ?>' },
        success: function(html){
                console.log(html);//this will console log everything that happens in ajax called php function. Echo works as well.
            }
        });
    }
</script>
<?php

function pridajDoDB(){
    check_ajax_referer( "subbmitData" );//this check from where is the request coming from
    //here database commands works but if you echo or console log something it will be just passed to success function above
    die();
}
?>


来源: stackexchange

问:
EditText.setSelection(end) brings no effect?
I use the following code to set the cursor at the end of customEditText(EditText) but it brings no effect.

```<code>customEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                 if (hasFocus) {
                    String customEditTextText = customEditText.getText().toString();
                    int selection = customEditTextText.length();
                    customEditText.setSelection(selection);
                }
            }
});
</code>```

Has anybody any ideas for that ?

答:
I had the same issue with an EditText inside an AlertDialog. The solution for me was this:</p>

```<code>    mEditText.post(new Runnable() {
        @Override
        public void run() {
            mEditText.setSelection(mEditText.length());
        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use the following code to set the cursor at the end of customEditText(EditText) but it brings no effect.

customEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                 if (hasFocus) {
                    String customEditTextText = customEditText.getText().toString();
                    int selection = customEditTextText.length();
                    customEditText.setSelection(selection);
                }
            }
});

Has anybody any ideas for that ?

Body:
I had the same issue with an EditText inside an AlertDialog. The solution for me was this:

    mEditText.post(new Runnable() {
        @Override
        public void run() {
            mEditText.setSelection(mEditText.length());
        }
    });


问:
Boost asio: Using IPv6 addresses in resolver::query works on Win32, but not on Linux
I am currently developing a simple server application which should be also IPv6 capable. IPv6 works fine on Windows (using MSVC2010), but it does not on Linux.

Imagine following code:

```<code>boost::system::error_code ec;
std::string address="::1", service="http";
tcp::resolver resolver(io_service);
tcp::resolver::query query(address, service);
tcp::resolver::iterator resiter = resolver.resolve(query, ec);

if (ec)
    std::cout << "Cannot resolve address: " << address << "(" << ec.message() << ")" << std::endl;
</code>```

The error message printed on Linux is "Host not found (authoritative)", while it works on Windows.

Any hints are welcome.

答: Linux and Windows have different behavior with respect to the search order of address returned by the name services.  Try using different flags to gain more fine-grained control over the type of address you are querying for.  For example, for this query you could use the numeric_host flag.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am currently developing a simple server application which should be also IPv6 capable. IPv6 works fine on Windows (using MSVC2010), but it does not on Linux.

Imagine following code:

boost::system::error_code ec;
std::string address="::1", service="http";
tcp::resolver resolver(io_service);
tcp::resolver::query query(address, service);
tcp::resolver::iterator resiter = resolver.resolve(query, ec);

if (ec)
    std::cout << "Cannot resolve address: " << address << "(" << ec.message() << ")" << std::endl;

The error message printed on Linux is "Host not found (authoritative)", while it works on Windows.

Any hints are welcome.


问:
Java: java.lang.UnsatisfiedLinkError Failed to call native method in .cpp file using JNI
as mentioned in title my java program is unable to invoke or call the native method in .cpp file where the library .dll gets loaded successfully in program.
but while running it throws an exception java.lang.UnsatisfiedLinkError.
I had correctly set a library path to project.

here is my cpp file:

```<code>#include "jni.h"
#include "Demojni.h"
#include <iostream>
using namespace std;

extern "c"{
   JNIEXPORT jint JNICALL _Java_demojni_Demojni_printm(JNIEnv *env, jobject   object){
      cout<<"call from c++";
      return 1;
   }
}

int main(){
   return 1;
}
</code>```

and here is .java file:

```<code>package demojni;

public class Jni1{
   private native int printm();
   static{
      try{
         System.out.println(System.getProperty("java.library.path"));
         System.loadLibrary("libCppJNILibrary_1");
         System.out.println("loaded");
      }
      catch(Exception e){
         System.out.println("can't load\n"+e.getMessage());
      }
   }

   public static void main(String[] arg){
      Jni1 api=new Jni1();
      int a=api.printm();
   }
}
</code>```

答:
Make sure to match method name and package name.

Take a look here:

http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html

Section: "Resolving Native Method Names"

In fact, the easies way to have everything set up properly is to use javah.

Take a look at simple Hello world sample here:

http://jnicookbook.owsiak.org/recipe-No-001/

Body:
as mentioned in title my java program is unable to invoke or call the native method in .cpp file where the library .dll gets loaded successfully in program.
but while running it throws an exception java.lang.UnsatisfiedLinkError.
I had correctly set a library path to project.

here is my cpp file:

#include "jni.h"
#include "Demojni.h"
#include <iostream>
using namespace std;

extern "c"{
   JNIEXPORT jint JNICALL _Java_demojni_Demojni_printm(JNIEnv *env, jobject   object){
      cout<<"call from c++";
      return 1;
   }
}

int main(){
   return 1;
}

and here is .java file:

package demojni;

public class Jni1{
   private native int printm();
   static{
      try{
         System.out.println(System.getProperty("java.library.path"));
         System.loadLibrary("libCppJNILibrary_1");
         System.out.println("loaded");
      }
      catch(Exception e){
         System.out.println("can't load\n"+e.getMessage());
      }
   }

   public static void main(String[] arg){
      Jni1 api=new Jni1();
      int a=api.printm();
   }
}


问:
Rails 3.1, RSpec: testing model validations
I have started my journey with TDD in Rails and have run into a small issue regarding tests for model validations that I can't seem to find a solution to. Let's say I have a User model,

```<code>class User < ActiveRecord::Base
  validates :username, :presence => true
end
</code>```

and a simple test

```<code>it "should require a username" do
  User.new(:username => "").should_not be_valid
end
</code>```

This correctly tests the presence validation, but what if I want to be more specific? For example, testing full_messages on the errors object..

```<code>it "should require a username" do
  user = User.create(:username => "")
  user.errors[:username].should ~= /can't be blank/
end
</code>```

My concern about the initial attempt (using should_not be_valid) is that RSpec won't produce a descriptive error message. It simply says "expected valid? to return false, got true." However, the second test example has a minor drawback: it uses the create method instead of the new method in order to get at the errors object.

I would like my tests to be more specific about what they're testing, but at the same time not have to touch a database.

Anyone have any input?

答:
in new version rspec, you should use expect instead should, otherwise you'll get warning:

it "should have valid factory" do
    expect(FactoryGirl.build(:user)).to be_valid
end

it "should require a username" do
    expect(FactoryGirl.build(:user, :username => "")).not_to be_valid
end
```

Body:
I have started my journey with TDD in Rails and have run into a small issue regarding tests for model validations that I can't seem to find a solution to. Let's say I have a User model,

class User < ActiveRecord::Base
  validates :username, :presence => true
end

and a simple test

it "should require a username" do
  User.new(:username => "").should_not be_valid
end

This correctly tests the presence validation, but what if I want to be more specific? For example, testing full_messages on the errors object..

it "should require a username" do
  user = User.create(:username => "")
  user.errors[:username].should ~= /can't be blank/
end

My concern about the initial attempt (using should_not be_valid) is that RSpec won't produce a descriptive error message. It simply says "expected valid? to return false, got true." However, the second test example has a minor drawback: it uses the create method instead of the new method in order to get at the errors object.

I would like my tests to be more specific about what they're testing, but at the same time not have to touch a database.

Anyone have any input?


问:
Ios - Recongnise QRcode response Typee
I am using qr code in my app and it is giving me response also in the form of AVMetadataMachineReadableCodeObject. Here is my delegate which handles the response.

```<code> func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {

    if strFound == ""
    {

    // Check if the metadataObjects array is not nil and it contains at least one object.
    if metadataObjects == nil || metadataObjects.count == 0 {
        qrCodeFrameVieww?.frame = CGRect.zero
        messageLabel.text = "No QR/barcode is detected"
        return
    }

    // Get the metadata object.
    let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

    if supportedCodeTypes.contains(metadataObj.type) {
        // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
        let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
        //qrCodeFrameVieww?.frame = barCodeObject!.bounds

        if defaults.value(forKey: "beep") as! Bool != false
        {
            playSound()

        }
        if defaults.value(forKey: "vibrate") as! Bool != false
        {
            AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

            AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)

        }

        print("type is",metadataObj.type)

        print("metaDataObj",metadataObj)

         foundCode(code: metadataObj.stringValue as NSString)

        if metadataObj.stringValue != nil {

            let stUrl = metadataObj.stringValue as String
            print("The Url Is \(stUrl)")

            if defaults.value(forKey: "copyToClipboard") as! Bool == true
            {
                UIPasteboard.general.string = stUrl

            }
</code>```

}

My question is as qrcode code can scan vcards,phone numbers,emails,geo locations and Calendar Event etc.How would i get to know that what kind of data has i got in the response string like if it is a related to vcard or it is a url or a calender event??

答:
```<code>guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject else {
  return
}
guard let codeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObject) else {
  return
}
switch codeObject.type {
  case .AVMetadataObjectTypeQRCode:
    //...
  default:
    break
}
</code>```

Title: Ios - Recongnise QRcode response Typee

Body:
I am using qr code in my app and it is giving me response also in the form of AVMetadataMachineReadableCodeObject. Here is my delegate which handles the response.

 func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {

    if strFound == ""
    {

    // Check if the metadataObjects array is not nil and it contains at least one object.
    if metadataObjects == nil || metadataObjects.count == 0 {
        qrCodeFrameVieww?.frame = CGRect.zero
        messageLabel.text = "No QR/barcode is detected"
        return
    }

    // Get the metadata object.
    let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

    if supportedCodeTypes.contains(metadataObj.type) {
        // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
        let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
        //qrCodeFrameVieww?.frame = barCodeObject!.bounds

        if defaults.value(forKey: "beep") as! Bool != false
        {
            playSound()

        }
        if defaults.value(forKey: "vibrate") as! Bool != false
        {
            AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

            AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)

        }

        print("type is",metadataObj.type)

        print("metaDataObj",metadataObj)

         foundCode(code: metadataObj.stringValue as NSString)

        if metadataObj.stringValue != nil {

            let stUrl = metadataObj.stringValue as String
            print("The Url Is \(stUrl)")

            if defaults.value(forKey: "copyToClipboard") as! Bool == true
            {
                UIPasteboard.general.string = stUrl

            }

}

My question is as qrcode code can scan vcards,phone numbers,emails,geo locations and Calendar Event etc.How would i get to know that what kind of data has i got in the response string like if it is a related to vcard or it is a url or a calender event??


问:
dragexit vs dragleave - which should be used?
The HTML Drag and Drop API defines two very similar events, dragleave and dragexit, which along with dragenter are intended to help track the current drop target.

A quick search didn't turn up any current and clear documentation of the two events, when one should be used over another, and the browser support, so I thought I'd ask here.

I'll share the resources I found so far:

The HTML specification has detailed description of when each event is supposed to be fired, but it requires some deciphering.

The MDN docs (HTML Drag and Drop API and individual dragexit/dragleave pages) are not much of a help, saying "The dragexit event is fired when an element is no longer the drag operation's immediate selection target." / "The dragleave event is fired when a dragged element or text selection leaves a valid drop target." and providing no information about browser support for dragexit (as of 2017-03)

Dottoro's dragexit docs (another of the top Google hits) seems out of date, claiming that "The dragexit event is obsolete in Firefox from version 3.5. Use the ondragleave event instead."

Mozilla's bug 619703 and W3C bug 11568 referenced there shed some light on the history of these two events:

Looks like Gecko/Firefox initially implemented dragexit while IE at least implemented dragleave, the major difference being the order of events: dragexit fires before corresponding dragenter, while dragleave, confusingly, fires after.

The HTML5 spec initially only defined dragleave with IE semantics, but later (~2013) added dragexit with Mozilla's semantics.

Gecko appears to have implemented dragleave in Firefox 3.5 (2009), originally synonymous with dragexit, but later (4.0, ~2011?) changing it to match the spec.

caniuse indicates that the HTML DnD API is more-or-less supported across modern browsers, but does not say anything about dragexit specifically

答:
I have taken code sample from MDN and ran it on Chrome 57.0.2987.110 and Firefox 52.0.2.

Firefox event sequence is

dragexit

dragleave

drop

But Chrome never fired dragexit event.

Chrome event sequence is

dragleave

drop

Further analysis on dragexit event, I found out in Wikipedia that it's part of Mozilla XUL events which says:

In addition to the common/W3C events, Mozilla defined a set of events that work only with XUL elements

In case you need code snippets, here it is dragexit and dragleave event snippet from plunkr.

```<code>document.addEventListener("dragexit", function(event) {
  console.log(event.type);
  // reset the transparency
  event.target.style.opacity = "";
}, false);

document.addEventListener("dragleave", function(event) {
  console.log(event.type);
  // reset background of potential drop target when the draggable element leaves it
  if (event.target.className == "dropzone") {
    event.target.style.background = "";
  }

}, false);
</code>```

There is an interesting tutorial that shows that DnD API can be fully implemented without using the dragexit event which is not fully supported by all browsers. Your safe bet is to use the dragleave event instead that is well supported by all major browsers.

Body:
I have taken code sample from MDN and ran it on Chrome 57.0.2987.110 and Firefox 52.0.2.

Firefox event sequence is

dragexit

dragleave

drop

But Chrome never fired dragexit event.

Chrome event sequence is

dragleave

drop

Further analysis on dragexit event, I found out in Wikipedia that it's part of Mozilla XUL events which says:

In addition to the common/W3C events, Mozilla defined a set of events that work only with XUL elements

In case you need code snippets, here it is dragexit and dragleave event snippet from plunkr.

document.addEventListener("dragexit", function(event) {
  console.log(event.type);
  // reset the transparency
  event.target.style.opacity = "";
}, false);

document.addEventListener("dragleave", function(event) {
  console.log(event.type);
  // reset background of potential drop target when the draggable element leaves it
  if (event.target.className == "dropzone") {
    event.target.style.background = "";
  }

}, false);

There is an interesting tutorial that shows that DnD API can be fully implemented without using the dragexit event which is not fully supported by all browsers. Your safe bet is to use the dragleave event instead that is well supported by all major browsers.


问:
How and where should I use the keyword "use" in php
I used use the keyword "use" generally above the class definition. Like this:

```<code><?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...
</code>```

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

```<code> <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...
</code>```

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line
use \Codeception\Specify;
before the class definition?

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.

答:
You can not import class with use keyword. You have to use include/require statement. Even if you use some php auto loader, still autoloader will have to use either include or require internally.

The Purpose of use keyword:

Consider a case where you have two classes with same name; you'll find it strange, but when you are working with big MVC structure, this happens. So if you have two classes with same name, put them in different name spaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the use statement so that it can make a decision which one is going to be used on.

Here refer this
How does the keyword 'use' work

Body:
I used use the keyword "use" generally above the class definition. Like this:

<?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

 <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line
use \Codeception\Specify;
before the class definition?

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.


问:
Will providing APIs help deter screen scraping?
I have been thinking quite a bit here lately about screen scraping and what a task it can be. So I pose the following question.

Would you as a site developer expose simple APIs to prevent users from screen scraping, such as JSON results?

These results could then implement caching, and they are much smaller for traffic than the huge amounts of markup that could potentially be downloaded.

I am not looking at prevention, but deterring scraping.

Scraping Bandwidth Sample

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

users: 200,000

% of users using utility: 5

filesize: 1kb

freq: 1 minute

Formula:

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

10,000 * 1440 * 1

14400000kb or 13.73291015625gb

Assuming your JSON result is 200 bytes that's now (10,000 * 1440 * 0.2) or 2.74658203125gb a day.

That's a change of about 11gb of traffic a day.

My Stack Overflow profile is 96k for reference.

The reason for this question prompted asking for a JSON result from users profiles:

http://stackoverflow.uservoice.com/pages/general/suggestions/101342-add-json-for-user-information

I wanted to find out if other developers would expose this type of API, and if it is worth your time to provide these APIs to reduce bandwidth.

答: If you want to provide an open model that people can develop solutions ontop of your site, then yes you should provide an API. Screen scraping is a method of hostile integration, and should only be used in last resort.</p>

OwnerDisplayName: Tom Anderson

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: Josh


问:
Prestashop 1.6.1.11 (500) Internal server error (Associations) bytes exhausted
I've had a question posted on the Prestashop forums for some time regarding an issue that I'm not sure how to resolve. I'll post the link below to the original question, any assistance I can get regarding this issue would be greatly appreciated.

Initial Prestashop Forum Question.

Prestashop 1.6.1.11: Everytime I access certain products and try to edit thier associations I receive an error notice;

(500 Internal Server Error)

A server error occurred while loading the tabs: some tabs could not be
  loaded. Please try again by refreshing the page. If you are still
  encountering this problem, please check your server logs or contact
  your hosting provider for assistance.

I completed a few steps to try to identify the error as shown below in my code snippet, a result of which I was able to return a few details regarding the error.

```<code><php

// I enabled dev mode via config/defines.inc.php
if (!defined('_PS_MODE_DEV_')) {
define('_PS_MODE_DEV_', true);
}

?>
</code>```

Re-tracing the steps I tried to reccur the error.

This was my result...

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8192 bytes) in /classes/cache/CacheFs.php on line 69

I took a few steps forward in hopes of correcting this issue but all to no avail. I'll list the steps I've attempted below;

Adjusted my php.ini to allow the full memory limit, I'll post a full copy of which below. (memory_limit = 128M)

Contacted my hosting provider to have the 'xCache' caching module installed on my sever in hopes of worming my around the default caching solution and finding a possible fix. However this is not possible at this time.

Checked for recently installed module issues. (None found)

I have done some further digging on the web but most solutions seem exstensive, such as rebuilding the code to be less memory intensive. Sadly, I'm not confident enough in my ability to reliably resolve this issue with my current knowledge and I'm seeking some advice on how to go about resolving this error.

Regards,
-B

EDIT

After further digging and after disabling caching, my error location has changedto; Adapter/Adapter_EntityMapper.php on line 98.

答:
You can try to disable all the overrides to see if the problem is there:

Enable debug mode/error reporting, setting the config value _PS_MODE_DEV_ to true in config/defines.inc.php

define('_PS_MODE_DEV_', true);

Log into your PrestaShop 1.6 administration dashboard.

Click on the Advanced Parameters menu option located on the left sidebar and after that on Performance.

Toggle the Disable All Overrides button in the debug mode section

Body:
I've had a question posted on the Prestashop forums for some time regarding an issue that I'm not sure how to resolve. I'll post the link below to the original question, any assistance I can get regarding this issue would be greatly appreciated.

Initial Prestashop Forum Question.

Prestashop 1.6.1.11: Everytime I access certain products and try to edit thier associations I receive an error notice;

(500 Internal Server Error)

A server error occurred while loading the tabs: some tabs could not be
  loaded. Please try again by refreshing the page. If you are still
  encountering this problem, please check your server logs or contact
  your hosting provider for assistance.

I completed a few steps to try to identify the error as shown below in my code snippet, a result of which I was able to return a few details regarding the error.

<php

// I enabled dev mode via config/defines.inc.php
if (!defined('_PS_MODE_DEV_')) {
define('_PS_MODE_DEV_', true);
}

?>

Re-tracing the steps I tried to reccur the error.

This was my result...

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8192 bytes) in /classes/cache/CacheFs.php on line 69

I took a few steps forward in hopes of correcting this issue but all to no avail. I'll list the steps I've attempted below;

Adjusted my php.ini to allow the full memory limit, I'll post a full copy of which below. (memory_limit = 128M)

Contacted my hosting provider to have the 'xCache' caching module installed on my sever in hopes of worming my around the default caching solution and finding a possible fix. However this is not possible at this time.

Checked for recently installed module issues. (None found)

I have done some further digging on the web but most solutions seem exstensive, such as rebuilding the code to be less memory intensive. Sadly, I'm not confident enough in my ability to reliably resolve this issue with my current knowledge and I'm seeking some advice on how to go about resolving this error.

Regards,
-B

EDIT

After further digging and after disabling caching, my error location has changedto; Adapter/Adapter_EntityMapper.php on line 98.


问:
Why does not change value in directive Angular js?
I have simple directive in Angular JS:

```<code> .directive("statusClass", function() {

        return {
            restrict: 'A',
            scope: {
                'status': '='
            },

            link: function(scope, element, attrs) {

                switch (scope.status) {
                    case "pending":
                    case "Pending":
                        element.addClass('badge-default');
                        break;

                    case "completed":
                        element.addClass('badge-primary');
                        break;
                }

            }
        }
    })
</code>```

And call that like:

```<code><div status-class status="data.active"></div>
</code>```

Why when I change model outside: $scope.data.active = "go"; it is not bind with directive? So I can not see chnages in directive

答:
you need to use $watch to listen when the variable change and then fire the function.

Because link function gets executed at the run time. so when you are changing a directive scope variable it is not executed unless you fire an event(function for example).

```<code> .directive("statusClass", function() {
    return {
        restrict: 'A',
        scope: {
            'status': '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('status', function() {
                switch (scope.status) {
                    case "pending":
                    case "Pending":
                        element.addClass('badge-default');
                        break;
                    case "completed":
                        element.addClass('badge-primary');
                        break;
                }
            })
        }
    }
})
</code>```

Body:
I have simple directive in Angular JS:

 .directive("statusClass", function() {

        return {
            restrict: 'A',
            scope: {
                'status': '='
            },

            link: function(scope, element, attrs) {

                switch (scope.status) {
                    case "pending":
                    case "Pending":
                        element.addClass('badge-default');
                        break;

                    case "completed":
                        element.addClass('badge-primary');
                        break;
                }

            }
        }
    })

And call that like:

Why when I change model outside: $scope.data.active = "go"; it is not bind with directive? So I can not see chnages in directive

Body:
you need to use $watch to listen when the variable change and then fire the function.

Because link function gets executed at the run time. so when you are changing a directive scope variable it is not executed unless you fire an event(function for example).

 .directive("statusClass", function() {
    return {
        restrict: 'A',
        scope: {
            'status': '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('status', function() {
                switch (scope.status) {
                    case "pending":
                    case "Pending":
                        element.addClass('badge-default');
                        break;
                    case "completed":
                        element.addClass('badge-primary');
                        break;
                }
            })
        }
    }
})


问:
WPF Change position of controls in a listbox as other controls change size
I have a template for a listbox item that currently looks like this:

```<code>        <ListBoxItem>
            <Grid Background="DarkOrange" MaxWidth="431">
                <TextBlock TextWrapping="WrapWithOverflow" Width="431">
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec tempus sem.
                    Nunc lobortis magna sed odio ullamcorper sollicitudin. Etiam porttitor malesuada vestibulum.
                    Nullam et efficitur nibh, sit amet tristique felis.
                    Fusce vel accumsan dui. Duis aliquam nulla ac turpis vestibulum rutrum.
                    Phasellus vitae felis at magna ultricies suscipit lacinia eu ipsum.
                </TextBlock>
            </Grid>
        </ListBoxItem>
</code>```

As the length of the text changes, so does the height of the Textblock, and the size of the grid background behind it.

How can I add a MediaElement control underneath the Textblock, so that it (and the background) will move up and down along with the size of the Textblock?

答:
You can define Rows for your Grid. Define the Height of your first row as Auto this will adjust the Height of the row to the ActualHeight of it's content. For the second rows height you can define *, which will make it fill the rest of the grid.

```<code>    <Grid Background="DarkOrange" MaxWidth="431">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height ="*"/>
    </Grid.RowDefinitions>
    <TextBlock TextWrapping="WrapWithOverflow" Width="431">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec tempus sem.
                Nunc lobortis magna sed odio ullamcorper sollicitudin. Etiam porttitor malesuada vestibulum.
                Nullam et efficitur nibh, sit amet tristique felis.
                Fusce vel accumsan dui. Duis aliquam nulla ac turpis vestibulum rutrum.
                Phasellus vitae felis at magna ultricies suscipit lacinia eu ipsum.
    </TextBlock>
    <MediaElement Grid.Row="1"></MediaElement>
</Grid>
</code>```

Body:
I have a template for a listbox item that currently looks like this:

        <ListBoxItem>
            <Grid Background="DarkOrange" MaxWidth="431">
                <TextBlock TextWrapping="WrapWithOverflow" Width="431">
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec tempus sem.
                    Nunc lobortis magna sed odio ullamcorper sollicitudin. Etiam porttitor malesuada vestibulum.
                    Nullam et efficitur nibh, sit amet tristique felis.
                    Fusce vel accumsan dui. Duis aliquam nulla ac turpis vestibulum rutrum.
                    Phasellus vitae felis at magna ultricies suscipit lacinia eu ipsum.
                </TextBlock>
            </Grid>
        </ListBoxItem>

As the length of the text changes, so does the height of the Textblock, and the size of the grid background behind it.

How can I add a MediaElement control underneath the Textblock, so that it (and the background) will move up and down along with the size of the Textblock?

Body:
You can define Rows for your Grid. Define the Height of your first row as Auto this will adjust the Height of the row to the ActualHeight of it's content. For the second rows height you can define *, which will make it fill the rest of the grid.

    <Grid Background="DarkOrange" MaxWidth="431">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height ="*"/>
    </Grid.RowDefinitions>
    <TextBlock TextWrapping="WrapWithOverflow" Width="431">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec tempus sem.
                Nunc lobortis magna sed odio ullamcorper sollicitudin. Etiam porttitor malesuada vestibulum.
                Nullam et efficitur nibh, sit amet tristique felis.
                Fusce vel accumsan dui. Duis aliquam nulla ac turpis vestibulum rutrum.
                Phasellus vitae felis at magna ultricies suscipit lacinia eu ipsum.
    </TextBlock>
    <MediaElement Grid.Row="1"></MediaElement>
</Grid>


问:
overlapping of 2 html elements
My goal is to make 2 elements side by side in html but when I try to do it they overlap slightly. Where am I failing?

```<code> <div class="row">

 <div class="col-md-4"><img alt="100%x280" src="@Html.DisplayFor(modelItem => Model.ImgURL)" /></div>
 <div class="col-md-3"><span class="pull-right"><p>@Html.DisplayFor(modelItem => Model.Plot)</p><p>@Html.DisplayFor(modelItem => Model.Actors)</span></p></div>
</code>```

Edit I have seen some examples here of similar questions but some use custom css and i would like to avoid that. Also i am using bootstrap!

答:
```<code> <div class="col-md-4"><img alt="100%x280" src="@Html.DisplayFor(modelItem => Model.ImgURL)" /></div>
</code>```

This line here. Change the bootstrap column from 4 to 5 or 6 to allow it more padding on the right side. This should easily fix your problem.

Title: overlapping of 2 html elements

Body:
My goal is to make 2 elements side by side in html but when I try to do it they overlap slightly. Where am I failing?

 Model.ImgURL)" />

@Html.DisplayFor(modelItem => Model.Plot)

@Html.DisplayFor(modelItem => Model.Actors)

Edit I have seen some examples here of similar questions but some use custom css and i would like to avoid that. Also i am using bootstrap!

Body:
 <div class="col-md-4"><img alt="100%x280" src="@Html.DisplayFor(modelItem => Model.ImgURL)" /></div>

This line here. Change the bootstrap column from 4 to 5 or 6 to allow it more padding on the right side. This should easily fix your problem.


问:
Ng-repeat does'nt works with array in array
i'm new at ionic and i need to loop trough object with ng-repeat and i always get this error

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: info in allInfos, Duplicate key: string:", Duplicate value:

"this is my arrays

Please help...

答:
```<code><div ng-repeat="items in objectArr">
     <div class="list">
          <a class="item" href="#">{{items['name']}}</a>
     </div>
</div>
</code>```


问:
Check if another action filter attribute is being used in action in MVC 5
I have few custom action filters like

```<code>public class CustomFilter:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}
</code>```

```<code>public class CustomFilterNew:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}
</code>```

In my action method

```<code>[CustomFilter]
[CustomFilterNew]
public ActionResult Index()
{
   return View();
}
</code>```

Lets say CustomFilterNew exactly does opposite of CustomFilter.

In such case how to prevent one filter action from executing another filter action lets say CustomFilterNew should prohibit executing CustomFilter

答:
Setting the filterContext.Result property to any non-null value will stop execution of later filters. So if your first filter sets filterContext.Result = new RedirectResult(...), the second filter and action method will never be run.

There are many ways to do that as follow

```<code>  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
         filterContext.Result = new RedirectResult("~/Home/Index");
  }
</code>```

OR

```<code>public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    //Check your condition here
    if (true)
    {
        //Create your result
        filterContext.Result = new EmptyResult();
    }
    else
        base.OnActionExecuting(filterContext);
}
</code>```

OR

```<code>public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
    ...
    if (needToRedirect) //your condition here
    {
       ...
       filterContext.Result = new RedirectToAction(string action, string controller)
       return;
    }
    ...
 }
</code>```

Another thing here i have to mentioned how to set Order of filter works you can give an Order to Action Filters as follow to execute filters in order

```<code>[FilterOne(Order = 1), FilterTwo(Order = 2)]
</code>```

Body:
I have few custom action filters like

public class CustomFilter:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}

public class CustomFilterNew:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}

In my action method

[CustomFilter]
[CustomFilterNew]
public ActionResult Index()
{
   return View();
}

Lets say CustomFilterNew exactly does opposite of CustomFilter.

In such case how to prevent one filter action from executing another filter action lets say CustomFilterNew should prohibit executing CustomFilter

Body:
Setting the filterContext.Result property to any non-null value will stop execution of later filters. So if your first filter sets filterContext.Result = new RedirectResult(...), the second filter and action method will never be run.

There are many ways to do that as follow

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
         filterContext.Result = new RedirectResult("~/Home/Index");
  }

OR

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    //Check your condition here
    if (true)
    {
        //Create your result
        filterContext.Result = new EmptyResult();
    }
    else
        base.OnActionExecuting(filterContext);
}

OR

public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
    ...
    if (needToRedirect) //your condition here
    {
       ...
       filterContext.Result = new RedirectToAction(string action, string controller)
       return;
    }
    ...
 }

Another thing here i have to mentioned how to set Order of filter works you can give an Order to Action Filters as follow to execute filters in order

[FilterOne(Order = 1), FilterTwo(Order = 2)]


问:
An app that made with sdk 4.0.1 doesn't install on device with os 4.2
I made an app with ios sdk 4.0.1 but now i want to install it from xcode on ipod touch with os 4.2 but says

No provisioned iPhone OS device is
  connected.

答:
I think above method will not resolve the problem.

Follow these steps:

1) Go into Project -> Project Edit Settings

2) Set Base Sdk iOS4.2

3) Set MacOS Deployment Target : MAC OSX 10.5

4) iOS Deployment Target: iOS4.0

Thats it

Cheers,

Tariq


问:
Map to List[Tuple2] in Scala - removes duplicates?
Am trying to convert a map to list of Tuples, given a map like below

```<code>Map("a"->2,"a"->4,"a"->5,"b"->6,"b"->1,"c"->3)
</code>```

i want output like

```<code>List(("a",2),("a",4),("a",5),("b",6),("b",1),("c",3))
</code>```

I tried following

```<code>val seq = inputMap.toList  //output (a,5)(b,1)(c,3)

var list:List[(String,Int)] = Nil
   for((k,v)<-inputMap){
       (k,v) :: list
   }  //output (a,5)(b,1)(c,3)
</code>```

Why does it remove duplicates? I dont see other tuples that has "a" as key.

答:
The problem is with Map, whose keys are a Set, so you cannot have twice the same key. This is because Maps are dictionaries, which are made to access a value by its key, so keys MUST be unique. The builder thus keeps only the last value given with the key "a".

By the way, Map already has a method toList, that do exactly what you implemented.

Body:
Am trying to convert a map to list of Tuples, given a map like below

Map("a"->2,"a"->4,"a"->5,"b"->6,"b"->1,"c"->3)

i want output like

List(("a",2),("a",4),("a",5),("b",6),("b",1),("c",3))

I tried following

val seq = inputMap.toList  //output (a,5)(b,1)(c,3)

var list:List[(String,Int)] = Nil
   for((k,v)<-inputMap){
       (k,v) :: list
   }  //output (a,5)(b,1)(c,3)

Why does it remove duplicates? I dont see other tuples that has "a" as key.


问:
Cron script Prestashop (php)
I need to make a cron script ('cron_script.php') that updates a XML. The static functions that make this are defined in my main module class 'xmlmodule.php'.

My problem is the cron script doesn't run module class with 'require' or  'require_once'. The prestashop configuration values are not loaded in script so is always exiting. If I comment the 'if' statement for check '_PS_VERSION_' I have an error output because is not finding the 'Module' class.

Here is my module main class ('xmlmodule.php'):

```<code><?php

if (!defined('_PS_VERSION_')) {
    exit;
}

class XmlModule extends Module {
    //Module functions
}
</code>```

And this is my cron script:

```<code><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo "Before require once </br>";
require_once('xmlmodule.php'); //This exits the script
echo "<h2>Prueba CRON updateFeed</h2>"; //Never executed
</code>```

I'm executing it locally with curl and crontab and my PrestaShop version is 1.6 with PHP7.0. I know about modules use cron scripts but I can find anything of code for see how to do it.

Does anyone know? Thanks a lot.

答:
I guess you could try including these prestashop files inside your xmlmodule.php

```<code>$site_base_path="./";
require_once($site_base_path . 'config/config.inc.php');
require_once($site_base_path . 'init.php');
</code>```

This way, your script will have access to all the neede prestashop classes , constants etc.

Title: Cron script Prestashop (php)

Body:
I need to make a cron script ('cron_script.php') that updates a XML. The static functions that make this are defined in my main module class 'xmlmodule.php'.

My problem is the cron script doesn't run module class with 'require' or  'require_once'. The prestashop configuration values are not loaded in script so is always exiting. If I comment the 'if' statement for check '_PS_VERSION_' I have an error output because is not finding the 'Module' class.

Here is my module main class ('xmlmodule.php'):

<?php

if (!defined('_PS_VERSION_')) {
    exit;
}

class XmlModule extends Module {
    //Module functions
}

And this is my cron script:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo "Before require once
";
require_once('xmlmodule.php'); //This exits the script
echo "
Prueba CRON updateFeed
"; //Never executed

I'm executing it locally with curl and crontab and my PrestaShop version is 1.6 with PHP7.0. I know about modules use cron scripts but I can find anything of code for see how to do it.

Does anyone know? Thanks a lot.

Body:
I guess you could try including these prestashop files inside your xmlmodule.php

$site_base_path="./";
require_once($site_base_path . 'config/config.inc.php');
require_once($site_base_path . 'init.php');

This way, your script will have access to all the neede prestashop classes , constants etc.


问:
HTML buttons with overflow SVG background
I am trying to achieve the following: I am using bootstrap, standard btn class.

So far I the background image is kind of in the correct position, but it gets cut off. I've tried overflow: visible; etc...

```<code>.btn {
  background: url('../images/button.svg') no-repeat;
  background-repeat: no-repeat;
  background-position: left;
  padding-left: 80px;
}

<button class="btn btn-default btn-lg">GET A FREE QUOTE <i class="fa fa-chevron-right" aria-hidden="true"></i></button>
</code>```

Thanks for any help

答:
Hello you can use this code below, I have uploaded your png file to mediafire. I also removed the background of your image. Here is the link: http://www.mediafire.com/view/ddv9ce54d08488m/Ky5ME_burned.png

<!DOCTYPE html>

<input type="image" src="Ky5ME_burned.png" alt="Submit" width="660" height="174">

```

Body:
I am trying to achieve the following: I am using bootstrap, standard btn class.

So far I the background image is kind of in the correct position, but it gets cut off. I've tried overflow: visible; etc...

.btn {
  background: url('../images/button.svg') no-repeat;
  background-repeat: no-repeat;
  background-position: left;
  padding-left: 80px;
}

<button class="btn btn-default btn-lg">GET A FREE QUOTE </button>

Thanks for any help

Body:
Hello you can use this code below, I have uploaded your png file to mediafire. I also removed the background of your image. Here is the link: http://www.mediafire.com/view/ddv9ce54d08488m/Ky5ME_burned.png

<!DOCTYPE html>
<html>
<head>

<a href="http://google.com">
<input type="image" src="Ky5ME_burned.png" alt="Submit" width="660" height="174">
</a>

</head>
</html>


问:
WSO2 Identity server with multiple tenants and configure the application
I have configured two tenants in my WSO2 Identity server(5.3).

```<code>mydomain.com-->tenant1
mydomain2.com--->tenant22
</code>```

Each tenant has couple of users configured in them. In Tenant1(my domain.com) I have added application under service provider.
Note: Saas check box is unchecked.

I tried to generate the OAuth access token via clientCredential and password grant types. I face issues below issues.

client credentials grant:

curl -u LdTubNF7u1pxTeWa98Q46K2vqhUa:clx4UTH1h2DdXuSMhzWrfXPSBJga -k -d "grant_type=client_credentials" -H  "Content-Type:application/x-www-form-urlencoded" http://10.37.2.XX:9763/oauth2/token

This generates the token for me. Ideally it should have failed as the application is configured for the specific tenant. I tried to access it by passing some domain name which is not listed still it works.
e.g

```<code>curl -u LdTubNF7u1pxTeWa98Q46K2vqhUa:clx4UTH1h2DdXuSMhzWrfXPSBJga -k -d "grant_type=client_credentials" -H  "Content-Type:application/x-www-form-urlencoded" http://10.37.2.XX:9763/oauth2/token?tenantDomain=mytrail.com
</code>```

password grant

curl -v -X POST -H "Authorization: Basic TGRUdWJORjd1MXB4VGVXYTk4UTQ2SzJ2cWhVYTpjbHg0VVRIMWgyRGRYdVNNaHpXcmZYUFNCSmdh" -k -d "grant_type=password&username=xxx&password=xxxx" -H "Content-Type:application/x-www-form-urlencoded" http://10.37.2.xx:9763/oauth2/token

Here the username and password belongs to tenant mydomain.com and I get below error.

```<code>[2017-03-31 01:45:33,420] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler} -  Non-SaaS service provider tenant domain is not same as user tenant domain; mydomain.com != carbon.super
[2017-03-31 01:45:33,420] DEBUG {org.wso2.carbon.identity.oauth2.token.AccessTokenIssuer} -  Invalid Grant provided by the client Id: LdTubNF7u1pxTeWa98Q46K2vqhUa
</code>```

Can any one tell me what I missed here? I want my application to be tenant specific.

thanks
Rama

答:
These two scenarios can be described as below.

In client credential grant type, token endpoint must be calculating the tenant domain information from the client id value you are sending (not by the query param) When you send the client credential grant token request, WSO2 Identity Server extracts Authorization header, gets the client Id value and finds the application. Since client Id and secret values are valid, it will return the token.

When you try password grant type providing username and password, Identity Server first verifies users tenant domain. When you provide username without the tenant domain information, Identity Server assumes the super tenant domain (carbon.super) and checks whether it matches with the Oauth application tenant domain (application is identityfied by the client id). You get the error because those two attributes are different. This scenario should work fine if your username parameter contained tenant domain as well.

Say you have a user with username user1 in mydomain.com. Give user1@mydomain.com as the username parameter value in password grant token request. Then it should return the token.

Body:
I have configured two tenants in my WSO2 Identity server(5.3).

mydomain.com-->tenant1
mydomain2.com--->tenant22

Each tenant has couple of users configured in them. In Tenant1(my domain.com) I have added application under service provider.
Note: Saas check box is unchecked.

I tried to generate the OAuth access token via clientCredential and password grant types. I face issues below issues.

client credentials grant:

curl -u LdTubNF7u1pxTeWa98Q46K2vqhUa:clx4UTH1h2DdXuSMhzWrfXPSBJga -k -d "grant_type=client_credentials" -H  "Content-Type:application/x-www-form-urlencoded" http://10.37.2.XX:9763/oauth2/token

This generates the token for me. Ideally it should have failed as the application is configured for the specific tenant. I tried to access it by passing some domain name which is not listed still it works.
e.g

curl -u LdTubNF7u1pxTeWa98Q46K2vqhUa:clx4UTH1h2DdXuSMhzWrfXPSBJga -k -d "grant_type=client_credentials" -H  "Content-Type:application/x-www-form-urlencoded" http://10.37.2.XX:9763/oauth2/token?tenantDomain=mytrail.com

password grant

curl -v -X POST -H "Authorization: Basic TGRUdWJORjd1MXB4VGVXYTk4UTQ2SzJ2cWhVYTpjbHg0VVRIMWgyRGRYdVNNaHpXcmZYUFNCSmdh" -k -d "grant_type=password&username=xxx&password=xxxx" -H "Content-Type:application/x-www-form-urlencoded" http://10.37.2.xx:9763/oauth2/token

Here the username and password belongs to tenant mydomain.com and I get below error.

[2017-03-31 01:45:33,420] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler} -  Non-SaaS service provider tenant domain is not same as user tenant domain; mydomain.com != carbon.super
[2017-03-31 01:45:33,420] DEBUG {org.wso2.carbon.identity.oauth2.token.AccessTokenIssuer} -  Invalid Grant provided by the client Id: LdTubNF7u1pxTeWa98Q46K2vqhUa

Can any one tell me what I missed here? I want my application to be tenant specific.

thanks
Rama


答:
That's because a Map doesn't allow duplicate keys:

val map = Map("a"->2,"a"->4,"a"->5,"b"->6,"b"->1,"c"->3)
println(map) // Map(a -> 5, b -> 1, c -> 3)
```

Title: Map to List[Tuple2] in Scala - removes duplicates?


问:
How to get parent property in JS object?
Not sure if title is formulated correct, but I have a JS object that looks like:

```<code>parent:{
children:[
    {
        id: "1"
        user:[
            {
                id: 'aa',
                email:'aa@google.com'
            },
            {
                id: 'b',
                email:'bbb@google.com'
            },
        ]
    },
    {
        id:"2",
        user: [
            {
                id:'aa',
                email:'aa@google.com'
            },
            {
                id:'eee',
                email:'eee@google.com'
            }
        ]
    }
]
</code>```

}

The object is way bigger but follows the above structure.

How would I go to get a list of topics each user is on, filtered b ID?
E.g. 'aa' participates in children 1 and 2
'b'  participates in child 1
etc.

I figure it out I have to map the object but not sure how to proceed after that

答:
You can loop the topic array and build a new resulting array of users, if a user already exist then just update the users topic list, else create a new user with name, email, and a topic list.

```<code>let result = [];
project.topics.forEach((t) => {
  t.participants.forEach((p) => {
    let found = result.find((r) => r.name === p.id);

    if (found) {
      found.topics.push(t.id);
    } else {
      result.push({
        name: p.id,
        email: p.email,
        topics: [t.id]
      });
    }
  });
});
</code>```

so now when you have the resulting array, you can just find a user and get which topics she participates in

```<code>let aa = result.find((r) => r.name === 'aa');
console.log(aa.topics);
</code>```

Body:
Not sure if title is formulated correct, but I have a JS object that looks like:

parent:{
children:[
    {
        id: "1"
        user:[
            {
                id: 'aa',
                email:'aa@google.com'
            },
            {
                id: 'b',
                email:'bbb@google.com'
            },
        ]
    },
    {
        id:"2",
        user: [
            {
                id:'aa',
                email:'aa@google.com'
            },
            {
                id:'eee',
                email:'eee@google.com'
            }
        ]
    }
]

}

The object is way bigger but follows the above structure.

How would I go to get a list of topics each user is on, filtered b ID?
E.g. 'aa' participates in children 1 and 2
'b'  participates in child 1
etc.

I figure it out I have to map the object but not sure how to proceed after that

Body:
You can loop the topic array and build a new resulting array of users, if a user already exist then just update the users topic list, else create a new user with name, email, and a topic list.

let result = [];
project.topics.forEach((t) => {
  t.participants.forEach((p) => {
    let found = result.find((r) => r.name === p.id);

    if (found) {
      found.topics.push(t.id);
    } else {
      result.push({
        name: p.id,
        email: p.email,
        topics: [t.id]
      });
    }
  });
});

so now when you have the resulting array, you can just find a user and get which topics she participates in

let aa = result.find((r) => r.name === 'aa');
console.log(aa.topics);


问:
Max Flow Min Cut
So I have worked out that there is a Max Flow of 10, which therefore means there is a minimum cut also of 10 however how do I draw a minimum cut of 10 on this image?

答:
Let me assume:

the vertex in the top of the S is A (S -> A = 6)

the vertex in the right side of S is C (S -> C =  6)

the vertex in the right side of A is B (A -> B = 3)

the vertex in the right side of C is F (C -> F  = 3)

the vertex in the bottom of the graph is D (S -> D = 2 )

So the final min-cut edges are:

A -> B = 3

C -> F = 3

S -> D = 2

C -> D = 2

The source vertices also are: S, A, C

Title: Max Flow Min Cut


问:
How to copy data from one csv to another with respect to header names in python?
I have two CSV files one with certain columns and rows, the second one has just one row with headers in it, The headers in the second file has more headers than first but includes all the headers from the first file.
I want to fill the columns in the second file when it matches the header from the first file.
The first file is a raw data file which has 20 columns with 100,000 rows that need to be copied to the working file that has 30 columns(20 columns are same as raw). The working file also has no data in it except column headers.
I am able to copy the data with the code below but it but it changes the sequence of columns.I want the sequence of columns in working file intact.
I am pretty new to the language, I would really appreciate any help.

The code i am using right now is:

```<code>import os
import glob
import pandas as pd
def concatenate(indir = "", outfile = "",outdf=""):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    for fileName in fileList:
        print(fileName)
        df=pd.read_csv(fileName,low_memory=False)
        dfList.append(df)
    concatdf=pd.concat(dfList, axis=0)
    concatdf.to_csv(outfile, index=False)
concatenate(indir = "xyz.csv", outfile = "abc.csv")
</code>```

答:
consider dataframes abc and xyz

```<code>xyz = pd.DataFrame(dict(a=[1, 2, 3], b=[1, 2, 3], c=[1, 2, 3], d=[1, 2, 3]))
abc = pd.DataFrame(columns=list('artbnckld'))

xyz

   a  b  c  d
0  1  1  1  1
1  2  2  2  2
2  3  3  3  3

abc

Empty DataFrame
Columns: [a, r, t, b, n, c, k, l, d]
Index: []
</code>```

```<code>abc.append(xyz)[abc.columns.tolist()]

     a    r    t    b    n    c    k    l    d
0  1.0  NaN  NaN  1.0  NaN  1.0  NaN  NaN  1.0
1  2.0  NaN  NaN  2.0  NaN  2.0  NaN  NaN  2.0
2  3.0  NaN  NaN  3.0  NaN  3.0  NaN  NaN  3.0
</code>```

You can then export to a csv file

```<code>abc.append(xyz)[abc.columns.tolist()].to_csv()

,a,r,t,b,n,c,k,l,d
0,1.0,,,1.0,,1.0,,,1.0
1,2.0,,,2.0,,2.0,,,2.0
2,3.0,,,3.0,,3.0,,,3.0
</code>```

Body:
I have two CSV files one with certain columns and rows, the second one has just one row with headers in it, The headers in the second file has more headers than first but includes all the headers from the first file.
I want to fill the columns in the second file when it matches the header from the first file.
The first file is a raw data file which has 20 columns with 100,000 rows that need to be copied to the working file that has 30 columns(20 columns are same as raw). The working file also has no data in it except column headers.
I am able to copy the data with the code below but it but it changes the sequence of columns.I want the sequence of columns in working file intact.
I am pretty new to the language, I would really appreciate any help.

The code i am using right now is:

import os
import glob
import pandas as pd
def concatenate(indir = "", outfile = "",outdf=""):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    for fileName in fileList:
        print(fileName)
        df=pd.read_csv(fileName,low_memory=False)
        dfList.append(df)
    concatdf=pd.concat(dfList, axis=0)
    concatdf.to_csv(outfile, index=False)
concatenate(indir = "xyz.csv", outfile = "abc.csv")

Body:
consider dataframes abc and xyz

xyz = pd.DataFrame(dict(a=[1, 2, 3], b=[1, 2, 3], c=[1, 2, 3], d=[1, 2, 3]))
abc = pd.DataFrame(columns=list('artbnckld'))

xyz

   a  b  c  d
0  1  1  1  1
1  2  2  2  2
2  3  3  3  3

abc

Empty DataFrame
Columns: [a, r, t, b, n, c, k, l, d]
Index: []

abc.append(xyz)[abc.columns.tolist()]

     a    r    t    b    n    c    k    l    d
0  1.0  NaN  NaN  1.0  NaN  1.0  NaN  NaN  1.0
1  2.0  NaN  NaN  2.0  NaN  2.0  NaN  NaN  2.0
2  3.0  NaN  NaN  3.0  NaN  3.0  NaN  NaN  3.0

You can then export to a csv file

abc.append(xyz)[abc.columns.tolist()].to_csv()

,a,r,t,b,n,c,k,l,d
0,1.0,,,1.0,,1.0,,,1.0
1,2.0,,,2.0,,2.0,,,2.0
2,3.0,,,3.0,,3.0,,,3.0


答:
in PrestaShop cron always add at the beginning:

```<code>include(dirname(__FILE__).'/../../config/config.inc.php');
</code>```

If the cron is module is fine as I wrote it, or increase or decrease the "../" directory.

With that include the function of PrestaShop global functions and variables

Title: Cron script Prestashop (php)

Body:
in PrestaShop cron always add at the beginning:

include(dirname(__FILE__).'/../../config/config.inc.php');

If the cron is module is fine as I wrote it, or increase or decrease the "../" directory.

With that include the function of PrestaShop global functions and variables


问:
SQL: How to dynamically loop & add N number of column with NULL value into temp table
Due to a certain requirement, I need to create two temp tables in Stored Procedure, after processing some data into them, I need to combine the two temp tables to show as one result set and generate into excel. So I'm thinking to use UNION when I want to show the final result set.

The issue is, the first temp table (Table A) is fixed to 20 columns, and the second temp table has 50 columns (Table B). My plan is, before processing data for Table A, I want to add 30 nullable columns and insert data for first 20 columns, and the rest is all NULL

After I process the data for Table B, I use UNION to combine Table A & B so that they will show as one result set.

What I can think of right now is to hard code some columns that are destined to have null values when I declare the temp table:

```<code>Declare @tmpTableA table (
  ....
  ProcessDate datetime,
  Mode int,
  Col21 varchar(10)
  Col22 varchar(10)
  ....
  Col50 varchar(50)
)
</code>```

When I insert data into Table A, I have to manually add null from Col21 onwards

```<code>Insert into(.... Col21, Col22, Col23....)
Values (.... NULL, NULL, NULL....)
</code>```

After I complete processing data for Table A & B, I use UNION to merge Table A and B

```<code>Select *....Col49,Col50 From Table A
Union
Select *....CompleteDate,ContactPerson From Table B
</code>```

Instead of hard-coding Col21 to Col50 into Table A, is there any elegant way to achieve that like using while loop to dynamically add N number of columns into Table A?

EDIT:
According to latest requirement, Table B has not only 50 columns but 100 columns! I really need a way to dynamically loop those columns rather than hard-coding for over 80 columns

答:
I think you can just do

```<code>select * into #tableA from #tableB where 1=2
</code>```

with this both tables will have same columns

Body:
Due to a certain requirement, I need to create two temp tables in Stored Procedure, after processing some data into them, I need to combine the two temp tables to show as one result set and generate into excel. So I'm thinking to use UNION when I want to show the final result set.

The issue is, the first temp table (Table A) is fixed to 20 columns, and the second temp table has 50 columns (Table B). My plan is, before processing data for Table A, I want to add 30 nullable columns and insert data for first 20 columns, and the rest is all NULL

After I process the data for Table B, I use UNION to combine Table A & B so that they will show as one result set.

What I can think of right now is to hard code some columns that are destined to have null values when I declare the temp table:

Declare @tmpTableA table (
  ....
  ProcessDate datetime,
  Mode int,
  Col21 varchar(10)
  Col22 varchar(10)
  ....
  Col50 varchar(50)
)

When I insert data into Table A, I have to manually add null from Col21 onwards

Insert into(.... Col21, Col22, Col23....)
Values (.... NULL, NULL, NULL....)

After I complete processing data for Table A & B, I use UNION to merge Table A and B

Select *....Col49,Col50 From Table A
Union
Select *....CompleteDate,ContactPerson From Table B

Instead of hard-coding Col21 to Col50 into Table A, is there any elegant way to achieve that like using while loop to dynamically add N number of columns into Table A?

EDIT:
According to latest requirement, Table B has not only 50 columns but 100 columns! I really need a way to dynamically loop those columns rather than hard-coding for over 80 columns

Body:
I think you can just do

select * into #tableA from #tableB where 1=2

with this both tables will have same columns


问:
What is better way to do paging database with Rest api
I am trying to list all information of a registered user in table called clients Clients

Clients has more than 10000 rows. I want to page it by 50 or 100 with a single API.

In Hibernate HQL FROM Clients returns all clients or I can set max and limit number of results.

Currently for API, user wants to work properly total number of clients required.

How can I do it in single HQL query

答:
required parameter:

int page -> page number,

int recordePerPage -> required record per page, in your case it will
50 or 100
@return : null in case of no result, in case of result return list of clint with pagination.

public List getAllClintWithPagination(int page, int recordePerPage) {

```<code>        session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tr = null;
        try {
            tr = session.beginTransaction();
            Criteria cr = session.createCriteria(Clint.class);
            cr.setFirstResult((page - 1) * recordePerPage);
            cr.setMaxResults(recordePerPage);
            List<Clint> clintAll = cr.list();
            tr.commit();

            if (clintAll.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("clint are not exist");
            }
            return null;
            } else {

            return clintAll;
            }
        } catch (RuntimeException ex) {
            log.error(ex);
            if (tr != null) {
            tr.rollback(); // roll back the transaction due to runtime error
            }
            return null;
        }
    }
</code>```

Body:
required parameter:

int page -> page number,

int recordePerPage -> required record per page, in your case it will
50 or 100
@return : null in case of no result, in case of result return list of clint with pagination.

public List getAllClintWithPagination(int page, int recordePerPage) {

        session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tr = null;
        try {
            tr = session.beginTransaction();
            Criteria cr = session.createCriteria(Clint.class);
            cr.setFirstResult((page - 1) * recordePerPage);
            cr.setMaxResults(recordePerPage);
            List<Clint> clintAll = cr.list();
            tr.commit();

            if (clintAll.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("clint are not exist");
            }
            return null;
            } else {

            return clintAll;
            }
        } catch (RuntimeException ex) {
            log.error(ex);
            if (tr != null) {
            tr.rollback(); // roll back the transaction due to runtime error
            }
            return null;
        }
    }


问:
How to compile storyboard in playground
I am creating an app on playground, I added a Main.storyboard file in this project. but when its compile, it gives me the following error.

```<code>NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main' in bundle NSBundle
</code>```

so i start thinking that it maybe some typo, so that's why this error generates. but this was not the problem, so i start searching on google, and stackoverflow, but did not find the solution about my problem. There are many questions on stackoverflow with the following content however, each has a very specific scenario.

then i find a playground project from github, in which the developer added a main storyboard and its compiling perfectly, but its extension is Main.storyboardc. then i search about storyboardc extension. so i understand its a compile storyboard.
then for just checking i double tap the the Main.storyboard and change its name to Main.storyboadc. then the following error generates

```<code>'NSInvalidArgumentException', reason: 'There doesn't seem to be a valid compiled storyboard
</code>```

Now at this point I am sure that i have to compile my storyboard first then it will add in my playground, because with out  .storyboardc extension, it did not even find the Main storyboard. as i stated above.
so again i already check all the material on stackoverflow, each has a very specific scenario. so guide me how to compile main.storyboard.

答:
The command ibtool will do exactly this for you.

So for example, you can run
ibtool --compile Main.storyboardc Main.storyboard inside the terminal.
After that, all relevant files (Info.plist and .nib files) will be created inside the Main.storyboardc.

Now you can take that .storyboardc file and place it inside a project and reference the files inside the storyboard as you normally would.

```<code>let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let viewController = storyboard.instantiateViewController(withIdentifier: "MyViewController")
</code>```

A .storyboardc file is nothing more than a group of nib files.

For more information have a look at the manual page man ibtool

Title: How to compile storyboard in playground

Body:
I am creating an app on playground, I added a Main.storyboard file in this project. but when its compile, it gives me the following error.

NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main' in bundle NSBundle

so i start thinking that it maybe some typo, so that's why this error generates. but this was not the problem, so i start searching on google, and stackoverflow, but did not find the solution about my problem. There are many questions on stackoverflow with the following content however, each has a very specific scenario.

then i find a playground project from github, in which the developer added a main storyboard and its compiling perfectly, but its extension is Main.storyboardc. then i search about storyboardc extension. so i understand its a compile storyboard.
then for just checking i double tap the the Main.storyboard and change its name to Main.storyboadc. then the following error generates

'NSInvalidArgumentException', reason: 'There doesn't seem to be a valid compiled storyboard

Now at this point I am sure that i have to compile my storyboard first then it will add in my playground, because with out  .storyboardc extension, it did not even find the Main storyboard. as i stated above.
so again i already check all the material on stackoverflow, each has a very specific scenario. so guide me how to compile main.storyboard.

Body:
The command ibtool will do exactly this for you.

So for example, you can run
ibtool --compile Main.storyboardc Main.storyboard inside the terminal.
After that, all relevant files (Info.plist and .nib files) will be created inside the Main.storyboardc.

Now you can take that .storyboardc file and place it inside a project and reference the files inside the storyboard as you normally would.

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let viewController = storyboard.instantiateViewController(withIdentifier: "MyViewController")

A .storyboardc file is nothing more than a group of nib files.

For more information have a look at the manual page man ibtool


问:
How to Integrate Paypal Payment gateway in laravel?
How to Integrate Paypal Payment gateway in Laravel?
I tried this http://www.17educations.com/laravel/paypal-integration-in-laravel/
but config have some problem,Please anybody say some ideas </p>

答:
Follow Bellow Few Step:

1)Install Laravel Application

2)Database Configuration

3)Install Required Packages

4)configuration paypal.php file

5)create route

6)create controller

7)create view file

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

```
composer create-project --prefer-dist laravel/laravel blog
```

Step 2 : Database Configuration

In this step, we require to make database configuration, you have to add
 following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:
.env

```<code>DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```

Step 3 : Install Required Packages

We have required following 2 packages for integrate paypal payment in our laravel application.
add following two package in your composer.json file.

```<code>"guzzlehttp/guzzle": "~5.4",
"paypal/rest-api-sdk-php": "*",
</code>```

then after run following command in your terminal. vendor:publish command is used to copy few configuration file in your application from vendor package file.

```<code>php artisan vendor:publish
</code>```

after run this command, then after automatic create paypal.php file in your config/paypal.php path.

Step 4 : Configuration paypal.php file

```<code><?php

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration
*/
'settings' => array(
    /**
    * Available option 'sandbox' or 'live'
    */
    'mode' => 'sandbox',
    /**
    * Specify the max request time in seconds
    */
    'http.ConnectionTimeOut' => 1000,
    /**
    * Whether want to log to a file
    */
    'log.LogEnabled' => true,
    /**
    * Specify the file that want to write on
    */
    'log.FileName' => storage_path() . '/logs/paypal.log',
    /**
    * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
    *
    * Logging is most verbose in the 'FINE' level and decreases as you
    * proceed towards ERROR
    */
    'log.LogLevel' => 'FINE'
    ),
);
</code>```

Step 5: Create Route

In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route.
routes/web.php

```<code>Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'AddMoneyController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'AddMoneyController@getPaymentStatus',));
</code>```

Step 6: Create Controller

In this point, now we should create new controller as AddMoneyController in this path app/Http/Controllers/AddMoneyController.php. this controller will manage layout and payment post request, So run bellow command for generate new controller:

```<code>php artisan make:controller AddMoneyController
</code>```

Ok, now put bellow content in controller file:

app/Http/Controllers/AddMoneyController.php

```<code><?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class AddMoneyController extends HomeController
{

    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        /** setup PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item_1 = new Item();

        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        /** add payment ID to session **/
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }

    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') {

            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/

            \Session::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');

        return Redirect::route('addmoney.paywithpaypal');
    }
  }
</code>```

Now we are ready to run our example so run bellow command ro quick run:

```<code>php artisan serve
</code>```

Now you can open bellow URL on your browser:

```<code>http://localhost:8000/paywithpaypal
</code>```

please visit this toturials link..

https://www.youtube.com/watch?v=ly2xm_NM46g

http://laravelcode.com/post/how-to-integrate-paypal-payment-gateway-in-laravel-54

Body:
Follow Bellow Few Step:

1)Install Laravel Application

2)Database Configuration

3)Install Required Packages

4)configuration paypal.php file

5)create route

6)create controller

7)create view file

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Database Configuration

In this step, we require to make database configuration, you have to add
 following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:
.env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Step 3 : Install Required Packages

We have required following 2 packages for integrate paypal payment in our laravel application.
add following two package in your composer.json file.

"guzzlehttp/guzzle": "~5.4",
"paypal/rest-api-sdk-php": "*",

then after run following command in your terminal. vendor:publish command is used to copy few configuration file in your application from vendor package file.

php artisan vendor:publish

after run this command, then after automatic create paypal.php file in your config/paypal.php path.

Step 4 : Configuration paypal.php file

&lt;?php

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration
*/
'settings' => array(
    /**
    * Available option 'sandbox' or 'live'
    */
    'mode' => 'sandbox',
    /**
    * Specify the max request time in seconds
    */
    'http.ConnectionTimeOut' => 1000,
    /**
    * Whether want to log to a file
    */
    'log.LogEnabled' => true,
    /**
    * Specify the file that want to write on
    */
    'log.FileName' => storage_path() . '/logs/paypal.log',
    /**
    * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
    *
    * Logging is most verbose in the 'FINE' level and decreases as you
    * proceed towards ERROR
    */
    'log.LogLevel' => 'FINE'
    ),
);

Step 5: Create Route

In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route.
routes/web.php

Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'AddMoneyController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'AddMoneyController@getPaymentStatus',));

Step 6: Create Controller

In this point, now we should create new controller as AddMoneyController in this path app/Http/Controllers/AddMoneyController.php. this controller will manage layout and payment post request, So run bellow command for generate new controller:

php artisan make:controller AddMoneyController

Ok, now put bellow content in controller file:

app/Http/Controllers/AddMoneyController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class AddMoneyController extends HomeController
{

    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        /** setup PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item_1 = new Item();

        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        /** add payment ID to session **/
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }

    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') {

            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/

            \Session::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');

        return Redirect::route('addmoney.paywithpaypal');
    }
  }

Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/paywithpaypal

please visit this toturials link..

https://www.youtube.com/watch?v=ly2xm_NM46g

http://laravelcode.com/post/how-to-integrate-paypal-payment-gateway-in-laravel-54


问:
Update column using the same column from another table and gruoping by another and make sum equal
There are 2 tables - DepoSevkDetay и SatisDetay. Both have columns - Miktar and UrunID. I need to make sum of Miktar in DepoSevkDetay for each UrunID equal to sum of Miktar in SatisDetay. Query I ve written cant handle it.    What am I doing wrong? Considering that count of records in two tables is not equal

        ```</p>

<code>UPDATE
    Table_A
SET
    Table_A.[Miktar] = (((Table_B.Miktar)/Table_C.c) +
(case when ((Table_B.Miktar) % Table_C.c  < Table_C.r) then 1
                                                        else 0 end ))
FROM
    [Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
    INNER JOIN (
                SELECT COUNT([UrunID]) AS c, ROW_NUMBER() OVER (ORDER BY UrunID) r, UrunID as UrunID
                FROM tb_DepoSevkDetay
                GROUP BY UrunID ) AS Table_C
        ON Table_B.[UrunID] = Table_C.[UrunID]
</code>```

答:
your requirement is not very clear.

Explain with one example

```<code>update dd
set Miktar=sd.Miktar
DepoSevkDetay DD
inner join
(select UrunID, sum(Miktar) Miktar
from SatisDetay
group by UrunID)SD
on dd.UrunID=sd.UrunID
</code>```

Body:
There are 2 tables - DepoSevkDetay и SatisDetay. Both have columns - Miktar and UrunID. I need to make sum of Miktar in DepoSevkDetay for each UrunID equal to sum of Miktar in SatisDetay. Query I ve written cant handle it.    What am I doing wrong? Considering that count of records in two tables is not equal

UPDATE
    Table_A
SET
    Table_A.[Miktar] = (((Table_B.Miktar)/Table_C.c) +
(case when ((Table_B.Miktar) % Table_C.c  < Table_C.r) then 1
                                                        else 0 end ))
FROM
    [Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
    INNER JOIN (
                SELECT COUNT([UrunID]) AS c, ROW_NUMBER() OVER (ORDER BY UrunID) r, UrunID as UrunID
                FROM tb_DepoSevkDetay
                GROUP BY UrunID ) AS Table_C
        ON Table_B.[UrunID] = Table_C.[UrunID]

Body:
your requirement is not very clear.

Explain with one example

update dd
set Miktar=sd.Miktar
DepoSevkDetay DD
inner join
(select UrunID, sum(Miktar) Miktar
from SatisDetay
group by UrunID)SD
on dd.UrunID=sd.UrunID