问:
Procedure is having some issue
I have a procedure test

```<code>alter Procedure [dbo].[test]
(
@Branch nvarchar(100)
)
AS
BEGIN

SELECT        res.f_Employee_Id AS Employee_Id, emp.f_Employee_Name, q.f_Question AS Question, ISNULL(ans.f_Name, res.f_Answer) AS Answer, CONVERT(nvarchar, res.f_Created_Date, 103) AS Feedback_Date,
                     emp.f_Grade AS Grade, emp.f_Branch_DESC AS Branch
FROM            T_PAF_EmployeeResult AS res WITH (nolock) LEFT OUTER JOIN
                     t_PAF_FeedbackAns_Master AS ans WITH (nolock) ON res.f_Answer = ans.f_Code INNER JOIN
                     t_PAF_FeedbackQues_Master AS q WITH (nolock) ON res.f_Question_Id = q.f_Uid INNER JOIN
                     T_PAF_EmployeeList_2017 AS emp WITH (nolock) ON emp.f_Employee_ID = res.f_Employee_Id
WHERE

((@Branch = emp.f_Branch_DESC) OR
                     (@Branch IS NULL)) and f_Company_Id=1031

ORDER BY Employee_Id, res.f_Question_Id
END
</code>```

exec test 'Head Office'

Output

```<code>Employee_Id f_Employee_Name     Question                                                            Answer          Feedback_Date   Grade   Branch

1234        XYZ         My appraiser is aware of all the work i am involved in.                                     Strongly Disagree   29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser tries to understand my point of view when he or she discusses problems or work  with me .              Disagree        29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser has good understanding of my strengths and weaknesses.                             Neutral         29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser gives me clear direction for the work that i am expected to do.                            Agree           29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser provides me with necessary support to resolve issues at work (team related/client related/schedule related etc).   Strongly Agree      29/06/2017  L10 C   HEAD OFFICE
</code>```

alter

```<code>alter Procedure [dbo].[test]
(
@Branch nvarchar(100)
)
AS
BEGIN

SELECT        res.f_Employee_Id AS Employee_Id, emp.f_Employee_Name, q.f_Question AS Question, ISNULL(ans.f_Name, res.f_Answer) AS Answer, CONVERT(nvarchar, res.f_Created_Date, 103) AS Feedback_Date,
                     emp.f_Grade AS Grade, emp.f_Branch_DESC AS Branch
FROM            T_PAF_EmployeeResult AS res WITH (nolock) LEFT OUTER JOIN
                     t_PAF_FeedbackAns_Master AS ans WITH (nolock) ON   res.f_Answer = ans.f_Code INNER JOIN
                     t_PAF_FeedbackQues_Master AS q WITH (nolock) ON res.f_Question_Id = q.f_Uid INNER JOIN
                     T_PAF_EmployeeList_2017 AS emp WITH (nolock) ON emp.f_Employee_ID = res.f_Employee_Id

WHERE

        ((@Branch = emp.f_Branch_DESC) OR
                     (@Branch IS NULL)) and f_Company_Id=1031
        and
        (
            ans.f_Name in ('Agree','Disagree') or res.f_Answer in ('Agree','Disagree')
        )

ORDER BY Employee_Id, res.f_Question_Id
END
</code>```

exec test 'Head Office'

Output is Blank

When i add this code in my procedure it is coming blank:

```<code>and
    (
        ans.f_Name in ('Agree','Disagree') or res.f_Answer in    ('Agree','Disagree')
    )
</code>```

答:
Try this in your condition</p>

```<code>and
(
      ISNULL(ans.f_Name, res.f_Answer) like '%Agree%'
)
</code>```

Title: Procedure is having some issue

Body:
I have a procedure test

alter Procedure [dbo].[test]
(
@Branch nvarchar(100)
)
AS
BEGIN

SELECT        res.f_Employee_Id AS Employee_Id, emp.f_Employee_Name, q.f_Question AS Question, ISNULL(ans.f_Name, res.f_Answer) AS Answer, CONVERT(nvarchar, res.f_Created_Date, 103) AS Feedback_Date,
                     emp.f_Grade AS Grade, emp.f_Branch_DESC AS Branch
FROM            T_PAF_EmployeeResult AS res WITH (nolock) LEFT OUTER JOIN
                     t_PAF_FeedbackAns_Master AS ans WITH (nolock) ON res.f_Answer = ans.f_Code INNER JOIN
                     t_PAF_FeedbackQues_Master AS q WITH (nolock) ON res.f_Question_Id = q.f_Uid INNER JOIN
                     T_PAF_EmployeeList_2017 AS emp WITH (nolock) ON emp.f_Employee_ID = res.f_Employee_Id
WHERE

((@Branch = emp.f_Branch_DESC) OR
                     (@Branch IS NULL)) and f_Company_Id=1031

ORDER BY Employee_Id, res.f_Question_Id
END

exec test 'Head Office'

Output

Employee_Id f_Employee_Name     Question                                                            Answer          Feedback_Date   Grade   Branch

1234        XYZ         My appraiser is aware of all the work i am involved in.                                     Strongly Disagree   29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser tries to understand my point of view when he or she discusses problems or work  with me .              Disagree        29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser has good understanding of my strengths and weaknesses.                             Neutral         29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser gives me clear direction for the work that i am expected to do.                            Agree           29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser provides me with necessary support to resolve issues at work (team related/client related/schedule related etc).   Strongly Agree      29/06/2017  L10 C   HEAD OFFICE

alter

alter Procedure [dbo].[test]
(
@Branch nvarchar(100)
)
AS
BEGIN

SELECT        res.f_Employee_Id AS Employee_Id, emp.f_Employee_Name, q.f_Question AS Question, ISNULL(ans.f_Name, res.f_Answer) AS Answer, CONVERT(nvarchar, res.f_Created_Date, 103) AS Feedback_Date,
                     emp.f_Grade AS Grade, emp.f_Branch_DESC AS Branch
FROM            T_PAF_EmployeeResult AS res WITH (nolock) LEFT OUTER JOIN
                     t_PAF_FeedbackAns_Master AS ans WITH (nolock) ON   res.f_Answer = ans.f_Code INNER JOIN
                     t_PAF_FeedbackQues_Master AS q WITH (nolock) ON res.f_Question_Id = q.f_Uid INNER JOIN
                     T_PAF_EmployeeList_2017 AS emp WITH (nolock) ON emp.f_Employee_ID = res.f_Employee_Id

WHERE

        ((@Branch = emp.f_Branch_DESC) OR
                     (@Branch IS NULL)) and f_Company_Id=1031
        and
        (
            ans.f_Name in ('Agree','Disagree') or res.f_Answer in ('Agree','Disagree')
        )

ORDER BY Employee_Id, res.f_Question_Id
END

exec test 'Head Office'

Output is Blank

When i add this code in my procedure it is coming blank:

and
    (
        ans.f_Name in ('Agree','Disagree') or res.f_Answer in    ('Agree','Disagree')
    )

Body:
Try this in your condition

and
(
      ISNULL(ans.f_Name, res.f_Answer) like '%Agree%'
)


来源: stackexchange

问:
calling ajax before submitting the form
I want to create a login screen in which,on the click of button the ajax verify the password and then then submit the form.but when i click submit button the form is submitted before the ajax call
in short the action method and ajax both call on the same button click,but i want to call ajax before action method

View

```<code>@using (Html.BeginForm("Login", "AccountAP", FormMethod.Post))

{

@Html.AntiForgeryToken()
        <div class="login-box">
            <div class="login-logo">
                <!-- /.login-logo -->
                <div class="login-box-body">
                    <center><a href="#"><img src="img/ra_logo.png" class="img-responsive" width="128" height="128" /></a></center>
                    <br />
                    <p class="login-box-msg" style="font-size:20px !important;">Sign in to start your session</p>
                    <div class="form-group has-feedback">
                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @placeholder = "Email" } })
                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                    </div>
                    <div class="form-group has-feedback">
                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @placeholder = "Password" } })
                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                    </div>

                    <div class="row">
                        <!-- /.col -->
                        <div class="col-xs-12">
                            <input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>
                        </div>
                        <!-- /.col -->
                    </div>
                </div>
                <!-- /.login-box-body -->
            </div>
        </div>
}
<script type="text/javascript">
        $('#btnSave').click(function (e) {
            e.preventDefault();
            e.alert("what's up");
        });
    </script>
</code>```

答:
I will suggest to capture the submit event on the form, instead of the click event on the submit button. Because people can not only submit your form by clicking the submit button, but also hitting the enter key in a textarea...etc

You will need to stop the default browser behavior of the submit event you capture so that whenever a for is submitted, browser won't post your form. In jQuery, you can stop default by doing event.preventDefault();

ContentLicense: CC BY-SA 3.0

Title: calling ajax before submitting the form

Body:
I want to create a login screen in which,on the click of button the ajax verify the password and then then submit the form.but when i click submit button the form is submitted before the ajax call
in short the action method and ajax both call on the same button click,but i want to call ajax before action method

View

@using (Html.BeginForm("Login", "AccountAP", FormMethod.Post))

{

@Html.AntiForgeryToken()

Sign in to start your session

                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @placeholder = "Email" } })
                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @placeholder = "Password" } })
                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                            <input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>

}


问:
Separate headers from sequences in fasta file without using Biopython
I have been trying to separate multiple DNA sequences from their header in a single fasta file by constructing a dictionary with Python 3.5 without using Biopython. I can not get it work right. Any suggestions would be appreciated. Thank you very much.
The header follows the sign '>'

Here is an example of a single fasta file:

