问:
Python Checker: TypeError: list indices must be integers, not str
I am really confused as to why I keep on getting this Error,

```<code>password_strength['has_upper'] = False
TypeError: list indices must be integers, not str
</code>```

,because I have been changing the code around and I still don't understand. I am trying to make a python password checker and I've looked at all other questions and none of them have helped me.

The code is:

```<code>def Check():#menu function. Checks a password
global score
print ('Enter a password')
score = 0#sets the score to zero

while True:
    password = input('Password: ... ')
    if 7 <= len(password) < 24:
        break
    else:
        print ('The password must be between 8 and 24 characters.')

password_scores = {0:'Horrible', 5:'Weak', 10:'Medium', 15:'Strong'}#Choses the strength
password_strength = ['has_upper', 'has_lower', 'has_num']

if re.search(r'[A-Z]', password):
    password_strength['has_upper'] = True#checks if the password has a capital letter
    score=+5
else:
    password_strength['has_upper'] = False
score=-5#Taking away 5 points from the score

if re.search(r'[a-z]', password):
    password_strength['has_lower'] = True#checks if the password has a lower case letter
    score=+5
else:
    password_strength['has_lower'] = False
score= -5

if re.search(r'[0-9]', password):
    password_strength['has_num'] = True#Checking if the password has any numbers
    score=+5
else:
    password_strength['has_num'] = False
score=-5

score = len([b for b in password_strength.values() if b])#comparing the score against the strength

print ('Password is %s' % password_scores[score])#prints how strong the password is
print ("Score is: " + str(score))
</code>```

Please could you give any suggestions or ideas what may be the problem, this would be appreciated. Thank-you.

答:
Changed the code a bit :</p>

```<code>import re

def Check():  # menu function. Checks a password
    global score

print('Enter a password')
score = 0  # sets the score to zero

while True:
    password = input('Password: ... ')
    if 7 <= len(password) < 24:
        break
    else:
        print('The password must be between 8 and 24 characters.')

password_scores = {0: 'Horrible', 5: 'Weak', 10: 'Medium', 15: 'Strong'}  # Choses the strength
password_strength = {'has_upper':'0','has_lower':'0','has_num':'0'}

if re.search(r'[A-Z]', password):
    score = +5
    password_strength['has_upper'] = score  # checks if the password has a capital letter

else:
    score = -5  # Taking away 5 points from the score
    password_strength['has_upper'] = score

if re.search(r'[a-z]', password):
    score = +5
    password_strength['has_lower'] = score  # checks if the password has a lower case letter

else:
    score = -5
    password_strength['has_lower'] = score

if re.search(r'[0-9]', password):
    score = +5
    password_strength['has_num'] = score  # Checking if the password has any numbers

else:
    score = -5
    password_strength['has_num'] = score

score = sum(password_strength.values())  # comparing the score against the strength
print(score)

print('Password is %s' % password_scores[score])  # prints how strong the password is
print("Score is: " + str(score))
</code>```

Body:
I am really confused as to why I keep on getting this Error,

password_strength['has_upper'] = False
TypeError: list indices must be integers, not str

,because I have been changing the code around and I still don't understand. I am trying to make a python password checker and I've looked at all other questions and none of them have helped me.

The code is:

def Check():#menu function. Checks a password
global score
print ('Enter a password')
score = 0#sets the score to zero

while True:
    password = input('Password: ... ')
    if 7 <= len(password) < 24:
        break
    else:
        print ('The password must be between 8 and 24 characters.')

password_scores = {0:'Horrible', 5:'Weak', 10:'Medium', 15:'Strong'}#Choses the strength
password_strength = ['has_upper', 'has_lower', 'has_num']

if re.search(r'[A-Z]', password):
    password_strength['has_upper'] = True#checks if the password has a capital letter
    score=+5
else:
    password_strength['has_upper'] = False
score=-5#Taking away 5 points from the score

if re.search(r'[a-z]', password):
    password_strength['has_lower'] = True#checks if the password has a lower case letter
    score=+5
else:
    password_strength['has_lower'] = False
score= -5

if re.search(r'[0-9]', password):
    password_strength['has_num'] = True#Checking if the password has any numbers
    score=+5
else:
    password_strength['has_num'] = False
score=-5

score = len([b for b in password_strength.values() if b])#comparing the score against the strength

print ('Password is %s' % password_scores[score])#prints how strong the password is
print ("Score is: " + str(score))

Please could you give any suggestions or ideas what may be the problem, this would be appreciated. Thank-you.

Body:
Changed the code a bit :

import re

def Check():  # menu function. Checks a password
    global score

print('Enter a password')
score = 0  # sets the score to zero

while True:
    password = input('Password: ... ')
    if 7 <= len(password) < 24:
        break
    else:
        print('The password must be between 8 and 24 characters.')

password_scores = {0: 'Horrible', 5: 'Weak', 10: 'Medium', 15: 'Strong'}  # Choses the strength
password_strength = {'has_upper':'0','has_lower':'0','has_num':'0'}

if re.search(r'[A-Z]', password):
    score = +5
    password_strength['has_upper'] = score  # checks if the password has a capital letter

else:
    score = -5  # Taking away 5 points from the score
    password_strength['has_upper'] = score

if re.search(r'[a-z]', password):
    score = +5
    password_strength['has_lower'] = score  # checks if the password has a lower case letter

else:
    score = -5
    password_strength['has_lower'] = score

if re.search(r'[0-9]', password):
    score = +5
    password_strength['has_num'] = score  # Checking if the password has any numbers

else:
    score = -5
    password_strength['has_num'] = score

score = sum(password_strength.values())  # comparing the score against the strength
print(score)

print('Password is %s' % password_scores[score])  # prints how strong the password is
print("Score is: " + str(score))


来源: stackexchange

问:
How To Keep textarea content
I have a code :

```<code><?php
    if(isset($_POST['data'])) {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'w');
        fwrite($fh, $_POST['data']);
    } else {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'r');
        $theData = fread($fh, filesize($myFile));
    }
    fclose($fh);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>
    </head>
    <body>
        <form name="test" method="post" action="">
            <textarea name="data"><?php echo $theData; ?></textarea>
            <input type="submit" name="submit" value="Update File" />
        </form>
    </body>
</html>
</code>```

When I click submit content of the textarea is lost.
How can I solve this?

答:
You need to add $theData variable in submit also because after submitting you again need to read the data in order to show them.

```<code><?php
if(isset($_POST['data'])) {
    $myFile = "/var/www/vhosts/domain/subdomain/index.php";

    //here I changed the permission with read/write mode.
    $fh = fopen($myFile, 'rw');
    fwrite($fh, $_POST['data']);
    //this line to be added for getting the data after inserting.
    $theData = fread($fh, filesize($myFile));
} else {
    $myFile = "/var/www/vhosts/domain/subdomain/index.php";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
}
fclose($fh);
?>
</code>```

And put htmlspecialchars while echo that variable

```<code><?php echo htmlspecialchars($theData); ?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How To Keep textarea content

Body:
I have a code :

<?php
    if(isset($_POST['data'])) {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'w');
        fwrite($fh, $_POST['data']);
    } else {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'r');
        $theData = fread($fh, filesize($myFile));
    }
    fclose($fh);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>

        <form name="test" method="post" action="">
            <textarea name="data"><?php echo $theData; ?></textarea>
            <input type="submit" name="submit" value="Update File" />
        </form>

When I click submit content of the textarea is lost.
How can I solve this?

Body:
You need to add $theData variable in submit also because after submitting you again need to read the data in order to show them.

<?php
if(isset($_POST['data'])) {
    $myFile = "/var/www/vhosts/domain/subdomain/index.php";

    //here I changed the permission with read/write mode.
    $fh = fopen($myFile, 'rw');
    fwrite($fh, $_POST['data']);
    //this line to be added for getting the data after inserting.
    $theData = fread($fh, filesize($myFile));
} else {
    $myFile = "/var/www/vhosts/domain/subdomain/index.php";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
}
fclose($fh);
?>

And put htmlspecialchars while echo that variable

<?php echo htmlspecialchars($theData); ?>


答:
It's (i, f, c, o). In recurrent.py, in LSTMCell, the weights are constructed by:

    self.kernel_i = self.kernel[:, :self.units]
    self.kernel_f = self.kernel[:, self.units: self.units * 2]
    self.kernel_c = self.kernel[:, self.units * 2: self.units * 3]
    self.kernel_o = self.kernel[:, self.units * 3:]

    self.recurrent_kernel_i = self.recurrent_kernel[:, :self.units]
    self.recurrent_kernel_f = self.recurrent_kernel[:, self.units: self.units * 2]
    self.recurrent_kernel_c = self.recurrent_kernel[:, self.units * 2: self.units * 3]
    self.recurrent_kernel_o = self.recurrent_kernel[:, self.units * 3:]

    if self.use_bias:
        self.bias_i = self.bias[:self.units]
        self.bias_f = self.bias[self.units: self.units * 2]
        self.bias_c = self.bias[self.units * 2: self.units * 3]
        self.bias_o = self.bias[self.units * 3:]
```

