问:
Jquery Ajax Post array of input data
I am writing a thing to compare two passwords with each other, if they match the script sends out a response that says it is the same.

I currently have got this code:

```<code>$("#repeatPw").keyup(function(){
    jQuery.ajax({
        url: "System/Javascript/Functions/checkPasswords.php",
        data: "'password1'='" + $("#Password").val() + "', 'password2'='" + $("#repeatPw").val() + "'",
        type: "POST",
        success: function(data) {
            $("#passwordMatch").html(data);
        },
        error: function(data) {}
    });
});
</code>```

Now my problem is that i cant get this password1 and password2 in a proper array i can explode in the checkPasswords.php, this posts this:

Array ( ['password1'] => 'fasfasdfasSD2', 'password2'='asdasdasd' )

But this is not a proper array as it only puts password1 in proper array format, how would i go about making password2 in this format too?

Thank you all in advance!

答:
You can do it with a FormData object:

```<code>$("#repeatPw").keyup(function(){
  var fd = new FormData();
  fd.append('password1', $("#Password").val());
  fd.append('password2', $("#Password").val());
  jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data: fd,
    type: "POST",
      success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
  });
});
</code>```

Or do it the JSON way:

```<code>$("#repeatPw").keyup(function(){
  jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data :{
            password1: $("#Password").val(),
            password2: $("#repeatPw").val(),
            },
    type: "POST",
    success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
  });
});
</code>```

Title: Jquery Ajax Post array of input data

Body:
I am writing a thing to compare two passwords with each other, if they match the script sends out a response that says it is the same.

I currently have got this code:

$("#repeatPw").keyup(function(){
    jQuery.ajax({
        url: "System/Javascript/Functions/checkPasswords.php",
        data: "'password1'='" + $("#Password").val() + "', 'password2'='" + $("#repeatPw").val() + "'",
        type: "POST",
        success: function(data) {
            $("#passwordMatch").html(data);
        },
        error: function(data) {}
    });
});

Now my problem is that i cant get this password1 and password2 in a proper array i can explode in the checkPasswords.php, this posts this:

Array ( ['password1'] => 'fasfasdfasSD2', 'password2'='asdasdasd' )

But this is not a proper array as it only puts password1 in proper array format, how would i go about making password2 in this format too?

Thank you all in advance!

Body:
You can do it with a FormData object:

$("#repeatPw").keyup(function(){
  var fd = new FormData();
  fd.append('password1', $("#Password").val());
  fd.append('password2', $("#Password").val());
  jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data: fd,
    type: "POST",
      success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
  });
});

Or do it the JSON way:

$("#repeatPw").keyup(function(){
  jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data :{
            password1: $("#Password").val(),
            password2: $("#repeatPw").val(),
            },
    type: "POST",
    success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
  });
});


来源: stackexchange

问:
Android shortcut to write multiple lines of code
I am writing an string array in the string.xml file in android, it is of 300 elements which has incrementing values, just like the one mentioned below with 5 elements :

```<code><string-array name="values">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
        <item>Item 4</item>
        <item>Item 5</item>
        <item>Item 6</item>
 </string-array>
</code>```

Is there any shortcut to write this code in the xml file?

答: Try emmet plugin for android studio, it is very helpful when you have to write long serialized xml code, plus  it saves a huge time.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am writing an string array in the string.xml file in android, it is of 300 elements which has incrementing values, just like the one mentioned below with 5 elements :

<string-array name="values">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
        <item>Item 4</item>
        <item>Item 5</item>
        <item>Item 6</item>
 </string-array>

Is there any shortcut to write this code in the xml file?


问:
Is there a way to pass an argument to a setter
Is there a way to pass an argument to a setter?
How would I pass a string into the setter below?
How would I call the setter with the new string param?

```<code>public string It
{
   get{ { return it;}

   set { it = value;}
}
</code>```

Thank you very much

答:
To compliment what everyone else has said in this aged thread...

Perhaps a better method would be to define a struct to hold the extra information you want to pass, then pass the data this way.  For instance:

struct PersonName {

    public string Forename { get; set; }
    public string Surname { get; set; }

    public PersonName(string fn, string sn) {
        Forename = fn;
        Surname = sn;
    }

}

class MyPerson {

    public string Forename { get; set; }
    public string Surname { get; set; }
    public DateTime dob { get; set; }

    ...

    public PersonName Fullname {
        get { return Forename + " " + Surname; }
        set {
            Forename = value.Forename;
            Surname = value.Surname;
        }
    }
}

...

    public void main() {
        MyPerson aPerson = new MyPerson;
        aPerson.Fullname = new PersonName("Fred", "Bloggs");
    }
```

Personally, though, I think this is overkill for something so minor.  Also, it then beggars the question - why wasn't the Forename, Surname pair already defined as the appropriate struct (PersonName)?

Body:
Is there a way to pass an argument to a setter?
How would I pass a string into the setter below?
How would I call the setter with the new string param?

public string It
{
   get{ { return it;}

   set { it = value;}
}

Thank you very much

Body:
To compliment what everyone else has said in this aged thread...

Perhaps a better method would be to define a struct to hold the extra information you want to pass, then pass the data this way.  For instance:

struct PersonName {

    public string Forename { get; set; }
    public string Surname { get; set; }

    public PersonName(string fn, string sn) {
        Forename = fn;
        Surname = sn;
    }

}

class MyPerson {

    public string Forename { get; set; }
    public string Surname { get; set; }
    public DateTime dob { get; set; }

    ...

    public PersonName Fullname {
        get { return Forename + " " + Surname; }
        set {
            Forename = value.Forename;
            Surname = value.Surname;
        }
    }
}

...

    public void main() {
        MyPerson aPerson = new MyPerson;
        aPerson.Fullname = new PersonName("Fred", "Bloggs");
    }

Personally, though, I think this is overkill for something so minor.  Also, it then beggars the question - why wasn't the Forename, Surname pair already defined as the appropriate struct (PersonName)?


问:
Get value of a text box of a pop up menu
I have a pop up menu,which has a text box,when I go in a inspect elemnt its like the following,my question is how can get the value of this specific box</p>

```<code>< input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP" >
</code>```

答:
In jQuery, you can get and set values of inputs via val(). The following should work

```<code>$('input[name="DeviceIP"]').val();
</code>```

If you wanna do it in pure javascript, you can do this instead:

```<code>document.getElementsByName("DeviceIP")[0].value;
</code>```

Body:
I have a pop up menu,which has a text box,when I go in a inspect elemnt its like the following,my question is how can get the value of this specific box

< input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP" >

Body:
In jQuery, you can get and set values of inputs via val(). The following should work

$('input[name="DeviceIP"]').val();

If you wanna do it in pure javascript, you can do this instead:

document.getElementsByName("DeviceIP")[0].value;


问:
Symfony: qpush subcriber don't handle AWS SNS message
I'm using the qpush-bundle to send push messages to my application. The goal is to perform asynchronous tasks.

I'm using AWS SQS and SNS to dispatch my message back to my symfony application, that then should be handled by the service I configured.

From the docs:

Once a message is received via POST from your Message Queue, a MessageEvent is dispatched which can be handled by your services. Each MessageEvent contains the name of the queue and a Uecode\Bundle\QPushBundle\Message\Message object, accessible through getters.

My problem:

The event does not seems to be catched: The processing in my service is not performed.

```<code>class AsyncService
{
    public function onMessageReceived(MessageEvent $event)
    {
        // do some processing
    }
}
</code>```

Additional info:

The notification is correctly sent, as I verified in the access_log:

```<code>"POST / HTTP/1.1" 200 45 "-" "Amazon Simple Notification Service Agent"
</code>```

config.yml:

```<code>uecode_qpush:
providers:
    aws:
        driver: aws
        key: '%aws_access_key%'
        secret: '%aws_secret%'
        region: eu-central-1