```<code>>XM_021728176.1 PREDICTED: Ictidomys tridecemlineatus forkhead box N1 (Foxn1), transcript variant X1, mRNA
ATGGTGTCGCTACTCCCGCCACAGTCTGACGTCACGCTGCCTGGCCCCACCAGACTGGAGGGCGAGCCCC
AAGGGGACCTCATGCAGGCTCCGGGCCTCCCAGGCTCCCCTGCTCCACAGAGTAAGCACGCCGGCTTCAA
CTGCTCGTCATTTGTGCCCGACGGTCCTCCAGAGAGGGCACCCTCACTGCCCCCACACAGCCCGAGCATT
GCGTCACCAGGCCCCGAGCAAGTCCAGGGCCACTGCCCAGCCGGCCCTGGCCCAGGGCCTTTCCGGCTTT
CACCCTCAGATAAGTATCCTGGCTTTGGCTTTGAGGAGGGCCCAGCAAGCAGCCCTGGGCGCTACCTCAA
GGGCAACCACGTGCCCTTCCACCCATACAAGCGGCATTTCCATGAGGATATCTTCCCTGAAGCCCAGACC
GCCCTGGCCCTGGATGGACACTCCTTTAAGACCCCAGGGGCACTGGAGGCCTTTGAGGAGATCCCTGTGG
ACGTGGGGGAGGCCGAGGCCTTCCTGCCTGGTTTCCCTGCAGAGGCCTGGTGCAATGGGCTCCCTTACCC
CAGCCAGGAGCATGGCCAAGTCCTGCAGGCGTCAGAGGTCAAGATCAAGCCTCCAGCTCTGGAGAATGGT
CCTGGGATGTACTGCTACCAACCCCCCTTGCAGCACATGTACTGCCCTTCCCAGCCCCCTTTCCACCAGT
ATTCACAGGGTGGTGGCAGCTACCCTGTACCCTACCTGGGCTCCTCTCACTATCCATACCAGCGGATCGC
ACCCCAGGCCAGCGCTGATGGGCACCAGCCGCTCTTCCCCAAACCCATCTACTCCTACAGCATCCTCATC
TTCATGGCCCTCAAGAACAGCAAAACTGGAAGCCTGCCTGTCAGCGAGATCTACAATTTTATGACGGAGC

>XM_006532268.2 PREDICTED: Mus musculus forkhead box N1 (Foxn1), transcript variant X15, mRNA
CTCTCCAGGGAGACTCAGGATCAGGATGCTGCTGTGGAAGTGCAGAGAGCTCTGCTGACACAGCCTGGAA
TGGACAGCCTCGCCTGGCGCTGAGCCCCAAGGCCTCCCAGCTGCTCTGTGGTGCTGGGTCAGGGTTCTAC
AACAACAGTTCAGAAGGGGACTGGGTGATGGTGTCGCTACTCCCTCCGCAGTCTGACGTCACACTTCCAG
GCTCCACCCGACTGGAGGGCGAACCCCAAGGGGACCTCATGCAGGCTCCGGGCCTCCCAGACTCCCCTGC
CCCACAGAACCAGGGGTCAGAGGTCAAGGTCAAGCCCCAAGCTCTGGACAGTGGTCCTGGGATGTACTGC
TACCAGCCTCCCTTGCAACATATGTACTGTTCTTCTCAGCCTGCCTTCCATCAGTACTCCCCGGGTGGAG
GCAGCTACCCTGTGCCCTACCTGGGCTCACCTCACTATCCCTATCAGAGGATTGCACCCCAGGCCAACGC
CGAAGGTCACCAGCCACTCTTCCCAAAGCCCATCTACTCTTACAGCATCCTCATCTTCATGGCCCTTAAG
AACAGTAAGACCGGAAGCCTTCCAGTCAGTGAAATCTACAATTTCATGACGGAGCACTTCCCTTACTTCA
AGACTGCTCCTGATGGCTGGAAGAATTCTGTTCGCCATAACCTGTCCCTCAACAAGTGCTTTGAGAAGGT
GGAGAATAAATCCGGAAGTTCCTCTCGAAAGGGCTGTCTGTGGGCCCTCAATCCTTCCAAAATCGACAAG
ATGCAGGAAGAACTGCAGAAGTGGAAGAGGAAAGACCCCATTGCTGTGCGCAAAAGCATGGCCAAACCAG
AAGAGCTGGACAGCCTCATTGGAGACAAAAGGGAAAAACTGGGCTCTCCGCTGCTGGGCTGTCCACCCCC
TGGGCTGGCAGGCCCAGGTCCCATCCGGCCCATGGCACCATCAGCTGGTCTTTCCCAGCCTCTGCACCCA
</code>```

答:
How about the following:

```<code>import sys

sequences = {}

with open(sys.argv[1]) as fasta:
    header = None
    data = ''

    for line in fasta:
        if line.startswith('>'):
            if header and data:
                sequences[header] = data
            data = ''
            header = line.rstrip()
        else:
            data += line.rstrip()

    if header and data:
        sequences[header] = data  # deal with the last one in the file

for header, data in sequences.items():
    print('{}; {}bp'.format(header, len(data)))
</code>```

How would you analyze each record in the dictionary. Lets say you
  wanna count a number of letters in the sequence?

The code makes a dictionary with the headers as the keys and the concatenated data as the value.  I've added a loop to pull out the headers and data and print out the header with the data length.

Body:
I have been trying to separate multiple DNA sequences from their header in a single fasta file by constructing a dictionary with Python 3.5 without using Biopython. I can not get it work right. Any suggestions would be appreciated. Thank you very much.
The header follows the sign '>'

Here is an example of a single fasta file:

>XM_021728176.1 PREDICTED: Ictidomys tridecemlineatus forkhead box N1 (Foxn1), transcript variant X1, mRNA
ATGGTGTCGCTACTCCCGCCACAGTCTGACGTCACGCTGCCTGGCCCCACCAGACTGGAGGGCGAGCCCC
AAGGGGACCTCATGCAGGCTCCGGGCCTCCCAGGCTCCCCTGCTCCACAGAGTAAGCACGCCGGCTTCAA
CTGCTCGTCATTTGTGCCCGACGGTCCTCCAGAGAGGGCACCCTCACTGCCCCCACACAGCCCGAGCATT
GCGTCACCAGGCCCCGAGCAAGTCCAGGGCCACTGCCCAGCCGGCCCTGGCCCAGGGCCTTTCCGGCTTT
CACCCTCAGATAAGTATCCTGGCTTTGGCTTTGAGGAGGGCCCAGCAAGCAGCCCTGGGCGCTACCTCAA
GGGCAACCACGTGCCCTTCCACCCATACAAGCGGCATTTCCATGAGGATATCTTCCCTGAAGCCCAGACC
GCCCTGGCCCTGGATGGACACTCCTTTAAGACCCCAGGGGCACTGGAGGCCTTTGAGGAGATCCCTGTGG
ACGTGGGGGAGGCCGAGGCCTTCCTGCCTGGTTTCCCTGCAGAGGCCTGGTGCAATGGGCTCCCTTACCC
CAGCCAGGAGCATGGCCAAGTCCTGCAGGCGTCAGAGGTCAAGATCAAGCCTCCAGCTCTGGAGAATGGT
CCTGGGATGTACTGCTACCAACCCCCCTTGCAGCACATGTACTGCCCTTCCCAGCCCCCTTTCCACCAGT
ATTCACAGGGTGGTGGCAGCTACCCTGTACCCTACCTGGGCTCCTCTCACTATCCATACCAGCGGATCGC
ACCCCAGGCCAGCGCTGATGGGCACCAGCCGCTCTTCCCCAAACCCATCTACTCCTACAGCATCCTCATC
TTCATGGCCCTCAAGAACAGCAAAACTGGAAGCCTGCCTGTCAGCGAGATCTACAATTTTATGACGGAGC

>XM_006532268.2 PREDICTED: Mus musculus forkhead box N1 (Foxn1), transcript variant X15, mRNA
CTCTCCAGGGAGACTCAGGATCAGGATGCTGCTGTGGAAGTGCAGAGAGCTCTGCTGACACAGCCTGGAA
TGGACAGCCTCGCCTGGCGCTGAGCCCCAAGGCCTCCCAGCTGCTCTGTGGTGCTGGGTCAGGGTTCTAC
AACAACAGTTCAGAAGGGGACTGGGTGATGGTGTCGCTACTCCCTCCGCAGTCTGACGTCACACTTCCAG
GCTCCACCCGACTGGAGGGCGAACCCCAAGGGGACCTCATGCAGGCTCCGGGCCTCCCAGACTCCCCTGC
CCCACAGAACCAGGGGTCAGAGGTCAAGGTCAAGCCCCAAGCTCTGGACAGTGGTCCTGGGATGTACTGC
TACCAGCCTCCCTTGCAACATATGTACTGTTCTTCTCAGCCTGCCTTCCATCAGTACTCCCCGGGTGGAG
GCAGCTACCCTGTGCCCTACCTGGGCTCACCTCACTATCCCTATCAGAGGATTGCACCCCAGGCCAACGC
CGAAGGTCACCAGCCACTCTTCCCAAAGCCCATCTACTCTTACAGCATCCTCATCTTCATGGCCCTTAAG
AACAGTAAGACCGGAAGCCTTCCAGTCAGTGAAATCTACAATTTCATGACGGAGCACTTCCCTTACTTCA
AGACTGCTCCTGATGGCTGGAAGAATTCTGTTCGCCATAACCTGTCCCTCAACAAGTGCTTTGAGAAGGT
GGAGAATAAATCCGGAAGTTCCTCTCGAAAGGGCTGTCTGTGGGCCCTCAATCCTTCCAAAATCGACAAG
ATGCAGGAAGAACTGCAGAAGTGGAAGAGGAAAGACCCCATTGCTGTGCGCAAAAGCATGGCCAAACCAG
AAGAGCTGGACAGCCTCATTGGAGACAAAAGGGAAAAACTGGGCTCTCCGCTGCTGGGCTGTCCACCCCC
TGGGCTGGCAGGCCCAGGTCCCATCCGGCCCATGGCACCATCAGCTGGTCTTTCCCAGCCTCTGCACCCA

Body:
How about the following:

import sys

sequences = {}

with open(sys.argv[1]) as fasta:
    header = None
    data = ''

    for line in fasta:
        if line.startswith('>'):
            if header and data:
                sequences[header] = data
            data = ''
            header = line.rstrip()
        else:
            data += line.rstrip()

    if header and data:
        sequences[header] = data  # deal with the last one in the file

for header, data in sequences.items():
    print('{}; {}bp'.format(header, len(data)))