Title: Order of LSTM weights in Keras

Body:
I am trying to do a simple evaluation (i.e. forward pass) for a learned LSTM model and I cannot figure out in what order can f_t, i_t, o_t, c_in be extracted from z. It is my understanding that they are computed in bulk.
Here is the model architecture obtained using Keras:

My input sequence is:

input_seq = np.array([[[0.725323664],
                   [0.7671179],
                   [0.805884672]]])

The output should be:

[ 0.83467698]

Using Keras, I have obtained the following parameters for the first LSTM layer:

lstm_1_kernel_0 = np.array([[-0.40927699, -0.53539848, 0.40065038, -0.07722378, 0.30405849, 0.54959822, -0.23097005, 0.4720422, 0.05197877, -0.52746099, -0.5856396, -0.43691438]])

lstm_1_recurrent_kernel_0 = np.array([[-0.25504839, -0.0823682, 0.11609183,  0.41123426, 0.03409858, -0.0647027, -0.59183347, -0.15359771,  0.21647622,  0.24863823, 0.46169096, -0.21100986],
                                  [0.29160395,  0.46513283,  0.33996364, -0.31195125, -0.24458826, -0.09762905, 0.16202784, -0.01602131, 0.34460208, 0.39724654, 0.31806156, 0.1102117],
                                  [-0.15919448, -0.33053166, -0.22857222, -0.04912394, -0.21862955,  0.55346996, 0.38505834, 0.18110731, 0.270677, -0.02759281, 0.42814475, -0.13496138]])
lstm_1_bias_0 = np.array([0., 0., 0., 1., 1., 1., 0., 0., 0., 0., 0., 0.])

# LSTM 1
z_1_lstm_1 = np.dot(x_1_lstm_1, lstm_1_kernel_0) + np.dot(h_0_lstm_1, lstm_1_recurrent_kernel_0) + lstm_1_bias_0
i_1_lstm_1 = z_1_lstm_1[0, 0:3]
f_1_lstm_1 = z_1_lstm_1[0, 3:6]
input_to_c_1_lstm_1 = z_1_lstm_1[0, 6:9]
o_1_lstm_1 = z_1_lstm_1[0, 9:12]

So the question is what is the correct order for i_1_lstm_1, f_1_lstm_1, input_to_c_1_lstm_1, o_1_lstm_1 ?


问:
How to trigger SelectIndexChanged event to VListBox?
Somebody know the VListBox?
It is fast to load item to the listbox.

But I can't get the SelectIndexChanged Event be triggered by set SelectIndex.
Somebody know how to trigger that event by winapi or something else?
VlistBox source code is in the page above.

答:
Wy don't you call the EventHandler manually?</p>

```<code>vListBox1_selectedIndexChanged(null,null);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Wy don't you call the EventHandler manually?

vListBox1_selectedIndexChanged(null,null);


问:
Create a Generic Base Adapter?
I am interested in creating a generic BaseAdapter which will apply to any ListView having any list_item . And it will set the item_row for the list_view.

```<code>    public class GenericAdapter extends BaseAdapter
    {

    Context context;

    ArrayList<HashMap<String, String>> list;

    LayoutInflater inflater;

    public GenericAdapter (Context context, ArrayList<HashMap<String, String>> list)
        {
            this.context = context;

            this.list = list;

            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public Object getItem(int position)
        {
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view = convertView;

          if(view == null)
           {
            view = inflater.inflate(R.layout.item_of_any_list, parent, false);

// i have to do something here like there may be a method which must be call

           }

            /*HashMap<String, String> map = list.get(position);

            TextView textViewName = (TextView) view.findViewById(R.id.name);

            TextView textViewDate = (TextView) view.findViewById(R.id.date);

            //TextView textViewDesc = (TextView) view.findViewById(R.id.desc);

            textViewName.setText(map.get("name"));

            textViewDate.setText(map.get("date"));

            //textViewDesc.setText(map.get("description"));
    */
            return view;
        }
</code>```

I think i have to create an interface that's get and set the item_row for individual item. But i don't know it may be possible . Can someone tell me how i can achieve it.

My idea is to create an interface and GenericAdapter implements that interface. In that interface there is a method to get and set the item_row. Any class which extends GenericAdapter must implement that method. it will  help us  make a generic adapter.

When we extend that adapter we don't need to write all code like getCount, getItem,getItemId, we just have to override a function which is to inflateLayout. which must be inside getView

Thanks in Advance

答:
```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

public abstract class GenericAdapter<T> extends BaseAdapter {
    LayoutInflater layoutInflater;
    Context context;
    private List<T> tList;

public GenericAdapter(Context context, List<T> tList) {
        this.context = context;
        this.tList = tList;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        if (tList == null)
            return 0;
        return tList.size();
    }

    @Override
    public Object getItem(int position) {
        return tList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public abstract View getMyView(int position, View convertView, ViewGroup parent,T t);

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getMyView(position, convertView, parent,tList.get(position));
    }

}
</code>```

and you can use it like

```<code>spnDistrict.setAdapter(new GenericAdapter<Institutions>(getContext(), institutionsList) {
            @Override
            public View getMyView(int position, View convertView, ViewGroup parent, Institutions institutions) {
                TextView textView = (TextView) convertView;
                if (textView == null) {
                    textView = (TextView) getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
                    textView.setTextColor(getContext().getResources().getColor(R.color.black));
                }
                textView.setText(institutions.getName());
                return textView;
            }
        });
</code>```

Title: Create a Generic Base Adapter?

Body:
I am interested in creating a generic BaseAdapter which will apply to any ListView having any list_item . And it will set the item_row for the list_view.

    public class GenericAdapter extends BaseAdapter
    {

    Context context;

    ArrayList<HashMap<String, String>> list;

    LayoutInflater inflater;

    public GenericAdapter (Context context, ArrayList<HashMap<String, String>> list)
        {
            this.context = context;

            this.list = list;

            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public Object getItem(int position)
        {
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view = convertView;

          if(view == null)
           {
            view = inflater.inflate(R.layout.item_of_any_list, parent, false);

// i have to do something here like there may be a method which must be call

           }

            /*HashMap<String, String> map = list.get(position);

            TextView textViewName = (TextView) view.findViewById(R.id.name);

            TextView textViewDate = (TextView) view.findViewById(R.id.date);

            //TextView textViewDesc = (TextView) view.findViewById(R.id.desc);

            textViewName.setText(map.get("name"));

            textViewDate.setText(map.get("date"));

            //textViewDesc.setText(map.get("description"));
    */
            return view;
        }

I think i have to create an interface that's get and set the item_row for individual item. But i don't know it may be possible . Can someone tell me how i can achieve it.

My idea is to create an interface and GenericAdapter implements that interface. In that interface there is a method to get and set the item_row. Any class which extends GenericAdapter must implement that method. it will  help us  make a generic adapter.

When we extend that adapter we don't need to write all code like getCount, getItem,getItemId, we just have to override a function which is to inflateLayout. which must be inside getView

Thanks in Advance

Body:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

public abstract class GenericAdapter<T> extends BaseAdapter {
    LayoutInflater layoutInflater;
    Context context;
    private List<T> tList;

public GenericAdapter(Context context, List<T> tList) {
        this.context = context;
        this.tList = tList;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        if (tList == null)
            return 0;
        return tList.size();
    }

    @Override
    public Object getItem(int position) {
        return tList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public abstract View getMyView(int position, View convertView, ViewGroup parent,T t);

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getMyView(position, convertView, parent,tList.get(position));
    }

}

and you can use it like

spnDistrict.setAdapter(new GenericAdapter<Institutions>(getContext(), institutionsList) {
            @Override
            public View getMyView(int position, View convertView, ViewGroup parent, Institutions institutions) {
                TextView textView = (TextView) convertView;
                if (textView == null) {
                    textView = (TextView) getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
                    textView.setTextColor(getContext().getResources().getColor(R.color.black));
                }
                textView.setText(institutions.getName());
                return textView;
            }
        });


问:
Retain default namespace on appending child element
I have a following XML document:

```<code><?xml version="1.0" encoding="UTF-8"?>
<parent xmlns="urn:parent:ns:1.0"/>
</code>```

I figured out how to convert XML string into element and append it to existing element using this so.

Procedure goes like this:

```<code>String text = "<child></child>";
Document document = builder.parse(new InputSource(new
    StringReader(text)));
Element element = document.getDocumentElement();
Element importedNode = (Element) parent.importNode(element, true);
parent.getDocumentElement().appendChild(importedNode);
</code>```

This produces:

```<code><?xml version="1.0" encoding="UTF-8"?>
<parent xmlns="urn:parent:ns:1.0">
    <child xmlns=""/>
</parent>
</code>```

Child element clears its default namespace, and I would like to 'inherit' the namespace from the parent (in this case urn:parent:ns:1.0).

It would be preferable if solution would use only JRE API for XML, no 3rd party libs (e.g. dom4j etc.)

答:
This solution is inspired by this so:</p>

```<code>String text = "<child></child>";
Document document = builder.parse(new InputSource(new
    StringReader(text)));
Element originalElement = document.getDocumentElement();

Element newDocumentElement =
    document.createElementNS("urn:parent:ns:1.0",
    originalElement.getNodeName());

// no child elements, otherwise append all children to
// newDocumentElement

Element importedNode = (Element) parent.importNode(newDocumentElement,
    true);
parent.getDocumentElement().appendChild(importedNode);
</code>```

Body:
I have a following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<parent xmlns="urn:parent:ns:1.0"/>

I figured out how to convert XML string into element and append it to existing element using this so.

Procedure goes like this:

String text = "<child></child>";
Document document = builder.parse(new InputSource(new
    StringReader(text)));
Element element = document.getDocumentElement();
Element importedNode = (Element) parent.importNode(element, true);
parent.getDocumentElement().appendChild(importedNode);

This produces:

<?xml version="1.0" encoding="UTF-8"?>
<parent xmlns="urn:parent:ns:1.0">
    <child xmlns=""/>
</parent>

Child element clears its default namespace, and I would like to 'inherit' the namespace from the parent (in this case urn:parent:ns:1.0).

It would be preferable if solution would use only JRE API for XML, no 3rd party libs (e.g. dom4j etc.)

Body:
This solution is inspired by this so:

String text = "<child></child>";
Document document = builder.parse(new InputSource(new
    StringReader(text)));
Element originalElement = document.getDocumentElement();

Element newDocumentElement =
    document.createElementNS("urn:parent:ns:1.0",
    originalElement.getNodeName());

// no child elements, otherwise append all children to
// newDocumentElement

Element importedNode = (Element) parent.importNode(newDocumentElement,
    true);
parent.getDocumentElement().appendChild(importedNode);


问:
Browser detection in JavaScript?
How do I determine the exact browser and version using JavaScript?</p>

答:
Below code snippet will show how how you can show UI elemnts depends on IE version and browser

```<code>$(document).ready(function () {

var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {

    //Show UI elements specific to IE version 8 or low

    } else {
    //Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
    }
}
);
</code>```

Below code will give how we can get IE version

```<code>function GetMSIieversion() {

var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}

var trident = ua.indexOf('Trident/');
if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}

var edge = ua.indexOf('Edge/');
if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}