queues:
    civbq:
        provider: aws
        options:
            queue_name: myqueuename
            push_notifications: true
            subscribers:
                - { endpoint: https://my-site.com/, protocol: https }
</code>```

services.yml:

```<code>async_service:
    class: AppBundle\Service\AsyncService
    arguments: [@doctrine.orm.entity_manager, @uecode_qpush]
    tags:
        - { name: uecode_qpush.event_listener, event: myqueuename.message_received, method: onMessageReceived }
</code>```

Also I had to create a SNS topic named "myqueuename", to not get a Topic does not exist error.

答:
It event: civbq.message_received rather than event: myqueuename.message_received, the new documentation make this clearer, civbq is the queue key, and the my_queue_key rather than the queue_name is what should be used.

```<code>queues:
    my_queue_key:
        provider: aws
        options:
            queue_name:                  my_actual_queue_name
</code>```

Body:
I'm using the qpush-bundle to send push messages to my application. The goal is to perform asynchronous tasks.

I'm using AWS SQS and SNS to dispatch my message back to my symfony application, that then should be handled by the service I configured.

From the docs:

Once a message is received via POST from your Message Queue, a MessageEvent is dispatched which can be handled by your services. Each MessageEvent contains the name of the queue and a Uecode\Bundle\QPushBundle\Message\Message object, accessible through getters.

My problem:

The event does not seems to be catched: The processing in my service is not performed.

class AsyncService
{
    public function onMessageReceived(MessageEvent $event)
    {
        // do some processing
    }
}

Additional info:

The notification is correctly sent, as I verified in the access_log:

"POST / HTTP/1.1" 200 45 "-" "Amazon Simple Notification Service Agent"

config.yml:

uecode_qpush:
providers:
    aws:
        driver: aws
        key: '%aws_access_key%'
        secret: '%aws_secret%'
        region: eu-central-1
queues:
    civbq:
        provider: aws
        options:
            queue_name: myqueuename
            push_notifications: true
            subscribers:
                - { endpoint: https://my-site.com/, protocol: https }

services.yml:

async_service:
    class: AppBundle\Service\AsyncService
    arguments: [@doctrine.orm.entity_manager, @uecode_qpush]
    tags:
        - { name: uecode_qpush.event_listener, event: myqueuename.message_received, method: onMessageReceived }

Also I had to create a SNS topic named "myqueuename", to not get a Topic does not exist error.

Body:
It event: civbq.message_received rather than event: myqueuename.message_received, the new documentation make this clearer, civbq is the queue key, and the my_queue_key rather than the queue_name is what should be used.

queues:
    my_queue_key:
        provider: aws
        options:
            queue_name:                  my_actual_queue_name


问:
How could I set the url of microsoft emotion api by javascript
I use following javascript

```<code>document.getElementsByName("Image.Url")[0].placeholder = "waha"
</code>```

setup the value of the url of the microsoft emotion webpage, but the results I got is "light text".

Problem of "light text" is the webpage will not consider your input value as a valid url.

The result I need is normal text(if you input your text manually, color of the text will become "deeper") as following

答:
You're using the wrong attribute:

document.getElementsByName("Image.Url")[0].placeholder = "waha"

The placeholder attribute specifies a short hint that describes the expected value of an <input> element. It's the light text displayed in the <input> element before the user enters a value.

For setting the (initial) value of an HTML <input> element, you need to use the value attribute, e.g.:

document.getElementsByName("Image.Url")[0].value = "waha"

You could find more information on HTML <input> Tag and its attributes: here

Body:
I use following javascript

document.getElementsByName("Image.Url")[0].placeholder = "waha"

setup the value of the url of the microsoft emotion webpage, but the results I got is "light text".

Problem of "light text" is the webpage will not consider your input value as a valid url.

The result I need is normal text(if you input your text manually, color of the text will become "deeper") as following


问:
Stripe Checkout charging a card
I have this code that works great.

```<code><input class="form-control"
   type="number"
   id="custom-donation-amount"
   placeholder="50.00"
   min="0"
   value="50"
   step="10.00"/>
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton" class="pay-button">
    <h4 class="donate-text button">Donate by
    <img src="http://#/testing/credit-card.png" ></h4>
</button>

<script>
  var handler = StripeCheckout.configure({
key: 'pk_test_mytestingkey',
image: '',
locale: 'auto',
token: function(token) {
  // Use the token to create the charge with a server-side script.
  // You can access the token ID with `token.id`
}
  });

 $('#customButton').on('click', function(e) {
// Open Checkout with further options
 var amount = $("#custom-donation-amount").val() * 100;
handler.open({
  name: 'Testing',
  description: 'Testing',
  amount: amount
});
e.preventDefault();
});

 // Close Checkout on page navigation
 $(window).on('popstate', function() {
    handler.close();
  });
 </script>
</code>```

It states on the documentation:
"On your server, grab the Stripe token in the POST parameters submitted by your form. From there, it's one simple API call to charge the card:"
I am trying to CHARGE the card information. Stripe provides the following API call to do that: I am assuming this is a charge.php file?

```<code>// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_mykey");

// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];

// Create the charge on Stripe's servers - this will charge the user's card
try {
  $charge = \Stripe\Charge::create(array(
    "amount" => 1000, // amount in cents, again
    "currency" => "usd",
    "source" => $token,
    "description" => "Example charge"
    ));
} catch(\Stripe\Error\Card $e) {
  // The card has been declined
}
</code>```

My question: how do I charge the card using the following code without there being a <form> method post, or <form> action...? It's using javascript to capture the token. But I don't know how to send that token to a charge.php file... Basically how do I grab that stripe token and initiate the API call? How do I initiate the API call....?

答:
If your are using mamp. UPDATE TO MAMP 4
stripes API no longer supports older versions of MAMP.

Title: Stripe Checkout charging a card

Body:
I have this code that works great.

<input class="form-control"
   type="number"
   id="custom-donation-amount"
   placeholder="50.00"
   min="0"
   value="50"
   step="10.00"/>

<button id="customButton" class="pay-button">

Donate by

</button>

It states on the documentation:
"On your server, grab the Stripe token in the POST parameters submitted by your form. From there, it's one simple API call to charge the card:"
I am trying to CHARGE the card information. Stripe provides the following API call to do that: I am assuming this is a charge.php file?

// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_mykey");

// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];

// Create the charge on Stripe's servers - this will charge the user's card
try {
  $charge = \Stripe\Charge::create(array(
    "amount" => 1000, // amount in cents, again
    "currency" => "usd",
    "source" => $token,
    "description" => "Example charge"
    ));
} catch(\Stripe\Error\Card $e) {
  // The card has been declined
}

My question: how do I charge the card using the following code without there being a <form> method post, or <form> action...? It's using javascript to capture the token. But I don't know how to send that token to a charge.php file... Basically how do I grab that stripe token and initiate the API call? How do I initiate the API call....?


问:
What does this exam paper C# code do?
I managed to figure out the code for question 4, but it looks wrong:

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        string msg = "";
        int i = 1;

        while (i < 6)
        {
            int col = 0;
            while (col < i)
            {
                msg += i;
                col++;
            }
            msg += "\n";
            i++;
        }

        MessageBox.Show(msg);
    }
</code>```

Is there a simpler way to do it by using for and if statements?

Also for question 5, I am completely lost.

答:
for Question 4 you can try this simple code

```<code>                for (int i = 1; i <= 5; i++)
                {
                    for(int j=0;j<i;j++)
                    {
                        Console.Write(i);
                    }
                    Console.WriteLine();
                }
</code>```

for Question 5 You Can Use Below Code This Definately works

```<code>            for (int i = 1; i <= 10; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    if (i >= j && i <= 5)
                    {
                        Console.Write("*");
                    }
                    else if (i > 5 && (i+j) <= 11)
                    {
                        Console.Write("*");
                    }

                }
                   Console.WriteLine();
            }
</code>```

Title: What does this exam paper C# code do?

Body:
I managed to figure out the code for question 4, but it looks wrong:

    private void button1_Click(object sender, EventArgs e)
    {
        string msg = "";
        int i = 1;

        while (i < 6)
        {
            int col = 0;
            while (col < i)
            {
                msg += i;
                col++;
            }
            msg += "\n";
            i++;
        }

        MessageBox.Show(msg);
    }

Is there a simpler way to do it by using for and if statements?

Also for question 5, I am completely lost.

Body:
for Question 4 you can try this simple code

                for (int i = 1; i <= 5; i++)
                {
                    for(int j=0;j<i;j++)
                    {
                        Console.Write(i);
                    }
                    Console.WriteLine();
                }

for Question 5 You Can Use Below Code This Definately works

            for (int i = 1; i <= 10; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    if (i >= j && i <= 5)
                    {
                        Console.Write("*");
                    }
                    else if (i > 5 && (i+j) <= 11)
                    {
                        Console.Write("*");
                    }

                }
                   Console.WriteLine();
            }


问:
umbraco razor - getting fields from content
I have a 6 items of the same content type "news", in each item I have a field newsIntro. I want to put the fields in specific pages on another page so I need to target a specific field so it may be newsIntro on node 1702. I have tried a few things like

@1720.newsIntro

how do I target a specific field

Thanks

答:
If the content item 1720 is a parent or ancestor of the page where you want to use the value, you can get it recursively like this:</p>

```<code>@Umbraco.Field("newsIntro", recursive: true)
</code>```