How would you analyze each record in the dictionary. Lets say you
  wanna count a number of letters in the sequence?

The code makes a dictionary with the headers as the keys and the concatenated data as the value.  I've added a loop to pull out the headers and data and print out the header with the data length.


问:
evaluating else if after an if condition is true
Consider this snippet:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}
</code>```

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

答: Because you are using else if instead of another if.</p>

ContentLicense: CC BY-SA 2.5

Body:
Consider this snippet:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?


问:
CSS code for select option tag
I have an form in my index page where i used same css code for input and select but the problem is that in input tag its working fine as per i want but in the select tag firstly width became little small and in when i am selecting the option its not getting selected though in MAC chrome its working fine but in  windows chrome its not getting selected!!

Please check my code and let me know where i went wrong!

#contact-form input[type="text"],
#contact-form select[type="text"],
#contact-form textarea {
  width: 247px;
  max-width: 100%;
  padding: 16px 10px;
  background: #4f5662;
  border: 1px solid #828fac;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  box-sizing: content-box;
  -moz-border-radius: 5px;
  -o-border-radius: 5px;
  color: #b6b7b8;
  font-size: 14px;
  font-family: helvetica;
  box-shadow: none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  -o-box-shadow: none;
  margin-right: 18px;
}

#contact-form input[type="submit"],
.newsleter-widget input[type="submit"] {
  float: right;
  font-size: 14px;
  color: #fff;
  font-family: 'Noto Sans', sans-serif;
  text-transform: uppercase;
  background: #8248ac;
  padding: 20px 13px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -o-border-radius: 5px;
  border: none;
}

#contact-form input[type="text"],
#contact-form select[type="text"],
#contact-form2 textarea {
  margin-right: 0;
  display: block;
  width: 94%;
  max-width: 94%;
  margin-bottom: 19px;
  padding: 16px 3%
}

#contact-form textarea,
#contact-form2 textarea {
  height: 110px;
  padding: 8px 3%;
}

#contact-form input[type="submit"],
#contact-form2 input[type="submit"] {
  display: block;
  float: right;
  padding: 20px 38px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="span4">
  <h3>Contact Form</h3>
  <form id="contact-form">
    <input type="text" name="name" class="name" placeholder="Name">
    <input type="text" name="email" class="email" placeholder="Email address">
    <input type="text" name="email" class="email" placeholder="Phone no">
    <select type="text" name="service">
    <option value="" selected >Select Services</option>
    <option value="" >Option 1</option>
    <option value="" >Option 2</option>
    <option value="" >Option 3</option>
  </select>
    <input type="submit" name="submit-form" id="submit" value="Send Message">
  </form>
</div></code>```

When i pasted code here also , the option tag is getting selected though but in my code its not getting selected!! but still here also width of the select tag is still little smaller as compared to input tag.

Now its looks like this

答:
You must use box-sizing property to what should be included in sizing properties (width and height)
For your issue box-sizing: border-box and some modification in width and margin property will do the task.

Here is the fiddle for same https://jsfiddle.net/c7Lojau2/

Title: CSS code for select option tag

Body:
I have an form in my index page where i used same css code for input and select but the problem is that in input tag its working fine as per i want but in the select tag firstly width became little small and in when i am selecting the option its not getting selected though in MAC chrome its working fine but in  windows chrome its not getting selected!!

Please check my code and let me know where i went wrong!

#contact-form input[type="text"],
#contact-form select[type="text"],
#contact-form textarea {
  width: 247px;
  max-width: 100%;
  padding: 16px 10px;
  background: #4f5662;
  border: 1px solid #828fac;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  box-sizing: content-box;
  -moz-border-radius: 5px;
  -o-border-radius: 5px;
  color: #b6b7b8;
  font-size: 14px;
  font-family: helvetica;
  box-shadow: none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  -o-box-shadow: none;
  margin-right: 18px;
}

#contact-form input[type="submit"],
.newsleter-widget input[type="submit"] {
  float: right;
  font-size: 14px;
  color: #fff;
  font-family: 'Noto Sans', sans-serif;
  text-transform: uppercase;
  background: #8248ac;
  padding: 20px 13px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -o-border-radius: 5px;
  border: none;
}

#contact-form input[type="text"],
#contact-form select[type="text"],
#contact-form2 textarea {
  margin-right: 0;
  display: block;
  width: 94%;
  max-width: 94%;
  margin-bottom: 19px;
  padding: 16px 3%
}

#contact-form textarea,
#contact-form2 textarea {
  height: 110px;
  padding: 8px 3%;
}

#contact-form input[type="submit"],
#contact-form2 input[type="submit"] {
  display: block;
  float: right;
  padding: 20px 38px;
}

Contact Form

  <form id="contact-form">
    <input type="text" name="name" class="name" placeholder="Name">
    <input type="text" name="email" class="email" placeholder="Email address">
    <input type="text" name="email" class="email" placeholder="Phone no">
    <select type="text" name="service">
    <option value="" selected >Select Services</option>
    <option value="" >Option 1</option>
    <option value="" >Option 2</option>
    <option value="" >Option 3</option>
  </select>
    <input type="submit" name="submit-form" id="submit" value="Send Message">
  </form>

When i pasted code here also , the option tag is getting selected though but in my code its not getting selected!! but still here also width of the select tag is still little smaller as compared to input tag.

Now its looks like this


问:
CSS code use to make sure that only 2 line sentence to display is not working for IE
I have the following css code to make sure that the display sentence is not more then 2 line, if so it will replace the rest of the word to "..."

```<code>   .bell-notification-max-words-display{
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
</code>```

This working fine for chrome, safari and mozilla. However, it's not working for IE. When I inspect the element, error showing like below:

Does anyone know how can I make it work for IE?

答:
The vendor prefix -webkit means that this is specific to the webkit engine which IE does not use. That's why it doesn't work.

You can get the desired result with a bit of line-height tweaking. - Read more about line-height - and by also using overflow: hidden;

Setting  overflow to hidden means the content will be trimmed if it exceeds the dimensions of the div:

Working example:

.parent {
  font-size:16px;
  height: 36px; /* 2x "font-size" +4px clearing */
  line-height: 36px; /* should match your parent div height */
  width: 90%;
  overflow: hidden;
  margin-top: 20px;
}