// other browser like Chrome,Mozila..etc
return false;

}
</code>```

Title: Browser detection in JavaScript?

Body:
Below code snippet will show how how you can show UI elemnts depends on IE version and browser

$(document).ready(function () {

var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {

    //Show UI elements specific to IE version 8 or low

    } else {
    //Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
    }
}
);

Below code will give how we can get IE version

function GetMSIieversion() {

var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}

var trident = ua.indexOf('Trident/');
if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}

var edge = ua.indexOf('Edge/');
if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}

// other browser like Chrome,Mozila..etc
return false;

}


问:
email confirmation verification
I have a Wcf service and an Xamarin.forms mobile application, when the user registers from the mobile app I want the web service to send an email verification to the user, when the user goes to his/her email and clicks the link the user account will be activated.

I only have one solution which is to have the user id in the verification link and give the service url followed by verification function and user id.

Is there a better secure way to do so as I dont want to give wcf link in the link?

```<code>private void SendEmailConfirmation(String EmailId,string UserId)
        {
            MailMessage msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            string emailId = EmailId;
            msg.From = new MailAddress("YourGmailEmailId@gmail.com");
            msg.To.Add(emailId);
            msg.Subject = "Confirmation email for account activation";
            //For testing replace the local host path with your lost host path and while making online replace with your website domain name
            //string ActivationUrl = "http://localhost:8665/FetchUserId(emailId) & "&EmailId=" & emailId);
            msg.Body ="Thanks for showing interest and registring in <a href='http://www.activationlink.com'> webservice.com<a> " +
                  " Please Thanks!";
            msg.IsBodyHtml = true;
            smtp.Credentials = new NetworkCredential("emailaddress@gmail.com", "mypassword");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            //NetworkCredential Credentials = new NetworkCredential("emailaddress@gmail.com", "Super2@17");
            //smtp.UseDefaultCredentials = false;
            smtp.Send(msg);
        }
</code>```

答:
```<code>using System.Linq;
using System.Net;
using System.Net.Mail;
</code>```

You will need to import the above namespaces.

Title: email confirmation verification

Body:
I have a Wcf service and an Xamarin.forms mobile application, when the user registers from the mobile app I want the web service to send an email verification to the user, when the user goes to his/her email and clicks the link the user account will be activated.

I only have one solution which is to have the user id in the verification link and give the service url followed by verification function and user id.

Is there a better secure way to do so as I dont want to give wcf link in the link?

private void SendEmailConfirmation(String EmailId,string UserId)
        {
            MailMessage msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            string emailId = EmailId;
            msg.From = new MailAddress("YourGmailEmailId@gmail.com");
            msg.To.Add(emailId);
            msg.Subject = "Confirmation email for account activation";
            //For testing replace the local host path with your lost host path and while making online replace with your website domain name
            //string ActivationUrl = "http://localhost:8665/FetchUserId(emailId) & "&EmailId=" & emailId);
            msg.Body ="Thanks for showing interest and registring in  webservice.com " +
                  " Please Thanks!";
            msg.IsBodyHtml = true;
            smtp.Credentials = new NetworkCredential("emailaddress@gmail.com", "mypassword");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            //NetworkCredential Credentials = new NetworkCredential("emailaddress@gmail.com", "Super2@17");
            //smtp.UseDefaultCredentials = false;
            smtp.Send(msg);
        }

Body:
using System.Linq;
using System.Net;
using System.Net.Mail;

You will need to import the above namespaces.


问:
Liferay Portal : How different from Websphere Portal
I have worked with Websphere Portal 6.0,6.1 and developed portal applications usign JSR 168,JSR 286 Portlets.

Now I am moving to project where I will be working with Liferay portal server and JSR 168,JSR 286.

I know that as per programming interface (JSRs) It will be the same. But want to know what are the major difference at server level ( features,configuration,architecture, out-of-box services) when compared to Websphere Portal ?

Thanks

答:
I agree the configuration will be different but I think it will help a lot the fact that you are prepared to think about the information architechture.

The main difference is that Liferay is not really that much prepared for escalability. It uses velocity so neither of the tags you use will help (Placeholders, component, element, etc).

It doesnt have that many portlets by default so you will have to develop a lot from the starter point.

Check this out for a really nice comparision (the slides are in spanish, and require the flash plug-in):

http://www.slideshare.net/mcimino/websphere-portal-vs-liferay-by-gartner-v10

Basically Liferay weaker points are in B2C and support. If you need to build a site that will rely heavily on personalization, you will have much work to do too.

Hope it helps


问:
If a class dependency is missing, how can I determine which class is missing?
I am getting the error "Could not find or load main class" even though the class is there. From this answer, I learned that the class can likely be found, but not loaded, due to missing dependencies.

Aside from manually decompiling the class, checking all its dependencies, and if those are on the classpath, and so on for each dependent class ad infinitum....is there any way to determine exactly which class is missing from the classpath therefore causing Java to be unable to load my main class?

That other question was a question of a missing parent/interface class. But I have manually checked that all ancestor classes are either on the specified classpath or in the JDK, as below.

```<code>$ cd ~/picketbox
$ java -cp picketbox-4.1.1.Final-redhat-1.jar org.picketbox.datasource.security.SecureIdentityLoginModule HelloWorld
Error: Could not find or load main class org.picketbox.datasource.security.SecureIdentityLoginModule
$ jar xvf picketbox-4.1.1.Final-redhat-1.jar > jarxvf.txt
$ cat jarxvf.txt | grep SecureIdentityLoginModule
 inflated: org/picketbox/datasource/security/SecureIdentityLoginModule.class