Body:
If the content item 1720 is a parent or ancestor of the page where you want to use the value, you can get it recursively like this:

@Umbraco.Field("newsIntro", recursive: true)


问:
Using RegEX To Prefix And Append In Notepad++
I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that:

```
wordone
wordtwo
wordthree
```

become

```
able:"wordone"
able:"wordtwo"
able:"wordthree"
```

How can I do this?

答:
Regular Expression that can be used:

```<code>Find: \w.+
Replace: able:"$&"
</code>```

As, $& will give you the string you search for.

Refer: regexr

ContentLicense: CC BY-SA 2.5

Body:
I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that:

wordone
wordtwo
wordthree

become

able:"wordone"
able:"wordtwo"
able:"wordthree"

How can I do this?

LastEditorDisplayName: Tomalak

Body:
Regular Expression that can be used:

Find: \w.+
Replace: able:"$&"

As, $& will give you the string you search for.

Refer: regexr


问:
I am trying to check runtime permissions by calling a class inside fragment. But onRequestPermissionsResult is not working inside fragment
I am trying to check runtime permissions inside a fragment by calling permissions class but in fragment overided  method to get result of permissions granted or not is not working in fragment

Here is method of class where i check or request permissions

```<code> public boolean checkPermissionForExternalStorage(){
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED){
            return true;
        } else {
            return false;
        }
    }

 public void requestPermissionForExternalStorage(){
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            Toast.makeText(activity, "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        }
    }
</code>```

Here is my Fragment

```<code>    package in.prsc.com.prscportal;

import android.Manifest;
import android.app.DownloadManager;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * Created by Bhuvan on 05-Aug-16.
 */
public class LEP extends Fragment {
    View myView;
    ProgressBar pb;
    WebView mWebView;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 1;
    public static int temp_perm;
    MarshmallowPermissions marshmallowPermissions;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
                uploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else
            Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.web_front, container, false);
        pb = (ProgressBar) myView.findViewById(R.id.progressBar);
        mWebView = (WebView) myView.findViewById(R.id.webview);

        marshmallowPermissions = new MarshmallowPermissions(getActivity());
        if (Build.VERSION.SDK_INT >= 23) {
            if (!marshmallowPermissions.checkPermissionForExternalStorage()) {
                marshmallowPermissions.requestPermissionForExternalStorage();
            }
        }

        return myView;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MarshmallowPermissions.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   // Here i have to do my code after permissions granted

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}
</code>```

答:
For Fragment, We have to pass Reference in Class
Create Constructor in MarshmallowPermissions Class

```<code>public MarshmallowPermissions(Context context, Fragment fragment) {

            Log.e(TAG, "MarshMallowPermission() called with: " + "context = [" + context + "], activity = [" + fragment + "]");
            this.fragment = fragment;
            this.context = context;
        }

public void requestPermissionForFragmentWriteExternalStorage() throws Exception {
        try {
            fragment.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

public boolean checkPermissionForWriteExternalStorage() {
            int result = context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (result == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                return false;
            }

        return false;
    }

 marshmallowPermissions = new MarshmallowPermissions(getActivity(),fragment);
</code>```

Body:
I am trying to check runtime permissions inside a fragment by calling permissions class but in fragment overided  method to get result of permissions granted or not is not working in fragment