.child {
  display: inline-block;
  vertical-align: middle;
  line-height: normal; /* reset line height here it here */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">
    Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
    te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.
  </div>
</div></code>```

There also another method in which you use a reset html textarea element.

Working example:

textarea {
  all: unset;
  width: 100%
}

.sample {
  overflow: hidden;
  max-width: 80%;
  overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="sample" rows="2">
Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
    te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.
</textarea></code>```

Unfortunately neither methods support ellipsis or "..."

I don't think there are any "non-hacky" methods of combining ellipsis and overflow using CSS alone unless you use hacks or scripts.

An example of such hacks is to use pseudo-elements (this only works if the text is justified)

.sample {
  max-width: 80%;
  overflow: hidden;
  position: relative;
  max-height: 2.2em;
  text-align: justify;
  padding-right: .75em;
}

.sample:before {
  content: "...";
  position: absolute;
  right: 0;
  bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sample">
  Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
  te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.
</div></code>```

Body:
I have the following css code to make sure that the display sentence is not more then 2 line, if so it will replace the rest of the word to "..."

   .bell-notification-max-words-display{
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

This working fine for chrome, safari and mozilla. However, it's not working for IE. When I inspect the element, error showing like below:

Does anyone know how can I make it work for IE?

Body:
The vendor prefix -webkit means that this is specific to the webkit engine which IE does not use. That's why it doesn't work.

You can get the desired result with a bit of line-height tweaking. - Read more about line-height - and by also using overflow: hidden;

Setting  overflow to hidden means the content will be trimmed if it exceeds the dimensions of the div:

Working example:

.parent {
  font-size:16px;
  height: 36px; /* 2x "font-size" +4px clearing */
  line-height: 36px; /* should match your parent div height */
  width: 90%;
  overflow: hidden;
  margin-top: 20px;
}

.child {
  display: inline-block;
  vertical-align: middle;
  line-height: normal; /* reset line height here it here */
}

<div class="parent">
  <div class="child">
    Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
    te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.
  </div>
</div>

There also another method in which you use a reset html textarea element.

Working example:

textarea {
  all: unset;
  width: 100%
}

.sample {
  overflow: hidden;
  max-width: 80%;
  overflow: ellipsis;
}

<textarea class="sample" rows="2">
Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
    te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.
</textarea>

Unfortunately neither methods support ellipsis or "..."

I don't think there are any "non-hacky" methods of combining ellipsis and overflow using CSS alone unless you use hacks or scripts.

An example of such hacks is to use pseudo-elements (this only works if the text is justified)

.sample {
  max-width: 80%;
  overflow: hidden;
  position: relative;
  max-height: 2.2em;
  text-align: justify;
  padding-right: .75em;
}

.sample:before {
  content: "...";
  position: absolute;
  right: 0;
  bottom: 0;
}

<div class="sample">
  Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
  te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.
</div>


问:
Counting number of words in Python file
I'm trying to count the number of instances several words appear in a file.

Here is my code:

```<code>#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))
</code>```

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

答:
in your code the file is consumed (exhausted) in the first line so the next lines will not return anything to count: the first file.read() reads the whole contents of the file and returns it as a string. the second file.read() has nothing left to read and just returns an empty string '' - as does the third file.read() .

this is a version that should do what you want:

```<code>from collections import Counter

counter = Counter()

with open('my_output', 'r') as file:
    for line in file:
        counter.update(line.split())
print(counter)
</code>```

you may have to do some preprocessing (in order to get rid of special characters and , and . and what not).

Counter is in the python standard library and is very useful for exactly that kind of thing.

note that this way you iterate once over the file only and you do not have to store the whole file in memory at any time.

if you only want to keep track of certain words you could select only them instead of passing the whole line to a counter:

```<code>from collections import Counter
import string

counter = Counter()

words = ('wordA', 'wordB', 'wordC')
chars_to_remove = str.maketrans('', '', string.punctuation)

with open('my_output', 'r') as file:
    for line in file:
        line = line.translate(chars_to_remove)
        w = (word for word in line.split() if word in words)
        counter.update(w)
print(counter)
</code>```

i also included an example of what i meant with preprocessing: punctuation will be removed before counting.

Title: Counting number of words in Python file

Body:
I'm trying to count the number of instances several words appear in a file.

Here is my code:

#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

Body:
in your code the file is consumed (exhausted) in the first line so the next lines will not return anything to count: the first file.read() reads the whole contents of the file and returns it as a string. the second file.read() has nothing left to read and just returns an empty string '' - as does the third file.read() .

this is a version that should do what you want:

from collections import Counter

counter = Counter()

with open('my_output', 'r') as file:
    for line in file:
        counter.update(line.split())
print(counter)

you may have to do some preprocessing (in order to get rid of special characters and , and . and what not).

Counter is in the python standard library and is very useful for exactly that kind of thing.

note that this way you iterate once over the file only and you do not have to store the whole file in memory at any time.

if you only want to keep track of certain words you could select only them instead of passing the whole line to a counter:

from collections import Counter
import string

counter = Counter()

words = ('wordA', 'wordB', 'wordC')
chars_to_remove = str.maketrans('', '', string.punctuation)

with open('my_output', 'r') as file:
    for line in file:
        line = line.translate(chars_to_remove)
        w = (word for word in line.split() if word in words)
        counter.update(w)
print(counter)

i also included an example of what i meant with preprocessing: punctuation will be removed before counting.


问:
Merge First name with Last name using Applescript
I'm using MacBook. In the application "Contacts", I've managed the people's name like this. The first name is in the first name field, the Last name is in last name field. But now I want to change this format. First name and last name together is in the First name field and not using Last name field.

In my contacts, I have more than 1,000 contacts' information. If I do this task one by one with my hand, it will take too much time. So, I want to make Applescript do this task automatically. But unfortunately, I do not know the grammar of Applescript. Please help me to handle this job easily without time wasting.

答:
insert sigh here

If this wasn't AppleScript, a language that's syntax is pretty much all english words, I would understand if you don't understand the syntax.

It's a really easy language to understand because of this.

Back to the question,
Doing a Google search for "Change contacts with AppleScript", the first result is this.
In less than 3 minutes, without any prior knowledge to automating Contacts, I put together a short script that does what you've asked for.

The first code snippet on the page is all I needed,

```<code>tell application "Address Book"
    set peopleToChange to people whose (street of first address) contains "321 Old Street"
    repeat with thePerson in peopleToChange
        set (street of first address) of thePerson to "123 New Street"
    end repeat
    save
end tell
</code>```

All I had to do was use common sense to know that "first name" and "last name" would be the property to automate them.

I just changed the name of the properties and what I was doing with them using this code snippet, and the result:

```<code>tell application "Contacts"
    set peopleToChange to people whose (last name) is not equal to ""
    repeat with thePerson in peopleToChange
        set first name of thePerson to first name of thePerson & " " & (last name) of thePerson
        set (last name) of thePerson to ""
    end repeat
    save
end tell
</code>```

I've tested it, and it works.

For the future, spend more time trying before asking a question, you'll get negative reputation.

Body:
insert sigh here

If this wasn't AppleScript, a language that's syntax is pretty much all english words, I would understand if you don't understand the syntax.

It's a really easy language to understand because of this.

Back to the question,
Doing a Google search for "Change contacts with AppleScript", the first result is this.
In less than 3 minutes, without any prior knowledge to automating Contacts, I put together a short script that does what you've asked for.

The first code snippet on the page is all I needed,

tell application "Address Book"
    set peopleToChange to people whose (street of first address) contains "321 Old Street"
    repeat with thePerson in peopleToChange
        set (street of first address) of thePerson to "123 New Street"
    end repeat
    save
end tell

All I had to do was use common sense to know that "first name" and "last name" would be the property to automate them.

I just changed the name of the properties and what I was doing with them using this code snippet, and the result:

tell application "Contacts"
    set peopleToChange to people whose (last name) is not equal to ""
    repeat with thePerson in peopleToChange
        set first name of thePerson to first name of thePerson & " " & (last name) of thePerson
        set (last name) of thePerson to ""
    end repeat
    save
end tell

I've tested it, and it works.

For the future, spend more time trying before asking a question, you'll get negative reputation.


问:
PHP function trim() not stripping whitespace from the middle of the string
I have some pretty straight-forward code, but something's going wrong. The following code

```<code>$title = $_POST['templatename'];
$user = $_POST['username'];
$selectedcoordinates = $_POST['templatestring'];

$title = trim($title);
$user = trim($user);

$filename = $title . "_by_" . $user;

var_dump($title);
var_dump($user);
var_dump($filename);
</code>```

returns this:

```<code>string(11) "Single Tile"
string(6) "Author"
string(21) "Single Tile_by_Author"
</code>```

where the values originate from a HTML form. Why doesn't "Single Tile" become "SingleTile"?

答:
The answer is quite simple. First you need to have a basic understanding of what the function trim() does.

The syntax of the function is:

trim(string,charlist);

The second parameter is optional. If present it removes the characters present in charlist  from both ends of the string.

Example:

```<code>$str="beautiful day";
echo trim($str, "aby");
</code>```

Output:

```<code>eautiful d
</code>```

The letters a , b and y gets removed from both ends of the string

However, if the second parameter is omitted then the following characters are removed from both ends of the string.

```<code>"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - ordinary white space
</code>```

In your case the output is:

```<code>string(11) "Single Tile" string(6) "Author" string(21) "Single Tile_by_Author"
</code>```

The space between Single and Tile_by_Author remains as white spaces are removed from both ends only

Body:
I have some pretty straight-forward code, but something's going wrong. The following code

$title = $_POST['templatename'];
$user = $_POST['username'];
$selectedcoordinates = $_POST['templatestring'];

$title = trim($title);
$user = trim($user);

$filename = $title . "_by_" . $user;

var_dump($title);
var_dump($user);
var_dump($filename);

returns this:

string(11) "Single Tile"
string(6) "Author"
string(21) "Single Tile_by_Author"

where the values originate from a HTML form. Why doesn't "Single Tile" become "SingleTile"?

Body:
The answer is quite simple. First you need to have a basic understanding of what the function trim() does.

The syntax of the function is:

trim(string,charlist);

The second parameter is optional. If present it removes the characters present in charlist  from both ends of the string.

Example:

$str="beautiful day";
echo trim($str, "aby");

Output:

eautiful d

The letters a , b and y gets removed from both ends of the string

However, if the second parameter is omitted then the following characters are removed from both ends of the string.

"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - ordinary white space

In your case the output is:

string(11) "Single Tile" string(6) "Author" string(21) "Single Tile_by_Author"

The space between Single and Tile_by_Author remains as white spaces are removed from both ends only


问:
how to stable hover effect even after mouse out
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

```<code><div id="sme"></div>
</code>```

css

```<code>#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}
</code>```

答:
Transition must be put in the normal state.

#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  transition: all 1.9s ease;
}

#sme:hover {
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  transform: rotate(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sme"></div></code>```

Edit : Indeed, if you want it to keep the state, i suggest to change #sme:hover by .hovered and add this class in js to your #sme when you hover it.

Body:
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

css

#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}

Body:
Transition must be put in the normal state.

#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  transition: all 1.9s ease;
}

#sme:hover {
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  transform: rotate(180deg);
}

<div id="sme"></div>

Edit : Indeed, if you want it to keep the state, i suggest to change #sme:hover by .hovered and add this class in js to your #sme when you hover it.


问:
want to build web site by django for take a value by Temperature sensor on particle-Photon
i want to build an web site by djnago. this site could be able to take values from Temperature sensor which is connection with my particle-Photon. i checked the net but i do not found an compatible libary Which could be connect my Photon and django framwork. is there any helpful libary to do this .
my "Temperature.ino" code:</p>

```<code>#include <OneWire.h>
OneWire ds = OneWire(D4);  // 1-wire signal on pin D4

unsigned long lastUpdate = 0;

float lastTemp;

void setup() {
  Serial.begin(9600);
  // Set up 'power' pins, comment out if not used!
  pinMode(D3, OUTPUT);
  pinMode(D5, OUTPUT);
  digitalWrite(D3, LOW);
  digitalWrite(D5, HIGH);
}

// up to here, it is the same as the address acanner
// we need a few more variables for this example

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  // The order is changed a bit in this example
  // first the returned address is printed

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  // second the CRC is checked, on fail,
  // print error and just return to try again

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // we have a good address at this point
  // what kind of chip do we have?
  // we will set a type_s value for known types or just return

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS1820/DS18S20");
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    case 0x26:
      Serial.println("  Chip = DS2438");
      type_s = 2;
      break;
    default:
      Serial.println("Unknown device type.");
      return;
  }

  // this device has temp so let's read it

  ds.reset();               // first clear the 1-wire bus
  ds.select(addr);          // now select the device we just found
  // ds.write(0x44, 1);     // tell it to start a conversion, with parasite power on at the end
  ds.write(0x44, 0);        // or start conversion in powered mode (bus finishes low)

  // just wait a second while the conversion takes place
  // different chips have different conversion times, check the specs, 1 sec is worse case + 250ms
  // you could also communicate with other devices if you like but you would need
  // to already know their address to select them.

  delay(1000);     // maybe 750ms is enough, maybe not, wait 1 sec for conversion

  // we might do a ds.depower() (parasite) here, but the reset will take care of it.

  // first make sure current values are in the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xB8,0);         // Recall Memory 0
  ds.write(0x00,0);         // Recall Memory 0

  // now read the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE,0);         // Read Scratchpad
  if (type_s == 2) {
    ds.write(0x00,0);       // The DS2438 needs a page# to read
  }

  // transfer and print the values

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s == 2) raw = (data[2] << 8) | data[1];
  byte cfg = (data[4] & 0x60);

  switch (type_s) {
    case 1:
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
      celsius = (float)raw * 0.0625;
      break;
    case 0:
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      // default is 12 bit resolution, 750 ms conversion time
      celsius = (float)raw * 0.0625;
      break;

    case 2:
      data[1] = (data[1] >> 3) & 0x1f;
      if (data[2] > 127) {
        celsius = (float)data[2] - ((float)data[1] * .03125);
      }else{
        celsius = (float)data[2] + ((float)data[1] * .03125);
      }
  }

  // remove random errors
  if((((celsius <= 0 && celsius > -1) && lastTemp > 5)) || celsius > 125) {
      celsius = lastTemp;
  }

  fahrenheit = celsius * 1.8 + 32.0;
  lastTemp = celsius;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  // now that we have the readings, we can publish them to the cloud
  String temperature = String(fahrenheit); // store temp in "temperature" string
  Particle.publish("temperature", temperature, PRIVATE); // publish to cloud
  delay(5000); // 5 second delay
}
</code>```