$ cd org/picketbox/datasource/security/
$ javap SecureIdentityLoginModule.class | grep main
  public static void main(java.lang.String[]) throws java.lang.Exception;
$ javap SecureIdentityLoginModule.class | grep extends
public class org.picketbox.datasource.security.SecureIdentityLoginModule extends org.picketbox.datasource.security.AbstractPasswordCredentialLoginModule {
$ cat ~/picketbox/jarxvf.txt | grep AbstractPasswordCredentialLoginModule
 inflated: org/picketbox/datasource/security/AbstractPasswordCredentialLoginModule.class
$ javap AbstractPasswordCredentialLoginModule.class | grep extends
public abstract class org.picketbox.datasource.security.AbstractPasswordCredentialLoginModule extends org.jboss.security.auth.spi.AbstractServerLoginModule {
$ cat ~/picketbox/jarxvf.txt | grep AbstractServerLoginModule
 inflated: org/jboss/security/auth/spi/AbstractServerLoginModule.class
$ cd ~/picketbox/org/jboss/security/auth/spi/
$ javap AbstractServerLoginModule.class | grep implements
public abstract class org.jboss.security.auth.spi.AbstractServerLoginModule implements javax.security.auth.spi.LoginModule {
$ cd ~/rtjar
$ cp /usr/java/jdk1.8.0_141/jre/lib/rt.jar ./
$ jar xvf rt.jar | grep spi/LoginModule
extracted: javax/security/auth/spi/LoginModule.class
$ cd javax/security/auth/spi/
$ javap LoginModule.class | grep interface
public interface javax.security.auth.spi.LoginModule {
$
</code>```

答:
Create a helper class:

```<code>public class Helper {
    public static void main(String[] args) {
        YourActualMainClass.main(args);
    }
}
</code>```

and try to run this helper class instead of YourActualMainClass.

The key point is that neither Helper’s inheritance tree nor the signatures of its members depend on the problematic class, so loading and even initialization will succeed, given HotSpot’s lazy resolving strategy, so it will only attempt to load and resolve YourActualMainClass when trying to execute the Helper.main method. At this point, it will throw a detailed error telling you which class was actually missing.

This matches the behavior described in the linked answer that the use of a class leads to a specific error message when the inheritance of the using class does not depend on it.

Alternatively, you could try to run the application with Java 9, as its launcher will print the cause when the loading of the main class failed.

Body:
I am getting the error "Could not find or load main class" even though the class is there. From this answer, I learned that the class can likely be found, but not loaded, due to missing dependencies.

Aside from manually decompiling the class, checking all its dependencies, and if those are on the classpath, and so on for each dependent class ad infinitum....is there any way to determine exactly which class is missing from the classpath therefore causing Java to be unable to load my main class?

That other question was a question of a missing parent/interface class. But I have manually checked that all ancestor classes are either on the specified classpath or in the JDK, as below.

$ cd ~/picketbox
$ java -cp picketbox-4.1.1.Final-redhat-1.jar org.picketbox.datasource.security.SecureIdentityLoginModule HelloWorld
Error: Could not find or load main class org.picketbox.datasource.security.SecureIdentityLoginModule
$ jar xvf picketbox-4.1.1.Final-redhat-1.jar > jarxvf.txt
$ cat jarxvf.txt | grep SecureIdentityLoginModule
 inflated: org/picketbox/datasource/security/SecureIdentityLoginModule.class
$ cd org/picketbox/datasource/security/
$ javap SecureIdentityLoginModule.class | grep main
  public static void main(java.lang.String[]) throws java.lang.Exception;
$ javap SecureIdentityLoginModule.class | grep extends
public class org.picketbox.datasource.security.SecureIdentityLoginModule extends org.picketbox.datasource.security.AbstractPasswordCredentialLoginModule {
$ cat ~/picketbox/jarxvf.txt | grep AbstractPasswordCredentialLoginModule
 inflated: org/picketbox/datasource/security/AbstractPasswordCredentialLoginModule.class
$ javap AbstractPasswordCredentialLoginModule.class | grep extends
public abstract class org.picketbox.datasource.security.AbstractPasswordCredentialLoginModule extends org.jboss.security.auth.spi.AbstractServerLoginModule {
$ cat ~/picketbox/jarxvf.txt | grep AbstractServerLoginModule
 inflated: org/jboss/security/auth/spi/AbstractServerLoginModule.class
$ cd ~/picketbox/org/jboss/security/auth/spi/
$ javap AbstractServerLoginModule.class | grep implements
public abstract class org.jboss.security.auth.spi.AbstractServerLoginModule implements javax.security.auth.spi.LoginModule {
$ cd ~/rtjar
$ cp /usr/java/jdk1.8.0_141/jre/lib/rt.jar ./
$ jar xvf rt.jar | grep spi/LoginModule
extracted: javax/security/auth/spi/LoginModule.class
$ cd javax/security/auth/spi/
$ javap LoginModule.class | grep interface
public interface javax.security.auth.spi.LoginModule {
$

Body:
Create a helper class:

public class Helper {
    public static void main(String[] args) {
        YourActualMainClass.main(args);
    }
}

and try to run this helper class instead of YourActualMainClass.

The key point is that neither Helper’s inheritance tree nor the signatures of its members depend on the problematic class, so loading and even initialization will succeed, given HotSpot’s lazy resolving strategy, so it will only attempt to load and resolve YourActualMainClass when trying to execute the Helper.main method. At this point, it will throw a detailed error telling you which class was actually missing.

This matches the behavior described in the linked answer that the use of a class leads to a specific error message when the inheritance of the using class does not depend on it.

Alternatively, you could try to run the application with Java 9, as its launcher will print the cause when the loading of the main class failed.


问:
Default constructed map iterator enters infinite loop on increment - Green Hills compiler
I have to do a trivial iteration of all the elements in a std::map, first to last. On each element I have to perform an operation. Assume that the map contains the following pairs:

```<code>map<string,string> farm={
                        {"one","puppy"},
                        {"two","kitty"},
                        {"three","sheepy"}
                       }
</code>```

The bit of code that performs the iteration is the following:

```<code>for(map<string,string>::iterator beast; beast!=farm.end(); ++beast)
{
     feed(*beast);
}
</code>```

Now the surprise is that the above code works for the first element (puppy is fed) but the iterator fails to go to the next elements. The debugger shows that ++beast never returns (seems like it is recursively branching on its left leaf forever).

It seems that the issue here is that beast is never assigned to farm.begin() and as such it can't progress to the next item (see first element of the for).

So here are my questions:

Is it normal that the default constructor of a map iterator automatically positions the object to point to the map.begin() element?

If that is common practice, then why a valid first element is
returned (it could have been returned map.end() for example) ?

How could the operator++ be allowed to quietly fail in an infinite loop? Wouldn't be better to return with an error code (we disabled
exceptions) or fail openly somehow ?

I wonder if the standard allows this kind of behaviours or it is an implementation choice.

Assumptions: I am not using C++11, I am using Green Hills compiler v2016 with execption support disabled

EDIT:

I am trying to understand why I get a valid value and a quiet fail as in other threads people suggest that a default-constructed iterator is assigned to map.end(). Does the standard gives guidance on this?

答:
Is it normal that the default constructor of a map iterator
  automatically positions the object to point to the map.begin()
  element?

No, you should initialize it properly:

```<code>for(map<string,string>::iterator beast = farm.begin(); beast!=farm.end(); ++beast)
</code>```

Btw there is no way that the compiler can know that you want map<string,string>::iterator beast to be an iterator for farm, of course you need to get an iterator from the container and not just create an iterator and assume it points to the container you wish.

Body:
I have to do a trivial iteration of all the elements in a std::map, first to last. On each element I have to perform an operation. Assume that the map contains the following pairs:

map<string,string> farm={
                        {"one","puppy"},
                        {"two","kitty"},
                        {"three","sheepy"}
                       }

The bit of code that performs the iteration is the following:

for(map<string,string>::iterator beast; beast!=farm.end(); ++beast)
{
     feed(*beast);
}

Now the surprise is that the above code works for the first element (puppy is fed) but the iterator fails to go to the next elements. The debugger shows that ++beast never returns (seems like it is recursively branching on its left leaf forever).

It seems that the issue here is that beast is never assigned to farm.begin() and as such it can't progress to the next item (see first element of the for).

So here are my questions:

Is it normal that the default constructor of a map iterator automatically positions the object to point to the map.begin() element?

If that is common practice, then why a valid first element is
returned (it could have been returned map.end() for example) ?

How could the operator++ be allowed to quietly fail in an infinite loop? Wouldn't be better to return with an error code (we disabled
exceptions) or fail openly somehow ?

I wonder if the standard allows this kind of behaviours or it is an implementation choice.

Assumptions: I am not using C++11, I am using Green Hills compiler v2016 with execption support disabled

EDIT:

I am trying to understand why I get a valid value and a quiet fail as in other threads people suggest that a default-constructed iterator is assigned to map.end(). Does the standard gives guidance on this?

Body:
Is it normal that the default constructor of a map iterator
  automatically positions the object to point to the map.begin()
  element?

No, you should initialize it properly:

for(map<string,string>::iterator beast = farm.begin(); beast!=farm.end(); ++beast)

Btw there is no way that the compiler can know that you want map<string,string>::iterator beast to be an iterator for farm, of course you need to get an iterator from the container and not just create an iterator and assume it points to the container you wish.


问:
How to set an active tab
i did a tabbed menu on bootstrap. But i can't figure out active tab

How to style active tab, When i  define active class, it only effects first tab.

screenshot

heres my code below

```<code>    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
      <script>
   jQuery(function($){
       $(".circle").children("circle").click(function(){
           $(".active").removeClass("active");
       });
   });
</script>
  </head>
  <body>

<!-- Nav tabs --><div class="d-none d-sm-block girintile">
<ul class="nav nav-justified" role="tablist">
  <li class="nav-item">
      <a class="nav-link active" data-toggle="tab" href="#section-1" role="tab"> <div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle active"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-2" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-3" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-4" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
    <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-5" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
</ul></div>

<!-- Tab panes -->
<div class="tab-content girintile "><br>
  <div class="tab-pane box active" id="section-1" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok</h4><p class="text-justified girintile"> yunus</p></div>
  <div class="tab-pane box" id="section-2" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok1</h4><p class="text-justified girintile"> melih</p></div>
  <div class="tab-pane box" id="section-3" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok2</h4><p class="text-justified girintile"> gözütok</p></div>
  <div class="tab-pane box" id="section-4" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok3</h4><p class="text-justified girintile"> lipsum</p></div>
  <div class="tab-pane box" id="section-5" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok4</h4><p class="text-justified girintile"> lipsum</p></div>
</div>
</code>```

答:
i just added some active class with red color text, when u click on each item color red will apply and remaining will be same as blue color text

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

 yunus

Yunus Melih Gözütok1

 melih

Yunus Melih Gözütok2

 gözütok

Yunus Melih Gözütok3

 lipsum

Yunus Melih Gözütok4

 lipsum

```

Title: How to set an active tab

Body:
i did a tabbed menu on bootstrap. But i can't figure out active tab

How to style active tab, When i  define active class, it only effects first tab.

screenshot

heres my code below

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