Here is method of class where i check or request permissions

 public boolean checkPermissionForExternalStorage(){
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED){
            return true;
        } else {
            return false;
        }
    }

 public void requestPermissionForExternalStorage(){
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            Toast.makeText(activity, "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        }
    }

Here is my Fragment

    package in.prsc.com.prscportal;

import android.Manifest;
import android.app.DownloadManager;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * Created by Bhuvan on 05-Aug-16.
 */
public class LEP extends Fragment {
    View myView;
    ProgressBar pb;
    WebView mWebView;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 1;
    public static int temp_perm;
    MarshmallowPermissions marshmallowPermissions;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
                uploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else
            Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.web_front, container, false);
        pb = (ProgressBar) myView.findViewById(R.id.progressBar);
        mWebView = (WebView) myView.findViewById(R.id.webview);

        marshmallowPermissions = new MarshmallowPermissions(getActivity());
        if (Build.VERSION.SDK_INT >= 23) {
            if (!marshmallowPermissions.checkPermissionForExternalStorage()) {
                marshmallowPermissions.requestPermissionForExternalStorage();
            }
        }

        return myView;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MarshmallowPermissions.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   // Here i have to do my code after permissions granted

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

Body:
For Fragment, We have to pass Reference in Class
Create Constructor in MarshmallowPermissions Class

public MarshmallowPermissions(Context context, Fragment fragment) {

            Log.e(TAG, "MarshMallowPermission() called with: " + "context = [" + context + "], activity = [" + fragment + "]");
            this.fragment = fragment;
            this.context = context;
        }

public void requestPermissionForFragmentWriteExternalStorage() throws Exception {
        try {
            fragment.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

public boolean checkPermissionForWriteExternalStorage() {
            int result = context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (result == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                return false;
            }

        return false;
    }

 marshmallowPermissions = new MarshmallowPermissions(getActivity(),fragment);


问:
PHP: Pull all images from a specified directory using relative image path
I am trying to create a gallery where images are automatically pulled from a images directory.

When I foreach() each image it returns however it pulls the entire root path as the image src

/home/dev/public_html/assets/images/

this causes the images not to show and shows dead linked images on screen. I need the relative path like this:

/assets/images/imagename.jpg

How would I set a base path/URL?

```<code>$dirname = "/home/dev/public_html/assets/images/";

$images = glob($dirname."*.jpg");

foreach($images as $image) {
    echo '<img src="'.$image.'" /><br />';
}
</code>```

I tried setting $dirname to this

```<code>$dirname = "/assets/images/";
</code>```

But I get no result and nothing pulls through at all.

The file i am creating this in, is located outside the public_html folder, i believe this could be casing the issue but the file cannot be relocated.

答:
I would edit the loop in order to remove unnecessary string from path:</p>

```<code>foreach($images as $image) {
    $src = str_replace('/home/dev/public_html' ,'', $image) ;
    echo '<img src="'.$src.'" /><br />';
}
</code>```

Body:
I am trying to create a gallery where images are automatically pulled from a images directory.

When I foreach() each image it returns however it pulls the entire root path as the image src

/home/dev/public_html/assets/images/

this causes the images not to show and shows dead linked images on screen. I need the relative path like this:

/assets/images/imagename.jpg

How would I set a base path/URL?

$dirname = "/home/dev/public_html/assets/images/";

$images = glob($dirname."*.jpg");

foreach($images as $image) {
    echo '
';
}

I tried setting $dirname to this

$dirname = "/assets/images/";

But I get no result and nothing pulls through at all.

The file i am creating this in, is located outside the public_html folder, i believe this could be casing the issue but the file cannot be relocated.

Body:
I would edit the loop in order to remove unnecessary string from path:

foreach($images as $image) {
    $src = str_replace('/home/dev/public_html' ,'', $image) ;
    echo '<img src="'.$src.'" /><br />';
}


问:
Suitable technology for very small user base
My friend wants a way to organize her projects and tasks better at work.  She would like to be able to:

Define Projects

Define (Weekly) Tasks for each Project

A Task is associated with a particular week (day/time granularity not needed)

Define Sub-Tasks for each Task

View a week's worth of tasks and their subtasks at a time

Zoom in to see a particular task in more detail

Zoom out to see a whole month's tasks in less detail

And last, but not least, she would like to share this data with her supervisor, so he can see it and make comments / adjustments.

I'd like to know what options are available and the pros/cons of each...  I've considered:

Excel sheet

Pros: easy to share, availability (she and her boss both have Excel installed)

Cons: harder to maintain and create multiple views of the same data.

Access

Pros: easy to share (perhaps via storage on shared drive), availability

Cons: UI options not very rich, in my opinion

.NET with local db file

Pros: Rich UI options, quick development (i am most familiar with .NET)

Cons: Availability - they would both have to have my app installed, or it would have to live on a shared drive somewhere (which is probably an option I guess...)

Can anybody shed any light on this as far as available options, pros/cons I haven't thought of for these or any other technologies?

Thanks!

答: Excel is a great tool for this kind of thing. We use it in our development team for our iteration status. At least, when your sole user hits pain points, you'll see what your real pain points are before starting to code something in .NET/Ruby/Java/etc., and it will therefore serve as a useful prototype.</p>


问:
Error when running vagrant: "The host path of the shared folder is missing"
I have downloaded a Vagrantfile, but when i run vagrant up in terminal the following message appears:

Bringing machine 'default' up with 'virtualbox' provider... There are
  errors in the configuration of this machine. Please fix the following
  errors and try again:

vm:
  * The host path of the shared folder is missing: ~/Sync

OBS.: Using Ubuntu 14.10

I created a folder named Sync in my home.

答:
In my case it was a space at the end of the path in config.yaml:

```<code> source: '/Users/h/Packt/Code '
</code>```

I've deleted this space and it's working now.

Body:
In my case it was a space at the end of the path in config.yaml:

 source: '/Users/h/Packt/Code '

I've deleted this space and it's working now.

ContentLicense: CC BY-SA 4.0


问:
Trying to use node.js, keep getting errors
I installed node.js because I needed a way for storing my javascript variables into a mysql database (I use phpmyadmin).

I'm getting this error and I just don't now what to do with it:

```<code>C:\Users\Robin> npm install mysql
C:\Users\Robin
`-- mysql@2.13.0

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Robin\package.json'

npm WARN Robin No description

npm WARN Robin No repository field.

npm WARN Robin No README data

npm WARN Robin No license field.
</code>```

I also typed another command (can't remember which one) and it gave me a list of what looks like usernames and email-accounts.

I have no idea which steps I need to take for succesfully installing node.js and make it work. I checked youtube video's and stuff but there like worthless.

So my question from scrath is: I installed node.js, how to make it work?

Kind regards from the Netherlands

答:
You need have package.json file.
Do first:

```<code>npm init
</code>```

Then you will have package.json. Now you can do:

```<code>npm install package
</code>```

Or

```<code>npm install package --save (for save dependencies in package.json)
</code>```

EDIT:

Iam trying do npm intall in a void folder in my coputer:

```<code>diego.martin@csa-188:~/Proyectos/pruebas/prueba$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (prueba) Hello
Sorry, name can no longer contain capital letters.
name: (prueba) hello
version: (1.0.0)
description: None
entry point: (index.js)
test command:
git repository:
keywords:
author: Diego
license: (ISC)
About to write to /home/diego.martin/Proyectos/pruebas/prueba/package.json:

{
  "name": "hello",
  "version": "1.0.0",
  "description": "None",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Diego",
  "license": "ISC"
}

Is this ok? (yes) yes
</code>```

Then i have packaje.json:

```<code>diego.martin@csa-188:~/Proyectos/pruebas/prueba$ ls -la
total 12
drwxrwxr-x  2 diego.martin diego.martin 4096 jul  5 13:30 .
drwxr-xr-x 11 diego.martin diego.martin 4096 jul  5 13:25 ..
-rw-rw-r--  1 diego.martin diego.martin  210 jul  5 13:30 package.json
diego.martin@csa-188:~/Proyectos/pruebas/prueba$
</code>```

Lastest:

```<code>diego.martin@csa-188:~/Proyectos/pruebas/prueba$ npm install mysql --save
hello@1.0.0 /home/diego.martin/Proyectos/pruebas/prueba
└─┬ mysql@2.13.0
  ├── bignumber.js@3.1.2
  ├─┬ readable-stream@1.1.14
  │ ├── core-util-is@1.0.2
  │ ├── inherits@2.0.3
  │ ├── isarray@0.0.1
  │ └── string_decoder@0.10.31
  └── sqlstring@2.2.0

npm WARN hello@1.0.0 No repository field.
diego.martin@csa-188:~/Proyectos/pruebas/prueba$
</code>```

Body:
I installed node.js because I needed a way for storing my javascript variables into a mysql database (I use phpmyadmin).

I'm getting this error and I just don't now what to do with it:

C:\Users\Robin> npm install mysql
C:\Users\Robin
`-- mysql@2.13.0

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Robin\package.json'

npm WARN Robin No description

npm WARN Robin No repository field.

npm WARN Robin No README data

npm WARN Robin No license field.

I also typed another command (can't remember which one) and it gave me a list of what looks like usernames and email-accounts.

I have no idea which steps I need to take for succesfully installing node.js and make it work. I checked youtube video's and stuff but there like worthless.

So my question from scrath is: I installed node.js, how to make it work?

Kind regards from the Netherlands

Body:
You need have package.json file.
Do first:

npm init

Then you will have package.json. Now you can do:

npm install package

Or

npm install package --save (for save dependencies in package.json)

EDIT:

Iam trying do npm intall in a void folder in my coputer:

diego.martin@csa-188:~/Proyectos/pruebas/prueba$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (prueba) Hello
Sorry, name can no longer contain capital letters.
name: (prueba) hello
version: (1.0.0)
description: None
entry point: (index.js)
test command:
git repository:
keywords:
author: Diego
license: (ISC)
About to write to /home/diego.martin/Proyectos/pruebas/prueba/package.json:

{
  "name": "hello",
  "version": "1.0.0",
  "description": "None",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Diego",
  "license": "ISC"
}

Is this ok? (yes) yes

Then i have packaje.json:

diego.martin@csa-188:~/Proyectos/pruebas/prueba$ ls -la
total 12
drwxrwxr-x  2 diego.martin diego.martin 4096 jul  5 13:30 .
drwxr-xr-x 11 diego.martin diego.martin 4096 jul  5 13:25 ..
-rw-rw-r--  1 diego.martin diego.martin  210 jul  5 13:30 package.json
diego.martin@csa-188:~/Proyectos/pruebas/prueba$

Lastest:

diego.martin@csa-188:~/Proyectos/pruebas/prueba$ npm install mysql --save
hello@1.0.0 /home/diego.martin/Proyectos/pruebas/prueba
└─┬ mysql@2.13.0
  ├── bignumber.js@3.1.2
  ├─┬ readable-stream@1.1.14
  │ ├── core-util-is@1.0.2
  │ ├── inherits@2.0.3
  │ ├── isarray@0.0.1
  │ └── string_decoder@0.10.31
  └── sqlstring@2.2.0

npm WARN hello@1.0.0 No repository field.
diego.martin@csa-188:~/Proyectos/pruebas/prueba$


问:
Scrapy Start_url error
I am new to scrapy i am trying to scrape date from the pages of range(1,70000000)
the code I is used is </p>

```<code>import scrapy, json, re
from blackberry.items import BlackberryItem
class BlackSpider(scrapy.Spider):
    name = 'datas'
    start_urls = [
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' %page for page in xrange(1, 10000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%y for y in xrange(10000000, 20000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%a for a in xrange(20000000, 30000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%b for b in xrange(40000000, 50000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%c for c in xrange(50000000, 60000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%d for d in xrange(60000000, 70000000)
              ]
</code>```

<p>But i got this error : </p>

```<code>"y is not defined"
</code>```

答:
One of the possible solutions is as follow.</p>

```<code>import scrapy
import json
import re
from blackberry.items import BlackberryItem
class BlackSpider(scrapy.Spider):
    name = 'datas'
    start_urls = ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(10000000, 20000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(20000000, 30000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(30000000, 40000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(40000000, 50000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(50000000, 60000000)]
</code>```

Title: Scrapy Start_url error

Body:
I am new to scrapy i am trying to scrape date from the pages of range(1,70000000)
the code I is used is

import scrapy, json, re
from blackberry.items import BlackberryItem
class BlackSpider(scrapy.Spider):
    name = 'datas'
    start_urls = [
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' %page for page in xrange(1, 10000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%y for y in xrange(10000000, 20000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%a for a in xrange(20000000, 30000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%b for b in xrange(40000000, 50000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%c for c in xrange(50000000, 60000000),
              'https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482'%d for d in xrange(60000000, 70000000)
              ]

But i got this error :

"y is not defined"

Body:
One of the possible solutions is as follow.

import scrapy
import json
import re
from blackberry.items import BlackberryItem
class BlackSpider(scrapy.Spider):
    name = 'datas'
    start_urls = ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(10000000, 20000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(20000000, 30000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(30000000, 40000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(40000000, 50000000)]
    start_urls += ['https://appworld.blackberry.com/cas/content/%s?countryid=100&lang=en&callback=_content_2360&_=1499177414482' % page for page in xrange(50000000, 60000000)]


问:
Calculation on Datagridview?
This is some data on my datagridview and a data is just like this

```<code>column a | column b
1             0
2          is = 2-1
3          is = 3-2
4          is = 4-3
</code>```

So,I want to know how to calculate in column a and show the answer in column b.

答:
Try this:</p>

```<code>        private void button1_Click(object sender, EventArgs e)
    {
        //skip last emtpy line(if don't have, remove -1)
        for (int i = 1; i < dataGridView1.Rows.Count - 1; i++)
        {
            int valueCellIndex = 0;//assume calculate the 0th column
            int resultCellIndex = 1;//assume result to put into the 1th column
            //assume values are integers
            var lastRow = dataGridView1.Rows[i - 1];
            var curRow = dataGridView1.Rows[i];
            int last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
            int cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);
            curRow.Cells[resultCellIndex].Value = cur - last;
        }
    }
</code>```

Title: Calculation on Datagridview?

Body:
This is some data on my datagridview and a data is just like this

column a | column b
1             0
2          is = 2-1
3          is = 3-2
4          is = 4-3

So,I want to know how to calculate in column a and show the answer in column b.

Body:
Try this:

        private void button1_Click(object sender, EventArgs e)
    {
        //skip last emtpy line(if don't have, remove -1)
        for (int i = 1; i < dataGridView1.Rows.Count - 1; i++)
        {
            int valueCellIndex = 0;//assume calculate the 0th column
            int resultCellIndex = 1;//assume result to put into the 1th column
            //assume values are integers
            var lastRow = dataGridView1.Rows[i - 1];
            var curRow = dataGridView1.Rows[i];
            int last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
            int cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);
            curRow.Cells[resultCellIndex].Value = cur - last;
        }
    }


问:
Obj-C - POST JSON data to server?
Sorry for the newb question, but I am tearing my hair out over this one. I can successfully POST data to my endpoint URL via a program like FireFox's POSTER. However, I'm trying to post that same JSON data from my app to my endpoint URL (Drupal services push_notifications end point), and for some reason it will not POST successfully. Here is the code that I'm using:

ViewController.m

```<code>NSString *urlString1 = @"http://app.com/endpoint001/push_notifications";
 NSDictionary *jsonBodyDict = @{@"token":postDeviceID, @"type":@"ios"};
 NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
 // watch out: error is nil here, but you never do that in production code. Do proper checks!

 NSString *urlString2 = [NSString stringWithFormat:@"http://app.com/endpoint001/push_notifications?token=%@&type=%@",
                         postDeviceID,@"ios"];

 NSMutableURLRequest *request = [NSMutableURLRequest new];
 request.HTTPMethod = @"POST";

 // for alternative 1:
 [request setURL:[NSURL URLWithString:urlString1]];
 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 [request setHTTPBody:jsonBodyData];
 [request addValue:csrfToken forHTTPHeaderField:@"X-CSRF-Token"];

 // for alternative 2:
 [request setURL:[NSURL URLWithString:urlString2]];
 // no body needed, though that ultimately depends on your server. Also, I didn't test this for lack of a backend :)

 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
 NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                       delegate:nil
                                                  delegateQueue:[NSOperationQueue mainQueue]];
 NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:^(NSData * _Nullable data,
                                                             NSURLResponse * _Nullable response,
                                                             NSError * _Nullable error) {
                                             NSLog(@"Yay, done! Check for errors in response!");

                                             NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                             NSLog(@"The response is: %@", asHTTPResponse);
                                             // set a breakpoint on the last NSLog and investigate the response in the debugger

                                             // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                             NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];
                                             // or
                                             NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];

                                             NSLog(@"One of these might exist - object: %@ \n array: %@", forJSONObject, forJSONArray);

                                         }];
 [task resume];
</code>```

Note: I've put this code in AFTER my user already successfully logs in, so I'm not sure starting a whole new connection is necessary? How can I POST my data to the server if a session and CSRF Token already exists? What should my code look like? Whoever answers this question is going on my Christmas list... O_O

NSLog Response:

```<code>2017-07-17 17:31:11.421281-0700 app[977:206852] Yay, done! Check for errors in response!
2017-07-17 17:31:11.422198-0700 app[977:206852] The response is: <NSHTTPURLResponse: 0x170239b40> { URL: http://app.com/endpoint001/push_notifications?token=9526687d594944513b0wabf704eae3223f0de9bf69136a0aae3ab046863474b1&type=ios } { status code: 401, headers {
    "Cache-Control" = "no-cache, must-revalidate";
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Tue, 18 Jul 2017 00:14:35 GMT";
    Expires = "Sun, 19 Nov 1978 05:00:00 GMT";
    Server = Apache;
    "Transfer-Encoding" = Identity;
    Vary = Accept;
    "X-Content-Type-Options" = nosniff;
} }
2017-07-17 17:31:27.172085-0700 app[977:207024] XPC connection interrupted
2017-07-17 17:31:27.172311-0700 app[977:206852] One of these might exist - object: (
    "CSRF validation failed"
)
 array: (
    "CSRF validation failed"
)
</code>```

答:
tom's answer gives the right direction, but I see the lack of description what the code actually does is confusing to you. Also, you're using deprecated methods (of NSURLConnection), so I've made a quick (untested) example using NSURLSession and its related classes. Don't worry, it is basically the same.

That being said, the way you try this in your original code makes me wonder whether you're actually really sending a json body (i.e. your backend expects that) or rather the system relies on boring parameters to the URL. So I added both ways in my code:

```<code>NSString *postDeviceID = @"something";

NSString *urlString1 = @"http://myurl.com/endpoint01/push_notifications";
NSDictionary *jsonBodyDict = @{@"token":postDeviceID, @"type":@"ios"};
NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
// watch out: error is nil here, but you never do that in production code. Do proper checks!

NSString *urlString2 = [NSString stringWithFormat:@"http://myurl.com/endpoint01/push_notifications?token=%@&type=%@",
                        postDeviceID,@"ios"];

NSMutableURLRequest *request = [NSMutableURLRequest new];
request.HTTPMethod = @"POST";

// for alternative 1:
[request setURL:[NSURL URLWithString:urlString1]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonBodyData];

// for alternative 2:
[request setURL:[NSURL URLWithString:urlString2]];
// no body needed, though that ultimately depends on your server. Also, I didn't test this for lack of a backend :)

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                      delegate:nil
                                                 delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData * _Nullable data,
                                                            NSURLResponse * _Nullable response,
                                                            NSError * _Nullable error) {
                                            NSLog(@"Yay, done! Check for errors in response!");

                                            NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                            NSLog(@"The response is: %@", asHTTPResponse);
                                            // set a breakpoint on the last NSLog and investigate the response in the debugger

                                            // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                            NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];
                                            // or
                                            NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];

                                            NSLog(@"One of these might exist - object: %@ \n array: %@", forJSONObject, forJSONArray);

                                        }];
[task resume];
</code>```

It is also possible your backend supports both ways, but learning how to construct a proper json body is always helpful.
Note that the reason why tom's code makes you think it posted is that you seem to misunderstand how NSURLConnection works (unless you excluded code you rely on): The object is always constructed the way you're using it, so if (conn) is always in the YES branch. That doesn't mean the connection, i.e. the actual loading succeeds. The initializer returns nil if it can't create an instance, not if a valid instance simply relies on data that is refused on connecting to its target. You don't get an error for that in this way (you need to rely on delegation for this).

The session approach I showed gives you a completion block in which you can investigate what the server responds to track down further what went wrong. You can just set a breakpoint there and look at the error (which is nil if it succeeds), the status in the response etc.

I obviously didn't run this exact code, so excuse any typos, but I have used this approach a lot with loading from and sending to a variety of backends for my usual work. In general it should work (and, more importantly, allow you to figure out what the heck your backend expects, assuming you don't have detailed docs about it).

Edit:

Okay, that hint in the code comment was maybe misleading: I meant to check the response for errors. The response object (also see the documentation for the dataTask... method in general). I added code helping a bit with that, but please be aware that the conversion of the data object into JSON depends on what and if your server actually passes any data at all. Or it might have a weird format or something, you need to figure this out. For simple stuff that gets POSTed, it might not provide any data, you simply get an according information about whether it worked or not in the response. Note especially NSHTTPURLResponse's statusCode property. Unless your server does something weird, that's the HTTP status code defined by the standard and should help you out. If, for example, the way in which you constructed your body in the request (the jsonBodyDict in my example code) was wrong (wrong element names or the like) you would get a 400.

In general you have to understand that the meaning of "error" is not that simple here. The methods consider not being able to connect at all as an error, so you get an error object in the completion block in these cases. This is typically the case when your server simply doesn't exist or the like. If, however, you simply fail to communicate your intended information to your server, that's not an error from the API's perspective and you don't get an error object. You get a valid response that says "this request was erroneous". You're doing good already in your case, as the connection seems to happen and work, you're just not yet sending the data your server expects. The response should give more info on that.

To further debug this would go beyond the scope of this question even more, because ultimately we're talking about how your specific backend behaves now. If you can't figure that out, you'd need to give me the credentials for your server so I can test it myself, everything else would be guessing on my part now. :) We can do that, but it's probably best to do so in chat and not in a question/answer that's already that long, hehe.

Title: Obj-C - POST JSON data to server?

Body:
Sorry for the newb question, but I am tearing my hair out over this one. I can successfully POST data to my endpoint URL via a program like FireFox's POSTER. However, I'm trying to post that same JSON data from my app to my endpoint URL (Drupal services push_notifications end point), and for some reason it will not POST successfully. Here is the code that I'm using:

ViewController.m

NSString *urlString1 = @"http://app.com/endpoint001/push_notifications";
 NSDictionary *jsonBodyDict = @{@"token":postDeviceID, @"type":@"ios"};
 NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
 // watch out: error is nil here, but you never do that in production code. Do proper checks!

 NSString *urlString2 = [NSString stringWithFormat:@"http://app.com/endpoint001/push_notifications?token=%@&type=%@",
                         postDeviceID,@"ios"];

 NSMutableURLRequest *request = [NSMutableURLRequest new];
 request.HTTPMethod = @"POST";

 // for alternative 1:
 [request setURL:[NSURL URLWithString:urlString1]];
 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 [request setHTTPBody:jsonBodyData];
 [request addValue:csrfToken forHTTPHeaderField:@"X-CSRF-Token"];

 // for alternative 2:
 [request setURL:[NSURL URLWithString:urlString2]];
 // no body needed, though that ultimately depends on your server. Also, I didn't test this for lack of a backend :)

 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
 NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                       delegate:nil
                                                  delegateQueue:[NSOperationQueue mainQueue]];
 NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:^(NSData * _Nullable data,
                                                             NSURLResponse * _Nullable response,
                                                             NSError * _Nullable error) {
                                             NSLog(@"Yay, done! Check for errors in response!");

                                             NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                             NSLog(@"The response is: %@", asHTTPResponse);
                                             // set a breakpoint on the last NSLog and investigate the response in the debugger

                                             // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                             NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];
                                             // or
                                             NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];

                                             NSLog(@"One of these might exist - object: %@ \n array: %@", forJSONObject, forJSONArray);

                                         }];
 [task resume];

Note: I've put this code in AFTER my user already successfully logs in, so I'm not sure starting a whole new connection is necessary? How can I POST my data to the server if a session and CSRF Token already exists? What should my code look like? Whoever answers this question is going on my Christmas list... O_O

NSLog Response:

2017-07-17 17:31:11.421281-0700 app[977:206852] Yay, done! Check for errors in response!
2017-07-17 17:31:11.422198-0700 app[977:206852] The response is: <NSHTTPURLResponse: 0x170239b40> { URL: http://app.com/endpoint001/push_notifications?token=9526687d594944513b0wabf704eae3223f0de9bf69136a0aae3ab046863474b1&type=ios } { status code: 401, headers {
    "Cache-Control" = "no-cache, must-revalidate";
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Tue, 18 Jul 2017 00:14:35 GMT";
    Expires = "Sun, 19 Nov 1978 05:00:00 GMT";
    Server = Apache;
    "Transfer-Encoding" = Identity;
    Vary = Accept;
    "X-Content-Type-Options" = nosniff;
} }
2017-07-17 17:31:27.172085-0700 app[977:207024] XPC connection interrupted
2017-07-17 17:31:27.172311-0700 app[977:206852] One of these might exist - object: (
    "CSRF validation failed"
)
 array: (
    "CSRF validation failed"
)