答:
I think you can send data through HTTP from your photon(mostly, I've heard of it), and using HTTP calls you can push data to your Django application.

On Django side, use djangorestfraework for building APIs.

Body:
i want to build an web site by djnago. this site could be able to take values from Temperature sensor which is connection with my particle-Photon. i checked the net but i do not found an compatible libary Which could be connect my Photon and django framwork. is there any helpful libary to do this .
my "Temperature.ino" code:

#include <OneWire.h>
OneWire ds = OneWire(D4);  // 1-wire signal on pin D4

unsigned long lastUpdate = 0;

float lastTemp;

void setup() {
  Serial.begin(9600);
  // Set up 'power' pins, comment out if not used!
  pinMode(D3, OUTPUT);
  pinMode(D5, OUTPUT);
  digitalWrite(D3, LOW);
  digitalWrite(D5, HIGH);
}

// up to here, it is the same as the address acanner
// we need a few more variables for this example

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  // The order is changed a bit in this example
  // first the returned address is printed

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  // second the CRC is checked, on fail,
  // print error and just return to try again

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // we have a good address at this point
  // what kind of chip do we have?
  // we will set a type_s value for known types or just return

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS1820/DS18S20");
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    case 0x26:
      Serial.println("  Chip = DS2438");
      type_s = 2;
      break;
    default:
      Serial.println("Unknown device type.");
      return;
  }

  // this device has temp so let's read it

  ds.reset();               // first clear the 1-wire bus
  ds.select(addr);          // now select the device we just found
  // ds.write(0x44, 1);     // tell it to start a conversion, with parasite power on at the end
  ds.write(0x44, 0);        // or start conversion in powered mode (bus finishes low)

  // just wait a second while the conversion takes place
  // different chips have different conversion times, check the specs, 1 sec is worse case + 250ms
  // you could also communicate with other devices if you like but you would need
  // to already know their address to select them.

  delay(1000);     // maybe 750ms is enough, maybe not, wait 1 sec for conversion

  // we might do a ds.depower() (parasite) here, but the reset will take care of it.

  // first make sure current values are in the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xB8,0);         // Recall Memory 0
  ds.write(0x00,0);         // Recall Memory 0

  // now read the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE,0);         // Read Scratchpad
  if (type_s == 2) {
    ds.write(0x00,0);       // The DS2438 needs a page# to read
  }

  // transfer and print the values

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s == 2) raw = (data[2] << 8) | data[1];
  byte cfg = (data[4] & 0x60);

  switch (type_s) {
    case 1:
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
      celsius = (float)raw * 0.0625;
      break;
    case 0:
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      // default is 12 bit resolution, 750 ms conversion time
      celsius = (float)raw * 0.0625;
      break;

    case 2:
      data[1] = (data[1] >> 3) & 0x1f;
      if (data[2] > 127) {
        celsius = (float)data[2] - ((float)data[1] * .03125);
      }else{
        celsius = (float)data[2] + ((float)data[1] * .03125);
      }
  }

  // remove random errors
  if((((celsius <= 0 && celsius > -1) && lastTemp > 5)) || celsius > 125) {
      celsius = lastTemp;
  }

  fahrenheit = celsius * 1.8 + 32.0;
  lastTemp = celsius;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  // now that we have the readings, we can publish them to the cloud
  String temperature = String(fahrenheit); // store temp in "temperature" string
  Particle.publish("temperature", temperature, PRIVATE); // publish to cloud
  delay(5000); // 5 second delay
}


答:
It will only reach the second part if the first one is false. If you want to check against both you should do this:

```<code> if (textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
</code>```

You can look at && like this:

```<code>if (A && B) {
    //do something
}
</code>```

is the same as

```<code>if (A) {
    if (B) {
        //do something
    }
}
</code>```

Title: evaluating else if after an if condition is true

Body:
It will only reach the second part if the first one is false. If you want to check against both you should do this:

 if (textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)

You can look at && like this:

if (A && B) {
    //do something
}

is the same as

if (A) {
    if (B) {
        //do something
    }
}


问:
(D3) dispatching "mousedown" event to selection with drag behaviour throws error
Title says pretty much all, trying to dispatch mousedown event to selection that have drag behaviour set up throws "TypeError: Cannot read property 'document' of undefined", example is in snippet.

I'm trying to think of some workaround, because I have to pass mousedown to element I add at mouse cursor to drag it without pressing mouse button twice. Any input is very appreciated.

d3.select('#dragable').call(d3.drag().on('drag', function() {
  d3.select(this).style('left', d3.event.x + 'px');
  d3.select(this).style('top', d3.event.y + 'px');
}))

d3.select('#dragable').dispatch('mousedown');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dragable {
  position: absolute;
  left: 0;
  top: 0;
  background: red;
  width: 50px;
  height: 50px;
}</code>```

```

EDIT:

I tinkered around in debugger, and it seems that when firing from dispatcher, CustomEvent object passed to d3-drag is missing view variable. So theoreticaly adding Window object to it could fix it. I have no idea though how to do it, or rather how to do it without modifying d3 source.

答: Turns out I was using wrong tool for the job, because selection.dispatch() is used for dispatching custom events. To dispatch mouse event I had to use .dispatchEvent(event) method with MouseEvent.

Body:
Title says pretty much all, trying to dispatch mousedown event to selection that have drag behaviour set up throws "TypeError: Cannot read property 'document' of undefined", example is in snippet.

I'm trying to think of some workaround, because I have to pass mousedown to element I add at mouse cursor to drag it without pressing mouse button twice. Any input is very appreciated.

d3.select('#dragable').call(d3.drag().on('drag', function() {
  d3.select(this).style('left', d3.event.x + 'px');
  d3.select(this).style('top', d3.event.y + 'px');
}))

d3.select('#dragable').dispatch('mousedown');

#dragable {
  position: absolute;
  left: 0;
  top: 0;
  background: red;
  width: 50px;
  height: 50px;
}

EDIT:

I tinkered around in debugger, and it seems that when firing from dispatcher, CustomEvent object passed to d3-drag is missing view variable. So theoreticaly adding Window object to it could fix it. I have no idea though how to do it, or rather how to do it without modifying d3 source.


问:
How to convert req.body to model in ES6 to match the database columns when using knex js? - Javascript
I am working on a node js with es6.
I have a table which has few fields. I am using knex js for query building and db management.
My Doubt is how can I set the fields by sending req.body object to es6 class constructor?
Eg.

```<code>class User {
  constructor(user_id, email, username, password, phone, first_name, last_name, created_at, created_by, updated_at, updated_by){
    this.user_id = user_id;
    this.email = email;
    this.username = username;
    this.password = password;
    this.phone = phone;
    this.first_name = first_name;
    this.last_name = last_name;
    this.created_at = created_at;
    this.created_by = created_by;
    this.updated_at = updated_at;
    this.updated_by = updated_by;
  }

  get _user_id(){
      return this.user_id;
  }

  set _user_id(user_id){
      this.user_id = user_id;
  }

  get _email(){
      return this.email;
  }

  set _email(email){
      this.email = email;
  }

  get _username(){
      return this.username;
  }

  set _username(username){
      this.username = username;
  }

  get _password(){
      return this.password;
  }

  set _password(password){
      this.password = password;
  }

  get _phone(){
      return this.phone;
  }

  set _phone(phone){
      this.phone = phone;
  }

  get _first_name(){
      return this.first_name;
  }

  set _first_name(first_name){
      this.first_name = first_name;
  }

  get _last_name(){
      return this.last_name;
  }

  set _last_name(last_name){
      this.last_name = last_name;
  }

  get _created_at(){
      return this.created_at;
  }

  set _created_at(created_at){
      this.created_at = created_at;
  }

  get _created_by(){
      return this.created_by;
  }

  set _created_by(created_by){
      this.created_by = created_by;
  }

  get _updated_at(){
      return this.updated_at;
  }

  set _updated_at(updated_at){
      this.updated_at = updated_at;
  }

  get _updated_by(){
      return this.updated_by;
  }

  set _updated_by(updated_by){
      this.updated_by = updated_by;
  }
}

export default User;
</code>```

In java we can do this with pojo objects.
and use User user = new User(arg1, arg2 ...);
In es6 using above code I can do let user = new User(arg1, arg2...);

Now I can use

```<code>knex.insert(user).then((data) => {
}, (err) =>{
});
</code>```

But is there a better way to create objects like this in es6?

答:
I prefer working with plain objects instead of wrapping them in classes. In your example you typed 105 lines of code that do pretty much nothing. And it's much easier working with raw data instead of abstractions around it.

So basically my recipe is:

Working with class/wrapper around data object → working with data object itself

get myField → object.myField

set myField → object.myField = myValue

And your example becomes trivial

```<code>knex('users')
    .insert(req.body) // Or you may want to cleanup body before inserting or smth.
    .returning('*')
    .then((data) => {
        data.password = null;
        console.log('User created %j', data)
        res.json(data).status(200)
    })
</code>```

Body:
I am working on a node js with es6.
I have a table which has few fields. I am using knex js for query building and db management.
My Doubt is how can I set the fields by sending req.body object to es6 class constructor?
Eg.