 yunus

Yunus Melih Gözütok1

 melih

Yunus Melih Gözütok2

 gözütok

Yunus Melih Gözütok3

 lipsum

Yunus Melih Gözütok4

 lipsum

Body:
i just added some active class with red color text, when u click on each item color red will apply and remaining will be same as blue color text

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
    <style>
    .active{
      color:red !important;
    }
    </style>
      <script>
   $(".nav-item .nav-link").click(function(e){
  e.preventDefault();
  $(this).addClass("active");
  $(".nav-item .nav-link").not($(this)).removeClass("active");
})
</script>
  </head>
  <body>

<!-- Nav tabs --><div class="d-none d-sm-block girintile">
<ul class="nav nav-justified" role="tablist">
  <li class="nav-item">
      <a class="nav-link active" data-toggle="tab" href="#section-1" role="tab"> <div class="team-box"> <img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Codero_Hosting_Logo_%28100px%29.png" class="img-fluid rounded-circle circle active"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-2" role="tab"><div class="team-box"> <img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Codero_Hosting_Logo_%28100px%29.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-3" role="tab"><div class="team-box"> <img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Codero_Hosting_Logo_%28100px%29.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-4" role="tab"><div class="team-box"> <img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Codero_Hosting_Logo_%28100px%29.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
    <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-5" role="tab"><div class="team-box"> <img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Codero_Hosting_Logo_%28100px%29.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
</ul></div>

<!-- Tab panes -->
<div class="tab-content girintile "><br>
  <div class="tab-pane box active" id="section-1" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok</h4><p class="text-justified girintile"> yunus</p></div>
  <div class="tab-pane box" id="section-2" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok1</h4><p class="text-justified girintile"> melih</p></div>
  <div class="tab-pane box" id="section-3" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok2</h4><p class="text-justified girintile"> gözütok</p></div>
  <div class="tab-pane box" id="section-4" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok3</h4><p class="text-justified girintile"> lipsum</p></div>
  <div class="tab-pane box" id="section-5" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok4</h4><p class="text-justified girintile"> lipsum</p></div>
</div>


问:
How to get column count in SQL before executing the query? i.e. way other than ResultSetMetaData
I have a sql query. Because of too many BO's are involved, it's forming very big query containing more than 1000 columns. So I need some way with which I can find column count before hand and then apply some logic to handle 1000 column error.

May be parsing a query to get column count would help. But not getting how to implement it.

Note: tried below code already, it's giving me result, but i dont want to execute query, that's costly.

```<code>PreparedStatement pstmt;
    try {
        pstmt = getConnection().prepareStatement(sql);
        ResultSetMetaData meta = pstmt.getMetaData();
        System.out.println(meta.getColumnCount());

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

答:
If it is a plain old select query like :

select col1,col2 as xyz, col3,col4... from ... where ...

you can do something like this:

```<code>String select="select";//"SELECT" if yours is in caps
String from="from";//"FROM" if yours is in caps
String cols = sql.substring(sql.indexOf(select)+select.length(), sql.indexOf(from));
int colCount = cols.split(",").length;
</code>```

If your query contains functions like fn(col,'blah blah') you need to write some extra code to ID such functions and process things appropriately.

Body:
I have a sql query. Because of too many BO's are involved, it's forming very big query containing more than 1000 columns. So I need some way with which I can find column count before hand and then apply some logic to handle 1000 column error.

May be parsing a query to get column count would help. But not getting how to implement it.

Note: tried below code already, it's giving me result, but i dont want to execute query, that's costly.

PreparedStatement pstmt;
    try {
        pstmt = getConnection().prepareStatement(sql);
        ResultSetMetaData meta = pstmt.getMetaData();
        System.out.println(meta.getColumnCount());

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Body:
If it is a plain old select query like :

select col1,col2 as xyz, col3,col4... from ... where ...

you can do something like this:

String select="select";//"SELECT" if yours is in caps
String from="from";//"FROM" if yours is in caps
String cols = sql.substring(sql.indexOf(select)+select.length(), sql.indexOf(from));
int colCount = cols.split(",").length;

If your query contains functions like fn(col,'blah blah') you need to write some extra code to ID such functions and process things appropriately.


问:
One sided jQuery UI slider
I am using jQuery UI range slider to allow the user to define a range. Based on the user's selection I will then show/hide different divs.

In order to achieve that I use data-price="" that allow me to check if the value is bigger or smaller than that.

What I would like to achieve is:

Have only one selection for the price rather than selection from left
and right.

I would like to keep the functionality where the bar is filling with colour based on selection. (in the example in grey)

I have tried changing range: true to range: false but I could not achieve the desired effect.

My JSFIDDLE example is here: https://jsfiddle.net/L47mo8bm/

I have tried the following but not sure why the logic is not working: https://jsfiddle.net/57axLd53/1/

答:
I changed around some options in your .slider function.
I set range to false and use a single value to init the slider. You will have to change your logic of showing the products because it won't work with a single slider. As for the color I'm not sure what you mean by that so you would have to clarify that a bit.</p>

```<code>$(function () {
  $('#slider-container').slider({
      range: false,
      min: 299,
      max: 1099,
      value: 500,
      create: function() {
          $("#amount").val("$299 - $1099");
      },
      slide: function (event, ui) {
          $("#amount").val("$" + ui.value);
          var slider_value = ui.value;
          //filterSystem(slider_value);
      }
  })
});

function filterSystem(sliderValue) {
  $("#computers div.system").hide().filter(function () {
      // put logic here to show product within X price of selection
  }).show();
}
</code>```

Title: One sided jQuery UI slider

Body:
I changed around some options in your .slider function.
I set range to false and use a single value to init the slider. You will have to change your logic of showing the products because it won't work with a single slider. As for the color I'm not sure what you mean by that so you would have to clarify that a bit.

$(function () {
  $('#slider-container').slider({
      range: false,
      min: 299,
      max: 1099,
      value: 500,
      create: function() {
          $("#amount").val("$299 - $1099");
      },
      slide: function (event, ui) {
          $("#amount").val("$" + ui.value);
          var slider_value = ui.value;
          //filterSystem(slider_value);
      }
  })
});

function filterSystem(sliderValue) {
  $("#computers div.system").hide().filter(function () {
      // put logic here to show product within X price of selection
  }).show();
}


问:
Laravel custom command argument with dash
I got a custom command in Laravel 5, that gets username and password.

One user got his password starting with a dash, something like -819830219', making laravel return a error saying "The -8 option does not exist.

I tried setting the password between quotation marks and still got the same error.

Is there a way to pass a parameter that starts with a dash that laravel will not understand as a option?

```<code>protected function getArguments()
{
    return [
        ['username', InputArgument::REQUIRED, 'Partner\'s username.'],
        ['password', InputArgument::REQUIRED, 'Partner\'s password.'],
        ['origin', InputArgument::REQUIRED, 'Partner\'s origin code.'],
    ];
}
</code>```

答:
I been in the same situation, it seems to be an issue with arguments.

Another option beside to ask interactive is to use options, with with option this problem does not happen.

For example

protected $signature = 'project:command {--profile=} {--tz=}';

then

$profile_id = $this->option('profile', '');
 $timezone = $this->option('tz', '+00:00');

The call to the command will look like this

artisan project:command --profile=1609 --tz=-04:00

Regards

Body:
I got a custom command in Laravel 5, that gets username and password.

One user got his password starting with a dash, something like -819830219', making laravel return a error saying "The -8 option does not exist.

I tried setting the password between quotation marks and still got the same error.

Is there a way to pass a parameter that starts with a dash that laravel will not understand as a option?

protected function getArguments()
{
    return [
        ['username', InputArgument::REQUIRED, 'Partner\'s username.'],
        ['password', InputArgument::REQUIRED, 'Partner\'s password.'],
        ['origin', InputArgument::REQUIRED, 'Partner\'s origin code.'],
    ];
}


问:
Help with a foreach loop
In my website I am trying to display all the applicants to jobs that a user has posted, basically I want the out put to simimlar too,

Job Title 1

  Aplicant Name 1

  Aplicant Name 2

  Applicant Name 3

Job Title 2

  Applicant Name 4
  Application Name 5

Basically I want the applications to be gathered under the jobs they applied for, however the out put I am current getting is,

Job Title 1

  Application Name 1

Job Title 1

  Applicant Name 2

The code I am using to do this foreach loop is as follows

```<code><?php foreach($applications as $a) : ?>
        <h3><?php echo $a['jobtitle']; ?></h3>
    <li>
        <img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>
        <p><?php echo $a['name']; ?></p>
    </li>
    <?php endforeach; ?>
</code>```

答:
I recommend pulling jobtitle and applicants from the database and storing them in a multidimensional array.

```<code>$jobs[$jobtitle][] = $applicant_name;
</code>```

Then looping through this array in your view.  I've omitted your image code for clarity.

```<code>foreach($jobs as $title=>applicants){
    echo $title;
    foreach($applicants as $name){
        echo $name;
    }
}
</code>```

Title: Help with a foreach loop

Body:
In my website I am trying to display all the applicants to jobs that a user has posted, basically I want the out put to simimlar too,

Job Title 1

  Aplicant Name 1

  Aplicant Name 2

  Applicant Name 3

Job Title 2

  Applicant Name 4
  Application Name 5

Basically I want the applications to be gathered under the jobs they applied for, however the out put I am current getting is,

Job Title 1

  Application Name 1

Job Title 1

  Applicant Name 2

The code I am using to do this foreach loop is as follows

<?php foreach($applications as $a) : ?>

<?php echo $a['jobtitle']; ?>

        <img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>

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

    <?php endforeach; ?>

Body:
I recommend pulling jobtitle and applicants from the database and storing them in a multidimensional array.

$jobs[$jobtitle][] = $applicant_name;

Then looping through this array in your view.  I've omitted your image code for clarity.

foreach($jobs as $title=>applicants){
    echo $title;
    foreach($applicants as $name){
        echo $name;
    }
}


问:
Weird leading characters utf-8/utf-16 encoding in Python
I have written a simplified version to demonstrate the problem. I am encoding special characters in utf-8 and UTF-16 format.

With utf-8 encoding there is no problem, when I am encoding with UTF-16 I get some weird leading characters.

I tried to remove all trailing and leading characters but still the error persists.

Sample of code:

```<code>#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import chardet

def myEncode(s, pattern):
try:
    s.strip()
    u = unicode(s, pattern)
    print chardet.detect(u.encode(pattern, 'strict'))
    return u.encode(pattern, 'strict')
except UnicodeDecodeError as err:
    return "UnicodeDecodeError: ", err
except Exception as err:
    return "ExceptionError: ", err

print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-8')
print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-16')
</code>```

Sample of output:

```<code>{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§
{'confidence': 1.0, 'language': '', 'encoding': 'UTF-16'}
��Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§
</code>```

Where I am going wrong I can not figure it out. I do not want to convert the UTF-16 back to utf-8 it is important for me to keep the format on UTF-16.

Update: Thanks to @tripleee the solution to my problem is to define encoding UTF-16le or UTF-16be. Thanks again for your time and effort.

Thanks in advance for everyone time and effort.

答:
Answer to the problem was given by @tripleee.

By defining utf-16le or utf-16be instead of utf-16 resolved the problem.

Sample of solution:

```<code>#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import chardet

def myEncode(s, pattern):
    try:
        s.strip()
        u = unicode(s, pattern)
        print chardet.detect(u.encode(pattern, 'strict'))
        return u.encode(pattern, 'strict')
    except UnicodeDecodeError as err:
        return "UnicodeDecodeError: ", err
    except Exception as err:
        return "ExceptionError: ", err

print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-8')
print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-16be')
</code>```

Sample of output:

```<code>{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§
{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§
</code>```

Body:
I have written a simplified version to demonstrate the problem. I am encoding special characters in utf-8 and UTF-16 format.

With utf-8 encoding there is no problem, when I am encoding with UTF-16 I get some weird leading characters.

I tried to remove all trailing and leading characters but still the error persists.

Sample of code:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import chardet

def myEncode(s, pattern):
try:
    s.strip()
    u = unicode(s, pattern)
    print chardet.detect(u.encode(pattern, 'strict'))
    return u.encode(pattern, 'strict')
except UnicodeDecodeError as err:
    return "UnicodeDecodeError: ", err
except Exception as err:
    return "ExceptionError: ", err

print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-8')
print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-16')

Sample of output:

{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§
{'confidence': 1.0, 'language': '', 'encoding': 'UTF-16'}
��Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§

Where I am going wrong I can not figure it out. I do not want to convert the UTF-16 back to utf-8 it is important for me to keep the format on UTF-16.

Update: Thanks to @tripleee the solution to my problem is to define encoding UTF-16le or UTF-16be. Thanks again for your time and effort.

Thanks in advance for everyone time and effort.

Body:
Answer to the problem was given by @tripleee.

By defining utf-16le or utf-16be instead of utf-16 resolved the problem.

Sample of solution:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import chardet

def myEncode(s, pattern):
    try:
        s.strip()
        u = unicode(s, pattern)
        print chardet.detect(u.encode(pattern, 'strict'))
        return u.encode(pattern, 'strict')
    except UnicodeDecodeError as err:
        return "UnicodeDecodeError: ", err
    except Exception as err:
        return "ExceptionError: ", err

print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-8')
print myEncode(r"""Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§""",
               'utf-16be')

Sample of output:

{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§
{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
Test !"#$%&'()*+-,./:;<=>?@[\]?_{@}~& € ÄÖÜ äöüß £¥§


问:
How to access custom namespaced (react-)JSS theme from components?
I'm creating a react/redux app, and want to utilize JSS theming to style my app/components. I'm also using other libraries that use JSS theming, e.g. Material UI, thus I need to create a namespaced theme as described in  http://cssinjs.org/react-jss?v=v8.1.0#theming to avoid conflicts with other themes.

Does this mean that I have to import my namespaced theme in every component I want to style with that theme, and pass it to injectSheet? I.e:

```<code>import React from 'react
import injectSheet, {ThemeProvider} from 'react-jss

// import my custom namespaced theming object...
import theming from '../path/to/my/custom/theming'

const styles = theme => ({
  container: {
    background: theme.background,
  }
})

const Demo = () => (
    <div className={props.classes.container}>
      //...
    </div>
)

// injectSheet with my custom namespaced theming object..
export default injectSheet(styles, {theming})(Demo)
</code>```

This feels very cumbersome. Is it another way that one should do this? Am I missing something? Thanks in advance :)

答: You could wrap your injectSheet function in a central place and always pass the theming there.</p>

Body:
I'm creating a react/redux app, and want to utilize JSS theming to style my app/components. I'm also using other libraries that use JSS theming, e.g. Material UI, thus I need to create a namespaced theme as described in  http://cssinjs.org/react-jss?v=v8.1.0#theming to avoid conflicts with other themes.

Does this mean that I have to import my namespaced theme in every component I want to style with that theme, and pass it to injectSheet? I.e:

import React from 'react
import injectSheet, {ThemeProvider} from 'react-jss

// import my custom namespaced theming object...
import theming from '../path/to/my/custom/theming'

const styles = theme => ({
  container: {
    background: theme.background,
  }
})

const Demo = () => (

      //...

)

// injectSheet with my custom namespaced theming object..
export default injectSheet(styles, {theming})(Demo)

This feels very cumbersome. Is it another way that one should do this? Am I missing something? Thanks in advance :)


问:
Python Iterating over lists in lists with map()
So my intention is to iterate over lists in lists with map, filter and lambda
e.g.:

[ [33,3,3,0] , [34,1,0,4] ]  should result in [ [33,3,3] , [34,1,4] ]

```<code>   def no_zeros(lst):
      a=map(filter(lambda x:(y==0 for y in x) ,lst),lst)
      print (list(a))
      #(says that filter is not callable)
</code>```

I know that this code won't work but i do not know what exactly i do wrong since i'm still kind of new to lambda,etc.I already tried different stuff , like moving the filter after the lambda,but that did not seem to work either . Im gratefull for any kind of tipps or help.

答:
Another solution might be:</p>

```<code>def no_zeros(lst):
   if isinstance(lst, list):
      for i in lst:
          while 0 in i:
              i.remove(0)
      print(lst)
   else:
      raise TypeError("lst must be type of list")
</code>```

Body:
So my intention is to iterate over lists in lists with map, filter and lambda
e.g.:

[ [33,3,3,0] , [34,1,0,4] ]  should result in [ [33,3,3] , [34,1,4] ]

   def no_zeros(lst):
      a=map(filter(lambda x:(y==0 for y in x) ,lst),lst)
      print (list(a))
      #(says that filter is not callable)

I know that this code won't work but i do not know what exactly i do wrong since i'm still kind of new to lambda,etc.I already tried different stuff , like moving the filter after the lambda,but that did not seem to work either . Im gratefull for any kind of tipps or help.

Body:
Another solution might be:

def no_zeros(lst):
   if isinstance(lst, list):
      for i in lst:
          while 0 in i:
              i.remove(0)
      print(lst)
   else:
      raise TypeError("lst must be type of list")


问:
How do I validate and create a new model for each line in a text area
Users have many websites, and Websites have many Keywords. (Keywords being nested resources of the Websites resource)

Right now, with the default scaffolding setup, it's very tedious to add many keywords at once. I'd like a text area instead of a text field that allows users to type many keywords, each on their own line, and submit them all at once. The only input on the form is for the keyword's "text" column.

How can I do this?

I can figure out things like params[:keyword][:text].split("\r\n").each do |text|, but I'm not sure how to interact it with the Rails form.

```<code><%= form_for [@website, @keyword] do |f| %>
  <% if @keyword.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@keyword.errors.count, "error") %> prohibited this keyword from being saved:</h2>

      <ul>
      <% @keyword.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :text %><br />
    <%= f.text_area :text %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

答:
Have you considered parsing out keywords separated by commas (or even spaces if you're keywords are single 'words')? I think this is more common...at least in my experience.

For commas it'd be as simple as: line.split(',').

And to remove whitespace before & after comma: line.split(/\s*,\s*/) or line.split(',').map{|k| k.strip}.

Body:
Users have many websites, and Websites have many Keywords. (Keywords being nested resources of the Websites resource)

Right now, with the default scaffolding setup, it's very tedious to add many keywords at once. I'd like a text area instead of a text field that allows users to type many keywords, each on their own line, and submit them all at once. The only input on the form is for the keyword's "text" column.

How can I do this?

I can figure out things like params[:keyword][:text].split("\r\n").each do |text|, but I'm not sure how to interact it with the Rails form.

<%= form_for [@website, @keyword] do |f| %>
  <% if @keyword.errors.any? %>

<%= pluralize(@keyword.errors.count, "error") %> prohibited this keyword from being saved:

      <% @keyword.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :text %>

    <%= f.text_area :text %>

    <%= f.submit %>

<% end %>


问:
Swift UIImage convert as PDF
In my App have to sale UIImage from iPad Gallery and convert into PDF and save on Server side.

I can select the image and send it to server side , but Backend says that pdf is empty(null data)

I also see the warning/error in my console : [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

Where am I going wrong?
Thank you in advance!

Code I tried

```<code>//Opens gallery to select Image
func clickImage() {

    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    self.present(image, animated: true, completion: nil)

}

//image picker function
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
         scannedPhoto.image = image
    } else{
        print("Something went wrong")
    }

    self.dismiss(animated: true, completion: nil)

    uploadAttachment()

}

//Convert UIImage to PDF
func createPDF(image: UIImage) -> NSData? {

    let pdfData = NSMutableData()
    let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!

    var mediaBox = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)

    let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!

    pdfContext.beginPage(mediaBox: &mediaBox)
    pdfContext.draw(image.cgImage!, in: mediaBox)
    pdfContext.endPage()
    return pdfData
}

// custom body of HTTP request to upload pdf file
func createBody(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {

    let body = NSMutableData()

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    let filename = "ava.pdf"

    let mimetype = "pdf"

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageDataKey)
    body.appendString("\r\n")

    body.appendString("--\(boundary)--\r\n")

    return body as Data

}
//Function to send converted pdf server side
func uploadAttachment() {

    let pdfdata = createPDF(image: scannedPhoto.image!)

    // url path to php file
    let url = URL(string: "\(Config.path)/uploadAva.php")!

    // declare request to this file
    var request = URLRequest(url: url)

    // declare method of passign inf to this file
    request.httpMethod = "POST"

    // param to be sent in body of request
    let param = ["AppId":Config.AppID , "uuid":Config.uuid , "Id" : userId]

    // body
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    // ... body
    request.httpBody = createBodyWithParams(param, filePathKey: "file", imageDataKey: pdfdata! as Data, boundary: boundary)

    // launc session
    // warning I receive here
    URLSession.shared.dataTask(with: request) { data, response, error in
        //do anything here
    }
}
</code>```

答:
create pdf file data as:

```<code>func createPDFDataFromImage(image: UIImage) -> NSMutableData {
    let pdfData = NSMutableData()
    let imgView = UIImageView.init(image: image)
    let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    UIGraphicsBeginPDFContextToData(pdfData, imageRect, nil)
    UIGraphicsBeginPDFPage()
    let context = UIGraphicsGetCurrentContext()
    imgView.layer.render(in: context!)
    UIGraphicsEndPDFContext()

    //try saving in doc dir to confirm:
    let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
    let path = dir?.appendingPathComponent("file.pdf")

    do {
            try pdfData.write(to: path!, options: NSData.WritingOptions.atomic)
    } catch {
        print("error catched")
    }

    return pdfData
}
</code>```

Title: Swift UIImage convert as PDF

Body:
In my App have to sale UIImage from iPad Gallery and convert into PDF and save on Server side.

I can select the image and send it to server side , but Backend says that pdf is empty(null data)

I also see the warning/error in my console : [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

Where am I going wrong?
Thank you in advance!

Code I tried

//Opens gallery to select Image
func clickImage() {

    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    self.present(image, animated: true, completion: nil)

}

//image picker function
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
         scannedPhoto.image = image
    } else{
        print("Something went wrong")
    }

    self.dismiss(animated: true, completion: nil)

    uploadAttachment()

}

//Convert UIImage to PDF
func createPDF(image: UIImage) -> NSData? {

    let pdfData = NSMutableData()
    let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!

    var mediaBox = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)

    let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!

    pdfContext.beginPage(mediaBox: &mediaBox)
    pdfContext.draw(image.cgImage!, in: mediaBox)
    pdfContext.endPage()
    return pdfData
}

// custom body of HTTP request to upload pdf file
func createBody(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {

    let body = NSMutableData()

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    let filename = "ava.pdf"

    let mimetype = "pdf"

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageDataKey)
    body.appendString("\r\n")

    body.appendString("--\(boundary)--\r\n")

    return body as Data

}
//Function to send converted pdf server side
func uploadAttachment() {

    let pdfdata = createPDF(image: scannedPhoto.image!)

    // url path to php file
    let url = URL(string: "\(Config.path)/uploadAva.php")!

    // declare request to this file
    var request = URLRequest(url: url)

    // declare method of passign inf to this file
    request.httpMethod = "POST"

    // param to be sent in body of request
    let param = ["AppId":Config.AppID , "uuid":Config.uuid , "Id" : userId]

    // body
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    // ... body
    request.httpBody = createBodyWithParams(param, filePathKey: "file", imageDataKey: pdfdata! as Data, boundary: boundary)

    // launc session
    // warning I receive here
    URLSession.shared.dataTask(with: request) { data, response, error in
        //do anything here
    }
}

Body:
create pdf file data as:

func createPDFDataFromImage(image: UIImage) -> NSMutableData {
    let pdfData = NSMutableData()
    let imgView = UIImageView.init(image: image)
    let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    UIGraphicsBeginPDFContextToData(pdfData, imageRect, nil)
    UIGraphicsBeginPDFPage()
    let context = UIGraphicsGetCurrentContext()
    imgView.layer.render(in: context!)
    UIGraphicsEndPDFContext()

    //try saving in doc dir to confirm:
    let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
    let path = dir?.appendingPathComponent("file.pdf")

    do {
            try pdfData.write(to: path!, options: NSData.WritingOptions.atomic)
    } catch {
        print("error catched")
    }

    return pdfData
}


问:
creating a drawable from sd card to set as a background in android
I am trying to use an image from the sd card and set it as the background for a relativelayout.  I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me.  here is my code.  I have commented out other ways that i have tried and didnt work.  the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly.  when I have tried all the other ways, it just doesn't set anything.  Anyone know what I am doing wrong, or if there is a better way to do this?</p>

```<code>        //one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);

//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);

//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));

//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);
</code>```

答:
You do not load a drawable from SD card but a bitmap. Here is a method to load it with the reduced sampling (quality) so the program will not complain if the image is too large. Then I guess you need to process this bitmap i.e. crop it and resize for the background.

```<code>         // Read bitmap from Uri
     public Bitmap readBitmap(Uri selectedImage) {
         Bitmap bm = null;
         BitmapFactory.Options options = new BitmapFactory.Options();
         options.inSampleSize = 2; //reduce quality
         AssetFileDescriptor fileDescriptor =null;
         try {
             fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         }
         finally{
             try {
                 bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
                 fileDescriptor.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         return bm;
     }
</code>```

The Uri here can be supplied from a gallery picker activity.

The image then can be saved into application resources and loaded into an imageView

```<code>        private void saveBackground(Bitmap Background) {
        String strBackgroundFilename = "background_custom.jpg";
        try {
            Background.compress(CompressFormat.JPEG, 80, openFileOutput(strBackgroundFilename, MODE_PRIVATE));
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Background compression and save failed.", e);
        }

        Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(BackgroundSettings.this.getFilesDir(), strBackgroundFilename));

        // Load this image
        Bitmap bitmapImage = BitmapFactory.decodeFile(imageUriToSaveCameraImageTo.getPath());
        Drawable bgrImage = new BitmapDrawable(bitmapImage);

        //show it in a view
        ImageView backgroundView = (ImageView) findViewById(R.id.BackgroundImageView);
        backgroundView.setImageURI(null);
        backgroundView.setImageDrawable(bgrImage);
    }
</code>```

Body:
I am trying to use an image from the sd card and set it as the background for a relativelayout.  I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me.  here is my code.  I have commented out other ways that i have tried and didnt work.  the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly.  when I have tried all the other ways, it just doesn't set anything.  Anyone know what I am doing wrong, or if there is a better way to do this?

        //one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);

//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);

//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));

//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);

Body:
You do not load a drawable from SD card but a bitmap. Here is a method to load it with the reduced sampling (quality) so the program will not complain if the image is too large. Then I guess you need to process this bitmap i.e. crop it and resize for the background.

         // Read bitmap from Uri
     public Bitmap readBitmap(Uri selectedImage) {
         Bitmap bm = null;
         BitmapFactory.Options options = new BitmapFactory.Options();
         options.inSampleSize = 2; //reduce quality
         AssetFileDescriptor fileDescriptor =null;
         try {
             fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         }
         finally{
             try {
                 bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
                 fileDescriptor.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         return bm;
     }

The Uri here can be supplied from a gallery picker activity.

The image then can be saved into application resources and loaded into an imageView

        private void saveBackground(Bitmap Background) {
        String strBackgroundFilename = "background_custom.jpg";
        try {
            Background.compress(CompressFormat.JPEG, 80, openFileOutput(strBackgroundFilename, MODE_PRIVATE));
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Background compression and save failed.", e);
        }

        Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(BackgroundSettings.this.getFilesDir(), strBackgroundFilename));

        // Load this image
        Bitmap bitmapImage = BitmapFactory.decodeFile(imageUriToSaveCameraImageTo.getPath());
        Drawable bgrImage = new BitmapDrawable(bitmapImage);

        //show it in a view
        ImageView backgroundView = (ImageView) findViewById(R.id.BackgroundImageView);
        backgroundView.setImageURI(null);
        backgroundView.setImageDrawable(bgrImage);
    }


问:
extracting components from json dictionary
I have a json dictionary (result_dict_tag) as follows:

```<code>{'10644906845': {'photo': {'id': '10644906845',
   'tags': {'tag': [{'_content': 'srilanka',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-23098',
      'machine_tag': 0,
      'raw': 'sri lanka'},
     {'_content': 'navy',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-7137',
      'machine_tag': 0,
      'raw': 'navy'},
     {'_content': 'vessel',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-8792',
      'machine_tag': 0,
      'raw': 'vessel'}]}},
  'stat': 'ok'},
      '11778819726': {'photo': {'id': '11778819726',
   'tags': {'tag': [{'_content': 'sri',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12165',
      'machine_tag': 0,
      'raw': 'sri'},
     {'_content': 'lanka',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12166',
      'machine_tag': 0,
      'raw': 'lanka'},
     {'_content': 'mirissa',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-1158107',
      'machine_tag': 0,
      'raw': 'mirissa'}]}},
  'stat': 'ok'}}
</code>```

What I want is to extract the 'raw' words from each dictionary (e.g.result_dict_tag['10644906845']['photo']["tags"]['tag'][0]['raw']) and and create a dataframe consisting user id and relevant raw words for each user. I feel this need some for loop. I have written one and it only results the 'raw' words related to first user only. I have gone through documentation and various questions similar to this. But couldn't figure it out. Any help is appreciated.

答:
You can extract these in a single list comprehension</p>

```<code>raw_words = [mydict[i]['photo']["tags"]['tag'][k]['raw']
             for k in range(len(mydict[i]['photo']["tags"]['tag']))
             for i in mydict]

print(raw_words)
>> ['sri', 'sri lanka', 'lanka', 'navy', 'mirissa', 'vessel']
</code>```

Body:
I have a json dictionary (result_dict_tag) as follows:

{'10644906845': {'photo': {'id': '10644906845',
   'tags': {'tag': [{'_content': 'srilanka',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-23098',
      'machine_tag': 0,
      'raw': 'sri lanka'},
     {'_content': 'navy',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-7137',
      'machine_tag': 0,
      'raw': 'navy'},
     {'_content': 'vessel',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-8792',
      'machine_tag': 0,
      'raw': 'vessel'}]}},
  'stat': 'ok'},
      '11778819726': {'photo': {'id': '11778819726',
   'tags': {'tag': [{'_content': 'sri',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12165',
      'machine_tag': 0,
      'raw': 'sri'},
     {'_content': 'lanka',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12166',
      'machine_tag': 0,
      'raw': 'lanka'},
     {'_content': 'mirissa',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-1158107',
      'machine_tag': 0,
      'raw': 'mirissa'}]}},
  'stat': 'ok'}}

What I want is to extract the 'raw' words from each dictionary (e.g.result_dict_tag['10644906845']['photo']["tags"]['tag'][0]['raw']) and and create a dataframe consisting user id and relevant raw words for each user. I feel this need some for loop. I have written one and it only results the 'raw' words related to first user only. I have gone through documentation and various questions similar to this. But couldn't figure it out. Any help is appreciated.

Body:
You can extract these in a single list comprehension

raw_words = [mydict[i]['photo']["tags"]['tag'][k]['raw']
             for k in range(len(mydict[i]['photo']["tags"]['tag']))
             for i in mydict]

print(raw_words)
>> ['sri', 'sri lanka', 'lanka', 'navy', 'mirissa', 'vessel']