Body:
tom's answer gives the right direction, but I see the lack of description what the code actually does is confusing to you. Also, you're using deprecated methods (of NSURLConnection), so I've made a quick (untested) example using NSURLSession and its related classes. Don't worry, it is basically the same.

That being said, the way you try this in your original code makes me wonder whether you're actually really sending a json body (i.e. your backend expects that) or rather the system relies on boring parameters to the URL. So I added both ways in my code:

NSString *postDeviceID = @"something";

NSString *urlString1 = @"http://myurl.com/endpoint01/push_notifications";
NSDictionary *jsonBodyDict = @{@"token":postDeviceID, @"type":@"ios"};
NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
// watch out: error is nil here, but you never do that in production code. Do proper checks!

NSString *urlString2 = [NSString stringWithFormat:@"http://myurl.com/endpoint01/push_notifications?token=%@&type=%@",
                        postDeviceID,@"ios"];

NSMutableURLRequest *request = [NSMutableURLRequest new];
request.HTTPMethod = @"POST";

// for alternative 1:
[request setURL:[NSURL URLWithString:urlString1]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonBodyData];

// for alternative 2:
[request setURL:[NSURL URLWithString:urlString2]];
// no body needed, though that ultimately depends on your server. Also, I didn't test this for lack of a backend :)

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                      delegate:nil
                                                 delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData * _Nullable data,
                                                            NSURLResponse * _Nullable response,
                                                            NSError * _Nullable error) {
                                            NSLog(@"Yay, done! Check for errors in response!");

                                            NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                            NSLog(@"The response is: %@", asHTTPResponse);
                                            // set a breakpoint on the last NSLog and investigate the response in the debugger

                                            // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                            NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];
                                            // or
                                            NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];

                                            NSLog(@"One of these might exist - object: %@ \n array: %@", forJSONObject, forJSONArray);

                                        }];