class User {
  constructor(user_id, email, username, password, phone, first_name, last_name, created_at, created_by, updated_at, updated_by){
    this.user_id = user_id;
    this.email = email;
    this.username = username;
    this.password = password;
    this.phone = phone;
    this.first_name = first_name;
    this.last_name = last_name;
    this.created_at = created_at;
    this.created_by = created_by;
    this.updated_at = updated_at;
    this.updated_by = updated_by;
  }

  get _user_id(){
      return this.user_id;
  }

  set _user_id(user_id){
      this.user_id = user_id;
  }

  get _email(){
      return this.email;
  }

  set _email(email){
      this.email = email;
  }

  get _username(){
      return this.username;
  }

  set _username(username){
      this.username = username;
  }

  get _password(){
      return this.password;
  }

  set _password(password){
      this.password = password;
  }

  get _phone(){
      return this.phone;
  }

  set _phone(phone){
      this.phone = phone;
  }

  get _first_name(){
      return this.first_name;
  }

  set _first_name(first_name){
      this.first_name = first_name;
  }

  get _last_name(){
      return this.last_name;
  }

  set _last_name(last_name){
      this.last_name = last_name;
  }

  get _created_at(){
      return this.created_at;
  }

  set _created_at(created_at){
      this.created_at = created_at;
  }

  get _created_by(){
      return this.created_by;
  }

  set _created_by(created_by){
      this.created_by = created_by;
  }

  get _updated_at(){
      return this.updated_at;
  }

  set _updated_at(updated_at){
      this.updated_at = updated_at;
  }

  get _updated_by(){
      return this.updated_by;
  }

  set _updated_by(updated_by){
      this.updated_by = updated_by;
  }
}

export default User;

In java we can do this with pojo objects.
and use User user = new User(arg1, arg2 ...);
In es6 using above code I can do let user = new User(arg1, arg2...);

Now I can use

knex.insert(user).then((data) => {
}, (err) =>{
});

But is there a better way to create objects like this in es6?

Body:
I prefer working with plain objects instead of wrapping them in classes. In your example you typed 105 lines of code that do pretty much nothing. And it's much easier working with raw data instead of abstractions around it.

So basically my recipe is:

Working with class/wrapper around data object → working with data object itself

get myField → object.myField

set myField → object.myField = myValue

And your example becomes trivial

knex('users')
    .insert(req.body) // Or you may want to cleanup body before inserting or smth.
    .returning('*')
    .then((data) => {
        data.password = null;
        console.log('User created %j', data)
        res.json(data).status(200)
    })


问:
swift: How to take screenshot of AVPlayerLayer()
How to take screenshot of AVplayerLayer. I tried with the following code it works well, it captures the entire view as it was

```<code>func screenShotMethod() {
    let window = UIApplication.shared.delegate!.window!!
    //capture the entire window into an image
    UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
    window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
    let windowImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //now position the image x/y away from the top-left corner to get the portion we want
    UIGraphicsBeginImageContext(view.frame.size)
    windowImage?.draw(at: CGPoint(x: -view.frame.origin.x, y: -view.frame.origin.y))
    let croppedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext();
    //embed image in an imageView, supports transforms.
    let resultImageView = UIImageView(image: croppedImage)
    UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, nil)
}
</code>```

But the problem is when i tried the same code running on iPhone(device) it returns black image.i don't know what was wrong

Any suggestions would be greatly helpful!

答:
A few days ago, we also ran into the same issue. Where, if we take the screenshot of a screen which has a video player in it; The screenshot looks fine in the simulator.But, on the device, it was a black screen.

After a lot of attempts, I failed and finally end up with a patch (not sure if it is a correct way of solving the problem). But, the solution did the trick and I was able to get the screenshot on the device as well and simulator as well.

Following is a way I used to solve the issue.

1 -> Get a single frame at current time from the video (Public method is already available for this)

2 -> Use this thumbnail in the place of CALayer (add it to hierarchy)

3 -> Once we are done remove the thumbnail from the memory (remove from hierarchy)

Following is a demo sample for the same (The given solution is in Objective-c though the question asked is in Swift).

Objective - C solution

```<code>  - (void)SnapShot {
       UIImage *capturedImage = [self getASnapShotWithAVLayer];
    }
    - (UIImage *)getASnapShotWithAVLayer {
        //Add temporary thumbnail One
        UIImageView *temporaryViewForVideoOne = [[UIImageView alloc] initWithFrame:self.videoViewOne.bounds];
        temporaryViewForVideoOne.contentMode = UIViewContentModeScaleAspectFill;
        UIImage *imageFromCurrentTimeForVideoOne = [self takeVideoSnapShot:_playerItem1];
        int orientationFromVideoForVideoOne = [self getTheActualOrientationOfVideo:self.playerItem1];
        if(orientationFromVideoForVideoOne == 0)
        {
            orientationFromVideoForVideoOne = 3;
        }
        else if (orientationFromVideoForVideoOne == 90)
        {
            orientationFromVideoForVideoOne = 0;
        }
        imageFromCurrentTimeForVideoOne =
        [UIImage imageWithCGImage:[imageFromCurrentTimeForVideoOne CGImage]
                            scale:[imageFromCurrentTimeForVideoOne scale]
                      orientation: orientationFromVideoForVideoOne];
        UIImage *rotatedImageFromCurrentContextForVideoOne = [self normalizedImage:imageFromCurrentTimeForVideoOne];
        temporaryViewForVideoOne.clipsToBounds = YES;
        temporaryViewForVideoOne.image = rotatedImageFromCurrentContextForVideoOne;
        [self.videoViewOne addSubview:temporaryViewForVideoOne];
        CGSize imageSize = CGSizeZero;
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        if (UIInterfaceOrientationIsPortrait(orientation)) {
            imageSize = [UIScreen mainScreen].bounds.size;
        } else {
            imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
        }

        UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]);
        CGContextRef context = UIGraphicsGetCurrentContext();
        for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, window.center.x, window.center.y);
            CGContextConcatCTM(context, window.transform);
            CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
            if (orientation == UIInterfaceOrientationLandscapeLeft) {
                CGContextRotateCTM(context, M_PI_2);
                CGContextTranslateCTM(context, 0, -imageSize.width);
            } else if (orientation == UIInterfaceOrientationLandscapeRight) {
                CGContextRotateCTM(context, -M_PI_2);
                CGContextTranslateCTM(context, -imageSize.height, 0);
            } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
                CGContextRotateCTM(context, M_PI);
                CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
            }
            if (![window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
                [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
            } else {
                [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
            }
            CGContextRestoreGState(context);
        }
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [temporaryViewForVideoOne removeFromSuperview];
        [temporaryViewForVideoTwo removeFromSuperview];
        return image;
    }
    -(UIImage *)takeVideoSnapShot: (AVPlayerItem *) playerItem{
        AVURLAsset *asset = (AVURLAsset *) playerItem.asset;
        AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
        imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
        CGImageRef thumb = [imageGenerator copyCGImageAtTime:playerItem.currentTime
                                                  actualTime:NULL
                                                       error:NULL];
        UIImage *videoImage = [UIImage imageWithCGImage:thumb];
        CGImageRelease(thumb);
        return videoImage;
    }
    -(int)getTheActualOrientationOfVideo:(AVPlayerItem *)playerItem
    {
        AVAsset *asset = playerItem.asset;
        NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
        AVAssetTrack *track = [tracks objectAtIndex:0];
        CGAffineTransform videoAssetOrientation_ = [track preferredTransform];
        CGFloat videoAngle  = RadiansToDegrees(atan2(videoAssetOrientation_.b, videoAssetOrientation_.a));
        int  orientation = 0;
        switch ((int)videoAngle) {
            case 0:
                orientation = UIImageOrientationRight;
                break;
            case 90:
                orientation = UIImageOrientationUp;
                break;
            case 180:
                orientation = UIImageOrientationLeft;
                break;
            case -90:
                orientation = UIImageOrientationDown;
                break;
            default:
                //Not found
                break;
        }
        return orientation;
    }
    - (UIImage *)normalizedImage:(UIImage *)imageOf {
        if (imageOf.imageOrientation == UIImageOrientationUp) return imageOf;

        UIGraphicsBeginImageContextWithOptions(imageOf.size, NO, imageOf.scale);
        [imageOf drawInRect:(CGRect){0, 0, imageOf.size}];
        UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return normalizedImage;
    }
</code>```

Swift solution

```<code>func snapShot() {
    let capturedImage: UIImage? = getASnapShotWithAVLayer()
}

func getASnapShotWithAVLayer() -> UIImage {
    //Add temporary thumbnail One
    let temporaryViewForVideoOne = UIImageView(frame: videoViewOne.bounds) //replace videoViewOne with you view which is showing AVPlayerContent
    temporaryViewForVideoOne.contentMode = .scaleAspectFill
    var imageFromCurrentTimeForVideoOne: UIImage? = takeVideoSnapShot(playerItem1)
    var orientationFromVideoForVideoOne: Int = getTheActualOrientationOfVideo(playerItem1)
    if orientationFromVideoForVideoOne == 0 {
        orientationFromVideoForVideoOne = 3
    }
    else if orientationFromVideoForVideoOne == 90 {
        orientationFromVideoForVideoOne = 0
    }

    imageFromCurrentTimeForVideoOne = UIImage(cgImage: imageFromCurrentTimeForVideoOne?.cgImage, scale: imageFromCurrentTimeForVideoOne?.scale, orientation: orientationFromVideoForVideoOne)
    let rotatedImageFromCurrentContextForVideoOne: UIImage? = normalizedImage(imageFromCurrentTimeForVideoOne)
    temporaryViewForVideoOne.clipsToBounds = true
    temporaryViewForVideoOne.image = rotatedImageFromCurrentContextForVideoOne
    videoViewOne.addSubview(temporaryViewForVideoOne) //Replace videoViewOne with your view containing AVPlayer
    var imageSize = CGSize.zero
    let orientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
    if UIInterfaceOrientationIsPortrait(orientation) {
        imageSize = UIScreen.main.bounds.size
    }
    else {
        imageSize = CGSize(width: CGFloat(UIScreen.main.bounds.size.height), height: CGFloat(UIScreen.main.bounds.size.width))
    }
    UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale())
    let context: CGContext? = UIGraphicsGetCurrentContext()
    for window: UIWindow in UIApplication.shared.windows {
        context.saveGState()
        context.translateBy(x: window.center.x, y: window.center.y)
        context.concatenate(window.transform)
        context.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
        if orientation == .landscapeLeft {
            context.rotate(by: M_PI_2)
            context.translateBy(x: 0, y: -imageSize.width)
        }
        else if orientation == .landscapeRight {
            context.rotate(by: -M_PI_2)
            context.translateBy(x: -imageSize.height, y: 0)
        }
        else if orientation == .portraitUpsideDown {
            context.rotate(by: .pi)
            context.translateBy(x: -imageSize.width, y: -imageSize.height)
        }

        if !window.responds(to: Selector("drawViewHierarchyInRect:afterScreenUpdates:")) {
            window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
        }
        else {
            window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
        }
        context.restoreGState()
    }
    let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    temporaryViewForVideoOne.removeFromSuperview()
    return image!
}

func takeVideoSnapShot(_ playerItem: AVPlayerItem) -> UIImage {
    let asset: AVURLAsset? = (playerItem.asset as? AVURLAsset)
    let imageGenerator = AVAssetImageGenerator(asset)
    imageGenerator.requestedTimeToleranceAfter = kCMTimeZero
    imageGenerator.requestedTimeToleranceBefore = kCMTimeZero
    let thumb: CGImageRef? = try? imageGenerator.copyCGImage(atTime: playerItem.currentTime(), actualTime: nil)
    let videoImage = UIImage(cgImage: thumb)
    CGImageRelease(thumb)
    return videoImage
}

func getTheActualOrientationOfVideo(_ playerItem: AVPlayerItem) -> Int {
    let asset: AVAsset? = playerItem.asset
    let tracks: [Any]? = asset?.tracks(withMediaType: AVMediaTypeVideo)
    let track: AVAssetTrack? = (tracks?[0] as? AVAssetTrack)
    let videoAssetOrientation_: CGAffineTransform? = track?.preferredTransform
    let videoAngle: CGFloat? = RadiansToDegrees(atan2(videoAssetOrientation_?.b, videoAssetOrientation_?.a))
    var orientation: Int = 0
    switch Int(videoAngle) {
        case 0:
            orientation = .right
        case 90:
            orientation = .up
        case 180:
            orientation = .left
        case -90:
            orientation = .down
        default:
            //Not found
    }
    return orientation
}

func normalizedImage(_ imageOf: UIImage) -> UIImage {
    if imageOf.imageOrientation == .up {
        return imageOf
    }
    UIGraphicsBeginImageContextWithOptions(imageOf.size, false, imageOf.scale)
    imageOf.draw(in: (CGRect))
    let normalizedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return normalizedImage!
}
</code>```

Body:
How to take screenshot of AVplayerLayer. I tried with the following code it works well, it captures the entire view as it was

func screenShotMethod() {
    let window = UIApplication.shared.delegate!.window!!
    //capture the entire window into an image
    UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
    window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
    let windowImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //now position the image x/y away from the top-left corner to get the portion we want
    UIGraphicsBeginImageContext(view.frame.size)
    windowImage?.draw(at: CGPoint(x: -view.frame.origin.x, y: -view.frame.origin.y))
    let croppedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext();
    //embed image in an imageView, supports transforms.
    let resultImageView = UIImageView(image: croppedImage)
    UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, nil)
}

But the problem is when i tried the same code running on iPhone(device) it returns black image.i don't know what was wrong

Any suggestions would be greatly helpful!

Body:
A few days ago, we also ran into the same issue. Where, if we take the screenshot of a screen which has a video player in it; The screenshot looks fine in the simulator.But, on the device, it was a black screen.

After a lot of attempts, I failed and finally end up with a patch (not sure if it is a correct way of solving the problem). But, the solution did the trick and I was able to get the screenshot on the device as well and simulator as well.

Following is a way I used to solve the issue.

1 -> Get a single frame at current time from the video (Public method is already available for this)

2 -> Use this thumbnail in the place of CALayer (add it to hierarchy)

3 -> Once we are done remove the thumbnail from the memory (remove from hierarchy)

Following is a demo sample for the same (The given solution is in Objective-c though the question asked is in Swift).

Objective - C solution

  - (void)SnapShot {
       UIImage *capturedImage = [self getASnapShotWithAVLayer];
    }
    - (UIImage *)getASnapShotWithAVLayer {
        //Add temporary thumbnail One
        UIImageView *temporaryViewForVideoOne = [[UIImageView alloc] initWithFrame:self.videoViewOne.bounds];
        temporaryViewForVideoOne.contentMode = UIViewContentModeScaleAspectFill;
        UIImage *imageFromCurrentTimeForVideoOne = [self takeVideoSnapShot:_playerItem1];
        int orientationFromVideoForVideoOne = [self getTheActualOrientationOfVideo:self.playerItem1];
        if(orientationFromVideoForVideoOne == 0)
        {
            orientationFromVideoForVideoOne = 3;
        }
        else if (orientationFromVideoForVideoOne == 90)
        {
            orientationFromVideoForVideoOne = 0;
        }
        imageFromCurrentTimeForVideoOne =
        [UIImage imageWithCGImage:[imageFromCurrentTimeForVideoOne CGImage]
                            scale:[imageFromCurrentTimeForVideoOne scale]
                      orientation: orientationFromVideoForVideoOne];
        UIImage *rotatedImageFromCurrentContextForVideoOne = [self normalizedImage:imageFromCurrentTimeForVideoOne];
        temporaryViewForVideoOne.clipsToBounds = YES;
        temporaryViewForVideoOne.image = rotatedImageFromCurrentContextForVideoOne;
        [self.videoViewOne addSubview:temporaryViewForVideoOne];
        CGSize imageSize = CGSizeZero;
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        if (UIInterfaceOrientationIsPortrait(orientation)) {
            imageSize = [UIScreen mainScreen].bounds.size;
        } else {
            imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
        }

        UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]);
        CGContextRef context = UIGraphicsGetCurrentContext();
        for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, window.center.x, window.center.y);
            CGContextConcatCTM(context, window.transform);
            CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
            if (orientation == UIInterfaceOrientationLandscapeLeft) {
                CGContextRotateCTM(context, M_PI_2);
                CGContextTranslateCTM(context, 0, -imageSize.width);
            } else if (orientation == UIInterfaceOrientationLandscapeRight) {
                CGContextRotateCTM(context, -M_PI_2);
                CGContextTranslateCTM(context, -imageSize.height, 0);
            } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
                CGContextRotateCTM(context, M_PI);
                CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
            }
            if (![window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
                [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
            } else {
                [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
            }
            CGContextRestoreGState(context);
        }
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [temporaryViewForVideoOne removeFromSuperview];
        [temporaryViewForVideoTwo removeFromSuperview];
        return image;
    }
    -(UIImage *)takeVideoSnapShot: (AVPlayerItem *) playerItem{
        AVURLAsset *asset = (AVURLAsset *) playerItem.asset;
        AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
        imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
        CGImageRef thumb = [imageGenerator copyCGImageAtTime:playerItem.currentTime
                                                  actualTime:NULL
                                                       error:NULL];
        UIImage *videoImage = [UIImage imageWithCGImage:thumb];
        CGImageRelease(thumb);
        return videoImage;
    }
    -(int)getTheActualOrientationOfVideo:(AVPlayerItem *)playerItem
    {
        AVAsset *asset = playerItem.asset;
        NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
        AVAssetTrack *track = [tracks objectAtIndex:0];
        CGAffineTransform videoAssetOrientation_ = [track preferredTransform];
        CGFloat videoAngle  = RadiansToDegrees(atan2(videoAssetOrientation_.b, videoAssetOrientation_.a));
        int  orientation = 0;
        switch ((int)videoAngle) {
            case 0:
                orientation = UIImageOrientationRight;
                break;
            case 90:
                orientation = UIImageOrientationUp;
                break;
            case 180:
                orientation = UIImageOrientationLeft;
                break;
            case -90:
                orientation = UIImageOrientationDown;
                break;
            default:
                //Not found
                break;
        }
        return orientation;
    }
    - (UIImage *)normalizedImage:(UIImage *)imageOf {
        if (imageOf.imageOrientation == UIImageOrientationUp) return imageOf;

        UIGraphicsBeginImageContextWithOptions(imageOf.size, NO, imageOf.scale);
        [imageOf drawInRect:(CGRect){0, 0, imageOf.size}];
        UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return normalizedImage;
    }

Swift solution

func snapShot() {
    let capturedImage: UIImage? = getASnapShotWithAVLayer()
}

func getASnapShotWithAVLayer() -> UIImage {
    //Add temporary thumbnail One
    let temporaryViewForVideoOne = UIImageView(frame: videoViewOne.bounds) //replace videoViewOne with you view which is showing AVPlayerContent
    temporaryViewForVideoOne.contentMode = .scaleAspectFill
    var imageFromCurrentTimeForVideoOne: UIImage? = takeVideoSnapShot(playerItem1)
    var orientationFromVideoForVideoOne: Int = getTheActualOrientationOfVideo(playerItem1)
    if orientationFromVideoForVideoOne == 0 {
        orientationFromVideoForVideoOne = 3
    }
    else if orientationFromVideoForVideoOne == 90 {
        orientationFromVideoForVideoOne = 0
    }

    imageFromCurrentTimeForVideoOne = UIImage(cgImage: imageFromCurrentTimeForVideoOne?.cgImage, scale: imageFromCurrentTimeForVideoOne?.scale, orientation: orientationFromVideoForVideoOne)
    let rotatedImageFromCurrentContextForVideoOne: UIImage? = normalizedImage(imageFromCurrentTimeForVideoOne)
    temporaryViewForVideoOne.clipsToBounds = true
    temporaryViewForVideoOne.image = rotatedImageFromCurrentContextForVideoOne
    videoViewOne.addSubview(temporaryViewForVideoOne) //Replace videoViewOne with your view containing AVPlayer
    var imageSize = CGSize.zero
    let orientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
    if UIInterfaceOrientationIsPortrait(orientation) {
        imageSize = UIScreen.main.bounds.size
    }
    else {
        imageSize = CGSize(width: CGFloat(UIScreen.main.bounds.size.height), height: CGFloat(UIScreen.main.bounds.size.width))
    }
    UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale())
    let context: CGContext? = UIGraphicsGetCurrentContext()
    for window: UIWindow in UIApplication.shared.windows {
        context.saveGState()
        context.translateBy(x: window.center.x, y: window.center.y)
        context.concatenate(window.transform)
        context.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
        if orientation == .landscapeLeft {
            context.rotate(by: M_PI_2)
            context.translateBy(x: 0, y: -imageSize.width)
        }
        else if orientation == .landscapeRight {
            context.rotate(by: -M_PI_2)
            context.translateBy(x: -imageSize.height, y: 0)
        }
        else if orientation == .portraitUpsideDown {
            context.rotate(by: .pi)
            context.translateBy(x: -imageSize.width, y: -imageSize.height)
        }

        if !window.responds(to: Selector("drawViewHierarchyInRect:afterScreenUpdates:")) {
            window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
        }
        else {
            window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
        }
        context.restoreGState()
    }
    let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    temporaryViewForVideoOne.removeFromSuperview()
    return image!
}