[task resume];

It is also possible your backend supports both ways, but learning how to construct a proper json body is always helpful.
Note that the reason why tom's code makes you think it posted is that you seem to misunderstand how NSURLConnection works (unless you excluded code you rely on): The object is always constructed the way you're using it, so if (conn) is always in the YES branch. That doesn't mean the connection, i.e. the actual loading succeeds. The initializer returns nil if it can't create an instance, not if a valid instance simply relies on data that is refused on connecting to its target. You don't get an error for that in this way (you need to rely on delegation for this).

The session approach I showed gives you a completion block in which you can investigate what the server responds to track down further what went wrong. You can just set a breakpoint there and look at the error (which is nil if it succeeds), the status in the response etc.

I obviously didn't run this exact code, so excuse any typos, but I have used this approach a lot with loading from and sending to a variety of backends for my usual work. In general it should work (and, more importantly, allow you to figure out what the heck your backend expects, assuming you don't have detailed docs about it).

Edit:

Okay, that hint in the code comment was maybe misleading: I meant to check the response for errors. The response object (also see the documentation for the dataTask... method in general). I added code helping a bit with that, but please be aware that the conversion of the data object into JSON depends on what and if your server actually passes any data at all. Or it might have a weird format or something, you need to figure this out. For simple stuff that gets POSTed, it might not provide any data, you simply get an according information about whether it worked or not in the response. Note especially NSHTTPURLResponse's statusCode property. Unless your server does something weird, that's the HTTP status code defined by the standard and should help you out. If, for example, the way in which you constructed your body in the request (the jsonBodyDict in my example code) was wrong (wrong element names or the like) you would get a 400.

In general you have to understand that the meaning of "error" is not that simple here. The methods consider not being able to connect at all as an error, so you get an error object in the completion block in these cases. This is typically the case when your server simply doesn't exist or the like. If, however, you simply fail to communicate your intended information to your server, that's not an error from the API's perspective and you don't get an error object. You get a valid response that says "this request was erroneous". You're doing good already in your case, as the connection seems to happen and work, you're just not yet sending the data your server expects. The response should give more info on that.

To further debug this would go beyond the scope of this question even more, because ultimately we're talking about how your specific backend behaves now. If you can't figure that out, you'd need to give me the credentials for your server so I can test it myself, everything else would be guessing on my part now. :) We can do that, but it's probably best to do so in chat and not in a question/answer that's already that long, hehe.


问:
Sidenav mode 'over' vs 'side' in Material 2 with angular 4
I want the mode for sidenav to toogle between over and side depending on the screen size.

I found below example, but the component media seems to be deprecated for material. What is best practice?

```<code>constructor(public sidenav: SidenavService,
            public media: Media) {
}

hasMedia(breakSize: string): boolean {
    return this.media.hasMedia(breakSize);
}
</code>```

答:
I found the solution by ObservableMedia, but the code could probably be better:

Component:

```<code>import {Component, OnInit, ViewEncapsulation} from "@angular/core";
import {ObservableMedia} from "@angular/flex-layout";

@Component({
  moduleId: module.id,
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class SidebarComponent implements OnInit {

  constructor(public media:ObservableMedia ) {
  }

  ngOnInit(): void {
  }

}
</code>```

template:

```<code><md-sidenav-container>
    <md-sidenav #sidenav  mode="{{media.isActive('gt-sm') ? 'side' : 'over'}}" align="begin" class="md-whiteframe-4dp" opened >
      <md-nav-list>
        ...
      </md-nav-list>
    </md-sidenav>

</md-sidenav-container>
</code>```