func takeVideoSnapShot(_ playerItem: AVPlayerItem) -> UIImage {
    let asset: AVURLAsset? = (playerItem.asset as? AVURLAsset)
    let imageGenerator = AVAssetImageGenerator(asset)
    imageGenerator.requestedTimeToleranceAfter = kCMTimeZero
    imageGenerator.requestedTimeToleranceBefore = kCMTimeZero
    let thumb: CGImageRef? = try? imageGenerator.copyCGImage(atTime: playerItem.currentTime(), actualTime: nil)
    let videoImage = UIImage(cgImage: thumb)
    CGImageRelease(thumb)
    return videoImage
}

func getTheActualOrientationOfVideo(_ playerItem: AVPlayerItem) -> Int {
    let asset: AVAsset? = playerItem.asset
    let tracks: [Any]? = asset?.tracks(withMediaType: AVMediaTypeVideo)
    let track: AVAssetTrack? = (tracks?[0] as? AVAssetTrack)
    let videoAssetOrientation_: CGAffineTransform? = track?.preferredTransform
    let videoAngle: CGFloat? = RadiansToDegrees(atan2(videoAssetOrientation_?.b, videoAssetOrientation_?.a))
    var orientation: Int = 0
    switch Int(videoAngle) {
        case 0:
            orientation = .right
        case 90:
            orientation = .up
        case 180:
            orientation = .left
        case -90:
            orientation = .down
        default:
            //Not found
    }
    return orientation
}

func normalizedImage(_ imageOf: UIImage) -> UIImage {
    if imageOf.imageOrientation == .up {
        return imageOf
    }
    UIGraphicsBeginImageContextWithOptions(imageOf.size, false, imageOf.scale)
    imageOf.draw(in: (CGRect))
    let normalizedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return normalizedImage!
}


问:
Is it possible to wrap a C# singleton in an interface?
I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.

But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?

答:
You can't do this with interfaces since they only specify instance methods but you can put this in a base class.

A singleton base class:

```<code>public abstract class Singleton<ClassType> where ClassType : new()
{
  static Singleton()
  {
  }

  private static readonly ClassType instance = new ClassType();

  public static ClassType Instance
  {
    get
    {
      return instance;
    }
  }
}
</code>```

A child singleton:

```<code>class Example : Singleton<Example>
{
  public int ExampleProperty { get; set; }
}
</code>```

A caller:

```<code>public void LameExampleMethod()
{
  Example.Instance.ExampleProperty++;
}
</code>```

Body:
You can't do this with interfaces since they only specify instance methods but you can put this in a base class.

A singleton base class:

public abstract class Singleton<ClassType> where ClassType : new()
{
  static Singleton()
  {
  }

  private static readonly ClassType instance = new ClassType();

  public static ClassType Instance
  {
    get
    {
      return instance;
    }
  }
}

A child singleton:

class Example : Singleton<Example>
{
  public int ExampleProperty { get; set; }
}

A caller:

public void LameExampleMethod()
{
  Example.Instance.ExampleProperty++;
}


问:
How to get radio button selected value from dynamically generated radio buttons?
Hi I am developing web application in angularjs. I am generating radiobuttons dynamically using ng-repeat as below.

```<code><ul>
    <li ng-repeat="level in permissions">
        <input name="level.perm_levelname" type="radio" ng-model="level.perm_levelname" value="{{level.perm_levelname}}"> {{level.perm_levelname}}
        <a ng-click="gotopermMap({permisssionID: level.id})">View</a>
    </li>
</ul>
<input type="button" value="APPLY" ng-click="apply()" />
</code>```

I am trying to get selected radio button as below.

```<code> $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.level.perm_levelname);
        }
</code>```

I am getting error  Cannot read property 'perm_levelname' of undefined. May i get help here to get selected radio button? Thank you

答:
you should use radio button group like this--

```<code><ul>
     <li ng-repeat="level in permissions">
       <input name="btnGroup" type="radio" ng-model="radioButtonValue" value="{{level.perm_levelname}}">
       {{level.perm_levelname}}
       <a ng-click="gotopermMap({permisssionID: level.id})">View</a>
     </li>
   </ul>
   <input type="button" value="APPLY" ng-click="apply()"/>
</code>```

And inside of Controller-

```<code>$scope.radioButtonValue='';

 $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.radioButtonValue);
        }
</code>```

Body:
Hi I am developing web application in angularjs. I am generating radiobuttons dynamically using ng-repeat as below.

        <input name="level.perm_levelname" type="radio" ng-model="level.perm_levelname" value="{{level.perm_levelname}}"> {{level.perm_levelname}}
        View

<input type="button" value="APPLY" ng-click="apply()" />

I am trying to get selected radio button as below.

 $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.level.perm_levelname);
        }

I am getting error  Cannot read property 'perm_levelname' of undefined. May i get help here to get selected radio button? Thank you

Body:
you should use radio button group like this--

<ul>
     <li ng-repeat="level in permissions">
       <input name="btnGroup" type="radio" ng-model="radioButtonValue" value="{{level.perm_levelname}}">
       {{level.perm_levelname}}
       <a ng-click="gotopermMap({permisssionID: level.id})">View</a>
     </li>
   </ul>
   <input type="button" value="APPLY" ng-click="apply()"/>

And inside of Controller-

$scope.radioButtonValue='';

 $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.radioButtonValue);
        }


答:
I think the only safe cross-browser solution is to use javascript for line clamping. I've used Clamp.js once and I remember it being easy to use and working very well. You can read some more about the whole "line clamping issue"
 here.

The basic usage of Clamp.js in your case would be something like the following

```<code>$clamp(myText, {clamp: 2});
</code>```

Where myText is the element you want to line clamp and 2 means two lines.

Title: CSS code use to make sure that only 2 line sentence to display is not working for IE

Body:
I have the following css code to make sure that the display sentence is not more then 2 line, if so it will replace the rest of the word to "..."

   .bell-notification-max-words-display{
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

This working fine for chrome, safari and mozilla. However, it's not working for IE. When I inspect the element, error showing like below:

Does anyone know how can I make it work for IE?

Body:
I think the only safe cross-browser solution is to use javascript for line clamping. I've used Clamp.js once and I remember it being easy to use and working very well. You can read some more about the whole "line clamping issue"
 here.

The basic usage of Clamp.js in your case would be something like the following

$clamp(myText, {clamp: 2});

Where myText is the element you want to line clamp and 2 means two lines.


问:
Scheduled email job in asp.net on AWS EC2
I have an asp.net web page which retrieves some data from database and send to the subscribed customers. And I want to do it first day of every month.
So is there anyway to call this web page every month except the windows task sheduler? My website is on AWS EC2. Can I use AWS Lambda function and cron to call this specific page every month?</p>

答:
You can create a Lambda function to sending a request to your site. And your site will send an subscription email to your customers.

Cloudwatch has a service call Schedule Expressions. It's do the same thing with cron but it has an option for you to trigger some AWS service at the time. In this case, you trigger the Lambda.

P.S. I think the CloudWatch's timezone is UTC, and you have to do calculate time different for it.

For more information : http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html


问:
How to login to website through python using request?
I have gone through all the questions on stackoverflow related to this but I can't solve my problem. When I am implementing the follwing code,it runs successfully without any error but nothing gets printed.</p>

```<code>import requests

payload = {'username': 'user','password': 'pass'}

with requests.Session() as s:
    p = s.post(' file-transfers.in/login.php?rid=worlddomains',
          params=payload)
    r = s.get('http://file-transfers.in/member_arean.php')
    print r.text
</code>```

答:
There is a whole chapter about Authentication in the Python requests docs.

Basic Authentication

Many web services that require authentication accept HTTP Basic Auth.
  This is the simplest kind, and Requests supports it straight out of
  the box.

Making requests with HTTP Basic Auth is very simple:

```<code>>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>
</code>```

In fact, HTTP Basic Auth is so common that Requests provides a handy
  shorthand for using it:

```<code>>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>
</code>```

Providing the credentials in a tuple like this is exactly the same as
  the HTTPBasicAuth example above.

Body:
I have gone through all the questions on stackoverflow related to this but I can't solve my problem. When I am implementing the follwing code,it runs successfully without any error but nothing gets printed.

import requests

payload = {'username': 'user','password': 'pass'}

with requests.Session() as s:
    p = s.post(' file-transfers.in/login.php?rid=worlddomains',
          params=payload)
    r = s.get('http://file-transfers.in/member_arean.php')
    print r.text

Body:
There is a whole chapter about Authentication in the Python requests docs.

Basic Authentication

Many web services that require authentication accept HTTP Basic Auth.
  This is the simplest kind, and Requests supports it straight out of
  the box.

Making requests with HTTP Basic Auth is very simple:

>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>

In fact, HTTP Basic Auth is so common that Requests provides a handy
  shorthand for using it:

>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>

Providing the credentials in a tuple like this is exactly the same as
  the HTTPBasicAuth example above.