Body:
I want the mode for sidenav to toogle between over and side depending on the screen size.

I found below example, but the component media seems to be deprecated for material. What is best practice?

constructor(public sidenav: SidenavService,
            public media: Media) {
}

hasMedia(breakSize: string): boolean {
    return this.media.hasMedia(breakSize);
}

Body:
I found the solution by ObservableMedia, but the code could probably be better:

Component:

import {Component, OnInit, ViewEncapsulation} from "@angular/core";
import {ObservableMedia} from "@angular/flex-layout";

@Component({
  moduleId: module.id,
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class SidebarComponent implements OnInit {

  constructor(public media:ObservableMedia ) {
  }

  ngOnInit(): void {
  }

}

template:

<md-sidenav-container>
    <md-sidenav #sidenav  mode="{{media.isActive('gt-sm') ? 'side' : 'over'}}" align="begin" class="md-whiteframe-4dp" opened >
      <md-nav-list>
        ...
      </md-nav-list>
    </md-sidenav>

</md-sidenav-container>


问:
Finding minimum positive value and its position in each column of a matrix
I need to find the minimum positive values in each column and its position inside the column of a certain matrix. So if I have:

```<code>A = [1 4
     2 3
     3 6]
</code>```

I need to obtain the values 1 and 3, and the positions 1 and 2. Doing this inside a for loop I obtain correctly the minimum values and its position, but it also catches the negative values:

```<code>for bit = 1:2
    [y(bit),x(bit)] = min(A(:,bit));
end
</code>```

And if I use:

```<code>[y(bit),x(bit)] = min(A(A(:,bit)>0));
</code>```

I don't receive the expected result. What I'm doing wrong? Thanks.

答:
This can be easily achieved using inf and min...

New method using inf and no looping

Take some random example:

```<code>% Generated using A = randi([-100, 100], 10, 3)
A = [ 31    41   -12
     -93   -94   -24
      70   -45    53
      87   -91    59
      36   -81   -63
      52    65    -2
      49    39   -11
     -22   -37    29
      31    90    42
     -66   -94    51];
</code>```

Set all negative values to positive infinity, which will ensure they are never the minimum value in the column.

```<code>A(A<=0) = inf;
% if you want to preserve A, use A2=A; A2(A<=0)=inf;
</code>```

Now you can just use the min function as expected.

```<code>[mins, idx] = min(A);
% mins = 31, 39, 29: as expected
% idx  = 1, 7, 8: the indices of the above values in each column as expected.
</code>```

By default, min will get the column-wise minimum as you want.
To specify this explicitly, use min(A,[],1), see the documentation for more details.

Note that you could achieve the same result by using NaN instead of inf.

Your method

In response to why you were getting an unexpected result, it's because you weren't selecting the column of A in your loop, the second attempt should be corrected to

```<code>[y(bit),x(bit)] = min(A(A(:,bit)>0, bit));
</code>```

However, this will still give an unexpected result! The minimums will be correct, but their indices will be lower than expected. This is because the indices will only count the positive values in each column, so you will get the nth positive number rather than the nth number. The easiest "workaround" is to abandon this method and use the quicker one above which doesn't require looping.

Body:
I need to find the minimum positive values in each column and its position inside the column of a certain matrix. So if I have:

A = [1 4
     2 3
     3 6]

I need to obtain the values 1 and 3, and the positions 1 and 2. Doing this inside a for loop I obtain correctly the minimum values and its position, but it also catches the negative values:

for bit = 1:2
    [y(bit),x(bit)] = min(A(:,bit));
end

And if I use:

[y(bit),x(bit)] = min(A(A(:,bit)>0));

I don't receive the expected result. What I'm doing wrong? Thanks.

Body:
This can be easily achieved using inf and min...

New method using inf and no looping

Take some random example:

% Generated using A = randi([-100, 100], 10, 3)
A = [ 31    41   -12
     -93   -94   -24
      70   -45    53
      87   -91    59
      36   -81   -63
      52    65    -2
      49    39   -11
     -22   -37    29
      31    90    42
     -66   -94    51];

Set all negative values to positive infinity, which will ensure they are never the minimum value in the column.

A(A<=0) = inf;
% if you want to preserve A, use A2=A; A2(A<=0)=inf;

Now you can just use the min function as expected.

[mins, idx] = min(A);
% mins = 31, 39, 29: as expected
% idx  = 1, 7, 8: the indices of the above values in each column as expected.

By default, min will get the column-wise minimum as you want.
To specify this explicitly, use min(A,[],1), see the documentation for more details.

Note that you could achieve the same result by using NaN instead of inf.

Your method

In response to why you were getting an unexpected result, it's because you weren't selecting the column of A in your loop, the second attempt should be corrected to

[y(bit),x(bit)] = min(A(A(:,bit)>0, bit));

However, this will still give an unexpected result! The minimums will be correct, but their indices will be lower than expected. This is because the indices will only count the positive values in each column, so you will get the nth positive number rather than the nth number. The easiest "workaround" is to abandon this method and use the quicker one above which doesn't require looping.


问:
Preloaded SQLite local DB in Swift
Problem

I wanna use SQLite.swift framework on my project to access my local preloaded (read-only) database file (db.sqlite3) which located in my current project directory. I created my db connection as let db = try? Connection("path/to/db.sqlite3") First question is when I keep my db in my project directory can I involve connection path as Connection("path/to/db.sqlite3") or Connection("db.sqlite3")? (What's the meaning of path/to of course, I'm wondering) Anyway, my main question is how can I query my local db? What's wrong?

Here is my code but it doesn't work. This code mostly similar to SQLite.swift's github documantion page but it doesn't work in Swift 2.2

```<code>    override func viewDidLoad() {
    super.viewDidLoad()
    let db = try? Connection("path/to/db.sqlite3")

    let users = Table("users")

    for user in try! db!.prepare(users) {
        print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
        // id: 1, name: Optional("Alice"), email: alice@mac.com
    }

    // Do any additional setup after loading the view.
}
</code>```

I have already copied my db files to Copy Bundle Resources (Build Phrase)

My working directory

Error

Note: I tried db connection as "path/to/db.sqlite3" and "db.sqlite3". So, this is not the solution.

答:
Converted in Swift 3.0

```<code>let path = Bundle.main.path(forResource: "SMP", ofType: "sqlite")!
let db = try? Connection(path)
</code>```

// Insert Rows ======

```<code>let stmt = try! db!.prepare("INSERT INTO tbl_workout (name) VALUES (?)")
for name in ["Workout1", "Workout2"] {
       try! stmt.run(name)
}
</code>```

// Fetch Rows ======

```<code>for row in try! db!.prepare("SELECT * FROM tbl_workout") {
    print("id: \(String(describing: row[0])), email: \(String(describing: row[1]))")
}
</code>```

Title: Preloaded SQLite local DB in Swift

Body:
Problem

I wanna use SQLite.swift framework on my project to access my local preloaded (read-only) database file (db.sqlite3) which located in my current project directory. I created my db connection as let db = try? Connection("path/to/db.sqlite3") First question is when I keep my db in my project directory can I involve connection path as Connection("path/to/db.sqlite3") or Connection("db.sqlite3")? (What's the meaning of path/to of course, I'm wondering) Anyway, my main question is how can I query my local db? What's wrong?

Here is my code but it doesn't work. This code mostly similar to SQLite.swift's github documantion page but it doesn't work in Swift 2.2

    override func viewDidLoad() {
    super.viewDidLoad()
    let db = try? Connection("path/to/db.sqlite3")

    let users = Table("users")

    for user in try! db!.prepare(users) {
        print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
        // id: 1, name: Optional("Alice"), email: alice@mac.com
    }

    // Do any additional setup after loading the view.
}

I have already copied my db files to Copy Bundle Resources (Build Phrase)

My working directory

Error

Note: I tried db connection as "path/to/db.sqlite3" and "db.sqlite3". So, this is not the solution.

Body:
Converted in Swift 3.0

let path = Bundle.main.path(forResource: "SMP", ofType: "sqlite")!
let db = try? Connection(path)

// Insert Rows ======

let stmt = try! db!.prepare("INSERT INTO tbl_workout (name) VALUES (?)")
for name in ["Workout1", "Workout2"] {
       try! stmt.run(name)
}

// Fetch Rows ======

for row in try! db!.prepare("SELECT * FROM tbl_workout") {
    print("id: \(String(describing: row[0])), email: \(String(describing: row[1]))")
}


问:
Adding not validated dictionary with python eve along with an image
I want to import images in mongoDB along with any dictionary. The dictionary should provide image tags, of which types, numbers and names I can't know at the moment I define the schema.
I'm trying to add a dictionary in eve without success:

```<code>curl -F"attr={\"a\":1}"  -F "img_id=2asdasdasd" -F "img_data=@c:\path\
1.png;type=image/png" http://127.0.0.1:5000/images
{"_status": "ERR", "_issues": {"attr": "must be of dict type"}, "_error": {"message": "Insertion failure: 1 document(s)
contain(s) error(s)", "code": 422}}
</code>```

My schema definition looks like that:

```<code>'schema': {
    #Fixed attributes
        'original_name': {
            'type': 'string',
            'minlength': 4,
            'maxlength': 1000,
        },
        'img_id': {
            'type': 'string',
            'minlength': 4,
            'maxlength': 150,
            'required': True,

            'unique': True,
        },
        'img_data': {
            'type': 'media'
        },
    #Additional attributes
        'attr': {
            'type': 'dict'

        }
    }
</code>```

Is it possible at all? Should the schema for dicts be fixed?

EDIT
I wanted to add image first and the dictionary after it, but get an error in PATCH request:

```<code>C:\Windows\SysWOW64>curl -X PATCH -i  -H "Content-Type: application/json" -d "{\
"img_id\":\"asdasdasd\", \"attr\": {\"a\": 1}}" http://localhost:5000/images/asd
asdasd
HTTP/1.0 405 METHOD NOT ALLOWED
Content-Type: application/json
Content-Length: 106
Server: Eve/0.7.4 Werkzeug/0.9.4 Python/2.7.3
Date: Wed, 28 Jun 2017 22:55:54 GMT

{"_status": "ERR", "_error": {"message": "The method is not allowed for the requested URL.", "code": 405}}
</code>```

答:
I have posted an issue on Github for the same situation. However I have came with a workaround.

Override the dict validator:

```<code>class JsonValidator(Validator):

    def _validate_type_dict(self, field, value):
        if type(value) is dict:
            pass
        try:
            json.loads(value)
        except:
            self._error(value, "Invalid JSON")

app = Eve(validator=JsonValidator)
</code>```

Next, add an insert hook:

```<code>def multi_request_json_parser(documents):
    for item in documents:
        if 'my_json_field' in item.keys():
            item['my_json_field'] = json.loads(item['my_json_field'])

app.on_insert_myendpoint += multi_request_json_parser
</code>```

The dict validator must be overidden, because else the insert hook will not be called due to an validation error.

Body:
I want to import images in mongoDB along with any dictionary. The dictionary should provide image tags, of which types, numbers and names I can't know at the moment I define the schema.
I'm trying to add a dictionary in eve without success:

curl -F"attr={\"a\":1}"  -F "img_id=2asdasdasd" -F "img_data=@c:\path\
1.png;type=image/png" http://127.0.0.1:5000/images
{"_status": "ERR", "_issues": {"attr": "must be of dict type"}, "_error": {"message": "Insertion failure: 1 document(s)
contain(s) error(s)", "code": 422}}

My schema definition looks like that:

'schema': {
    #Fixed attributes
        'original_name': {
            'type': 'string',
            'minlength': 4,
            'maxlength': 1000,
        },
        'img_id': {
            'type': 'string',
            'minlength': 4,
            'maxlength': 150,
            'required': True,

            'unique': True,
        },
        'img_data': {
            'type': 'media'
        },
    #Additional attributes
        'attr': {
            'type': 'dict'

        }
    }

Is it possible at all? Should the schema for dicts be fixed?

EDIT
I wanted to add image first and the dictionary after it, but get an error in PATCH request:

C:\Windows\SysWOW64>curl -X PATCH -i  -H "Content-Type: application/json" -d "{\
"img_id\":\"asdasdasd\", \"attr\": {\"a\": 1}}" http://localhost:5000/images/asd
asdasd
HTTP/1.0 405 METHOD NOT ALLOWED
Content-Type: application/json
Content-Length: 106
Server: Eve/0.7.4 Werkzeug/0.9.4 Python/2.7.3
Date: Wed, 28 Jun 2017 22:55:54 GMT

{"_status": "ERR", "_error": {"message": "The method is not allowed for the requested URL.", "code": 405}}

Body:
I have posted an issue on Github for the same situation. However I have came with a workaround.

Override the dict validator:

class JsonValidator(Validator):

    def _validate_type_dict(self, field, value):
        if type(value) is dict:
            pass
        try:
            json.loads(value)
        except:
            self._error(value, "Invalid JSON")

app = Eve(validator=JsonValidator)

Next, add an insert hook:

def multi_request_json_parser(documents):
    for item in documents:
        if 'my_json_field' in item.keys():
            item['my_json_field'] = json.loads(item['my_json_field'])

app.on_insert_myendpoint += multi_request_json_parser

The dict validator must be overidden, because else the insert hook will not be called due to an validation error.


问:
How to create hyperlink in  cell of JQuery datatable that does not conflict with alphabet search plugin?
I'm using jQuery datatables with the Alphabetical Search plugin.

Alphabet search won't work if I keep any html code between  and 	 .

I wanted to create hyperlink for every cell to a different html page,
so I did this:

```<code><td>
<a href="demo.html" class="myclass" width="100%">demo </a>
</td>
</code>```

Alphabet search stopped working..
How to fix this please?

答:
You can try using Javascript. The code should be similar to the snippet

function gotoURL(theURL){
  window.location.href = theURL;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table><tr><td onclick="gotoURL('https://stackoverflow.com/');">demo
</td></tr></table></code>```

Title: How to create hyperlink in <td> cell of JQuery datatable that does not conflict with alphabet search plugin?

Body:
I'm using jQuery datatables with the Alphabetical Search plugin.

Alphabet search won't work if I keep any html code between  and 	 .

I wanted to create hyperlink for every cell to a different html page,
so I did this:

demo

Alphabet search stopped working..
How to fix this please?

Body:
You can try using Javascript. The code should be similar to the snippet

function gotoURL(theURL){
  window.location.href = theURL;
}

<table><tr><td onclick="gotoURL('https://stackoverflow.com/');">demo
</td></tr></table>


问:
HSQL query using limit in join part
I'm new in Spring Boot. I tried to find an answer for my question on SO and google, but I can't find an exact answer for it.

I'm trying to create a function in my Spring Boot JpaRepository class which returns a Customer by id with a limited number of ascending ordered AccountingLogs related to the Customer.

My line of code in JpaRepository:

```<code>@Query("select c from Customer left outer join AccountingLog a on a.customer.id = c.id where c.id= :id")
Customer getWithLimitedNumberOfLastTransactions(@Param("id") Long id, @Param("limit") int limit);
</code>```

The Customer class only with the relevant code:

```<code>@Entity
public class Customer {
    //...
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @Column(nullable = true)
    @JsonManagedReference
    private Set<AccountingLog> accountingLogs;
    //...
}
</code>```

The customer class only with the relevant code:

```<code>@Entity
public class AccountingLog {
    //...
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "customer_id")
    @JsonBackReference
    private Customer customer;
    //...
}
</code>```

So I'm looking for an HSQL query which selects one customer by id with a specified number (variable named limit) of accounting logs in ascending order (last in first) related to the customer.

Thank you for your help!

答:
You can write a native query in @Query if you are using MySql:

@Query(value="select c from Customer left outer join AccountingLog a on a.customer.id = c.id where c.id= :id limit :limit", nativeQuery = true)

or Oracle:

@Query(value="select c from Customer left outer join AccountingLog a on a.customer.id = c.id where c.id= :id and ROWNUM < :limit", nativeQuery = true)

Title: HSQL query using limit in join part

Body:
I'm new in Spring Boot. I tried to find an answer for my question on SO and google, but I can't find an exact answer for it.

I'm trying to create a function in my Spring Boot JpaRepository class which returns a Customer by id with a limited number of ascending ordered AccountingLogs related to the Customer.

My line of code in JpaRepository:

@Query("select c from Customer left outer join AccountingLog a on a.customer.id = c.id where c.id= :id")
Customer getWithLimitedNumberOfLastTransactions(@Param("id") Long id, @Param("limit") int limit);

The Customer class only with the relevant code:

@Entity
public class Customer {
    //...
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @Column(nullable = true)
    @JsonManagedReference
    private Set<AccountingLog> accountingLogs;
    //...
}

The customer class only with the relevant code:

@Entity
public class AccountingLog {
    //...
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "customer_id")
    @JsonBackReference
    private Customer customer;
    //...
}

So I'm looking for an HSQL query which selects one customer by id with a specified number (variable named limit) of accounting logs in ascending order (last in first) related to the customer.

Thank you for your help!