答:
This will write the tags to the corresponding text file. What you missed was to open the flnmc file in the latter part.

```<code>fc=open(flnmc,'r')
for tag, s in tags_dict.items():
    with open(flnmc,'r') as fc:
        for line in fc:
            if tag in line:
                f=open("%s.txt" %s,'w')
                f.write(line)
</code>```

Title: Python: failed to write results in multiple files

Body:
This will write the tags to the corresponding text file. What you missed was to open the flnmc file in the latter part.

fc=open(flnmc,'r')
for tag, s in tags_dict.items():
    with open(flnmc,'r') as fc:
        for line in fc:
            if tag in line:
                f=open("%s.txt" %s,'w')
                f.write(line)


来源: stackexchange

问:
Clearing Page Cache in ASP.NET
For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...

```<code><%@OutputCache Duration="600" VaryByParam="*" %>
</code>```

However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.

How do I do this in ASP.Net C#?

答: HttpRuntime.Close() .. I try all method and this is the only that work for me

OwnerDisplayName: GateKiller

ContentLicense: CC BY-SA 2.5

Title: Clearing Page Cache in ASP.NET

Body:
For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...

<%@OutputCache Duration="600" VaryByParam="*" %>

However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.

How do I do this in ASP.Net C#?

LastEditorDisplayName: GateKiller

ContentLicense: CC BY-SA 3.0


问:
Text-indent has effect on the first child span element of div?
here is the code: https://jsfiddle.net/zz89emkr/1/

```<code>.menu-items {
  width: 400px;
  text-indent: 5%;
}
<div class="menu-items">
    <span>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus quia maiores voluptatum adipisci iusto perferendis earum quasi, accusamus magni temporibus alias consectetur, provident vel quis nesciunt expedita sit nemo aliquam?</span>
    <div>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo quas esse eius. Quos atque ea necessitatibus labore est error hic. At quae veritatis sit aperiam debitis animi provident dolorum dolore?</div>
    <span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, eaque atque adipisci, fugiat fuga maiores repellendus voluptas non explicabo odio et ut tenetur sint iusto minima unde. Ex, voluptas sed?</span>
</div>
</code>```

I know that text-indent will not work on inline element, however, in this example, the first span will get text-indent. What's more, in firefox, the text-indent in the first span element is larger than that in the div element.

答:
Give display:block to .menu-items span because span default behavior is inline-block.

.menu-items {
  width: 400px;
  text-indent: 5%;
}
.menu-items span{
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-items">
    <span>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus quia maiores voluptatum adipisci iusto perferendis earum quasi, accusamus magni temporibus alias consectetur, provident vel quis nesciunt expedita sit nemo aliquam?</span>
    <div>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo quas esse eius. Quos atque ea necessitatibus labore est error hic. At quae veritatis sit aperiam debitis animi provident dolorum dolore?</div>
    <span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, eaque atque adipisci, fugiat fuga maiores repellendus voluptas non explicabo odio et ut tenetur sint iusto minima unde. Ex, voluptas sed?</span>
  </div></code>```

Body:
here is the code: https://jsfiddle.net/zz89emkr/1/

.menu-items {
  width: 400px;
  text-indent: 5%;
}

    Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus quia maiores voluptatum adipisci iusto perferendis earum quasi, accusamus magni temporibus alias consectetur, provident vel quis nesciunt expedita sit nemo aliquam?

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo quas esse eius. Quos atque ea necessitatibus labore est error hic. At quae veritatis sit aperiam debitis animi provident dolorum dolore?

    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, eaque atque adipisci, fugiat fuga maiores repellendus voluptas non explicabo odio et ut tenetur sint iusto minima unde. Ex, voluptas sed?

I know that text-indent will not work on inline element, however, in this example, the first span will get text-indent. What's more, in firefox, the text-indent in the first span element is larger than that in the div element.

Body:
Give display:block to .menu-items span because span default behavior is inline-block.

.menu-items {
  width: 400px;
  text-indent: 5%;
}
.menu-items span{
  display:block;
}

<div class="menu-items">
    <span>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus quia maiores voluptatum adipisci iusto perferendis earum quasi, accusamus magni temporibus alias consectetur, provident vel quis nesciunt expedita sit nemo aliquam?</span>
    <div>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo quas esse eius. Quos atque ea necessitatibus labore est error hic. At quae veritatis sit aperiam debitis animi provident dolorum dolore?</div>
    <span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, eaque atque adipisci, fugiat fuga maiores repellendus voluptas non explicabo odio et ut tenetur sint iusto minima unde. Ex, voluptas sed?</span>
  </div>


问:
PopUp for displaying Image not Working in IE
I am using the below code for displaying image in a new window.. It works fine in chrome but no in IE..
Here is my code..

```<code>function enlargeimg(url) {
  var newWindow = window.open("", "", "width=600,height=750");
  newWindow.document.writeln("<html>");
  newWindow.document.writeln("<body>");
  newWindow.document.writeln("<img src='" + url +"' alt='Click to close' id='bigImage'/>");
  newWindow.document.writeln("</body></html>");
  newWindow.document.close();
}
</code>```

This how image displayed in IE popoup :-

Any help will be appreciated.

答:
IE doesn't like spaces or empty name in the window name,

try this,

```<code>var newWindow = window.open("", "win_with_image", "width=600,height=750");
</code>```

Alternate solution:

If image is what you have to display in the popup,
you can try something like ref,

```<code>function openRequestedPopup() {
   var windowObjectReference = window.open(
       "http://www.domainname.ext/path/ImageFile.png",
       "DescriptiveWindowName",
       "resizable,scrollbars,status"
   );
}
</code>```

Body:
I am using the below code for displaying image in a new window.. It works fine in chrome but no in IE..
Here is my code..

function enlargeimg(url) {
  var newWindow = window.open("", "", "width=600,height=750");
  newWindow.document.writeln("");
  newWindow.document.writeln("");
  newWindow.document.writeln("");
  newWindow.document.writeln("");
  newWindow.document.close();
}

This how image displayed in IE popoup :-

Any help will be appreciated.

Body:
IE doesn't like spaces or empty name in the window name,

try this,

var newWindow = window.open("", "win_with_image", "width=600,height=750");

Alternate solution:

If image is what you have to display in the popup,
you can try something like ref,

function openRequestedPopup() {
   var windowObjectReference = window.open(
       "http://www.domainname.ext/path/ImageFile.png",
       "DescriptiveWindowName",
       "resizable,scrollbars,status"
   );
}


问:
How to display info of selected items?
I am new in Yii framework, so I don't have much idea in it.
My question is, I want to get details of the company which is selected in a search box.

Code in my frontend/companies.php

```<code><?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ?>
</code>```

Here's my select2 widget code:-

```<code>$typeahead =  Select2::widget([
'id' => 'front_companies_select',
'name' => 'state_10',
'data' => $companyNameList,
'options' => [
'placeholder' => 'Select ...',
'sigle' => true
],
]);
</code>```

My js code:-

```<code>$("#getinfo").click(function(){
        var obj = $("#front_companies_select option:selected").val();
        console.log(obj);
     });
</code>```

答:
If you want to get only company name you can try this.

```<code>$("#getinfo").click(function(){
    var company_id = $("#front_companies_select option:selected").val();
    console.log(company_id);
    var companyName = $("#front_companies_select option:selected").text();
    console.log(companyName); //here you can get company name
});
</code>```

Or If you want to get whole company details then you have to call ajax like this.

```<code>$("#getinfo").click(function(){
    var company_id = $("#front_companies_select option:selected").val();

    $.ajax({
        type: "POST",
        url:"YOUR_URL/YOUR_FUNCTION_TO_GET_COMPANY_DETAILS",
        data: {company_id:company_id},
        dataType:'json',
        async: false,
        success: function (data)
        {
          console.log(data); //here you can get all the company details in object
        }
    });

});
</code>```

Title: How to display info of selected items?

Body:
I am new in Yii framework, so I don't have much idea in it.
My question is, I want to get details of the company which is selected in a search box.

Code in my frontend/companies.php

<?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ?>

Here's my select2 widget code:-

$typeahead =  Select2::widget([
'id' => 'front_companies_select',
'name' => 'state_10',
'data' => $companyNameList,
'options' => [
'placeholder' => 'Select ...',
'sigle' => true
],
]);

My js code:-

$("#getinfo").click(function(){
        var obj = $("#front_companies_select option:selected").val();
        console.log(obj);
     });

Body:
If you want to get only company name you can try this.

$("#getinfo").click(function(){
    var company_id = $("#front_companies_select option:selected").val();
    console.log(company_id);
    var companyName = $("#front_companies_select option:selected").text();
    console.log(companyName); //here you can get company name
});

Or If you want to get whole company details then you have to call ajax like this.

$("#getinfo").click(function(){
    var company_id = $("#front_companies_select option:selected").val();

    $.ajax({
        type: "POST",
        url:"YOUR_URL/YOUR_FUNCTION_TO_GET_COMPANY_DETAILS",
        data: {company_id:company_id},
        dataType:'json',
        async: false,
        success: function (data)
        {
          console.log(data); //here you can get all the company details in object
        }
    });

});


问:
Converting a list into JSON with timestamp
I have a list of dictionaries like this:

```<code>  [{'accounts': [{'account_number': 'xx6747',
  'bank_name': 'Fargo Bank',
  'bankid': 85,
  'created_date_y': Timestamp('2015-05-20 08:08:33'),
  'item_account_id': 20086385.0,
  'item_id': 17764259,
  'user_id': 18},
  {'account_number': '*819',
 'bank_name': 'Central Alabama - Bank',
 'bankid': 88,
 'created_date_y': Timestamp('2015-05-20 08:08:33'),
 'item_account_id': 20637127.0,
 'item_id': 17761624,
 'user_id': 18},
 {'account_number': '*056',
'bank_name': 'Central Alabama - Bank',
'bankid': 88,
'created_date_y': Timestamp('2015-05-20 08:08:33'),
'item_account_id': 20087284.0,
'item_id': 17761624,
'user_id': 18},
'created_date_x': Timestamp('2014-03-11 10:48:42'),
'id': 18,
'password': 'NjgrUW9URGZz09',
'status': 1,
'uid': 97560,
'username': 'pepass@yahoo.com'},
{'accounts': [{'account_number': 791,
'bank_name': 'Chase - Bank',
'bankid': 855,
'created_date_y': Timestamp('2015-05-20 08:03:37'),
'item_account_id': 20090104.0,
'item_id': 17764260,
'user_id': 20},
{'account_number': 883,
'bank_name': 'Chase - Bank',
'bankid': 852,
'created_date_y': Timestamp('2015-05-20 08:03:37'),
'item_account_id': 20090105.0,
'item_id': 17764260,
'user_id': 20}],
'created_date_x': Timestamp('2014-03-11 13:42:20'),
'id': 20,
'password': 'bmJlbTN5dFo5QT09',
'status': 1,
'uid': 99408,
'username': 'hor@sanstore.com'}]
</code>```

It contains other items as well. The created_date_x and created_date_y are timestamps. I want to convert this list into a nested dictionary something like this:

```<code> {'id': 18,
  'password': 'NjgrUW9URGZz09',
  'status': 1,
  'uid': 97560,
  'username': 'pepass@yahoo.com'},
  'created_date_x': Timestamp('2014-03-11 10:48:42')
{'accounts':
       [{'account_number': 'xx6747',
       'bank_name': 'Fargo Bank',
       'bankid': 85,
       'created_date_y': Timestamp('2015-05-20 08:08:33'),
       'item_account_id': 20086385.0,
       'item_id': 17764259,
       'user_id': 18},
      {'account_number': '*819',
       'bank_name': 'Central Alabama - Bank',
       'bankid': 88,
       'created_date_y': Timestamp('2015-05-20 08:08:33'),
       'item_account_id': 20637127.0,
       'item_id': 17761624,
       'user_id': 18},
      {'account_number': '*056',
       'bank_name': 'Central Alabama - Bank',
       'bankid': 88,
       'created_date_y': Timestamp('2015-05-20 08:08:33'),
       'item_account_id': 20087284.0,
       'item_id': 17761624,
       'user_id': 18}]}}
</code>```

After converting it into a dictionary, I want to convert this into a JSON. The problem in converting it into json is that the timestamp fields give an error as timestamp is not json serializale. The code I have so far which does not work as I want is:

```<code> import pandas as pd
 #importing files
 df1 = pd.read_excel("C:\\Users\\Desktop\\yod_user.xlsx")
 df2 = pd.read_excel("C:\\Users\\Desktop\\yod_bank.xlsx")

 df1['created_date'] = df1['created_date'].astype(str)
 df2['created_date'] = df2['created_date'].astype(str)

 df1.dtypes
 #id               int64
 #username        object
 #password        object
 #uid              int64
 #created_date    object
 #status           int64
 #dtype: object
 df2.dtypes
 #user_id              int64
 #bankid                      int64
 #account_number             object
 #item_id              int64
 #item_account_id    float64
 #created_date               object
 #bank_name                  object
 #dtype: object

 df_merge = pd.merge(df1, df2, left_on = 'id', right_on ='user_id', how ='inner')
 df_merge.dtypes
 #id                        object
 #username                  object
 #password                  object
 #uid                       object
 #created_date_x            object
 #status                    object
 #user_id                   object
 #bankid                    object
 #account_number            object
 #item_id                   object
 #item_account_id           object
 #created_date_y            object
 #bank_name                 object
 #dtype: object
j = df_merge.groupby(['id', 'username', 'password',   'uid',created_date_x',  'status'], as_index=False)\
         .apply(lambda x: x[['account_number','user_id','bankid', 'item_id', 'item_account_id','created_date_y', 'bank_name' ]].to_dict('r'))\
         .reset_index()\
         .rename(columns={0:'accounts'})\

 j.dtypes
 #id                 int64
 #username          object
 #password          object
 #uid                int64
 #created_date_x    object
 #status             int64
 #accounts          object
 #dtype: object
 jdict = j.to_dict('records')

 import json
 json.dumps(jdict) #This gives an error: TypeError: Object of type     'Timestamp' is not JSON serializable
</code>```

If the initial list can be converted into a json like a dictionary that will also do. Please Help.

答:
A simple solution to this problem would be to avoid using Timestamp entirely. Instead of calling Timestamp you could instead use the built in datetime module and create a function that returns the actual, numeric timestamp. For example

```<code>from datetime import datetime
from pytz import utc

def timestamp_from_str(date_str):

    date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
    return date.replace(tzinfo=utc).timestamp()
</code>```

Note that the .timestamp method is not available in Python 2.7, in which case you will have to calculate the timestamp manually. This is a simple process, but I won't mention it here as it has already been described in depth by another question.

Body:
I have a list of dictionaries like this:

  [{'accounts': [{'account_number': 'xx6747',
  'bank_name': 'Fargo Bank',
  'bankid': 85,
  'created_date_y': Timestamp('2015-05-20 08:08:33'),
  'item_account_id': 20086385.0,
  'item_id': 17764259,
  'user_id': 18},
  {'account_number': '*819',
 'bank_name': 'Central Alabama - Bank',
 'bankid': 88,
 'created_date_y': Timestamp('2015-05-20 08:08:33'),
 'item_account_id': 20637127.0,
 'item_id': 17761624,
 'user_id': 18},
 {'account_number': '*056',
'bank_name': 'Central Alabama - Bank',
'bankid': 88,
'created_date_y': Timestamp('2015-05-20 08:08:33'),
'item_account_id': 20087284.0,
'item_id': 17761624,
'user_id': 18},
'created_date_x': Timestamp('2014-03-11 10:48:42'),
'id': 18,
'password': 'NjgrUW9URGZz09',
'status': 1,
'uid': 97560,
'username': 'pepass@yahoo.com'},
{'accounts': [{'account_number': 791,
'bank_name': 'Chase - Bank',
'bankid': 855,
'created_date_y': Timestamp('2015-05-20 08:03:37'),
'item_account_id': 20090104.0,
'item_id': 17764260,
'user_id': 20},
{'account_number': 883,
'bank_name': 'Chase - Bank',
'bankid': 852,
'created_date_y': Timestamp('2015-05-20 08:03:37'),
'item_account_id': 20090105.0,
'item_id': 17764260,
'user_id': 20}],
'created_date_x': Timestamp('2014-03-11 13:42:20'),
'id': 20,
'password': 'bmJlbTN5dFo5QT09',
'status': 1,
'uid': 99408,
'username': 'hor@sanstore.com'}]

It contains other items as well. The created_date_x and created_date_y are timestamps. I want to convert this list into a nested dictionary something like this:

 {'id': 18,
  'password': 'NjgrUW9URGZz09',
  'status': 1,
  'uid': 97560,
  'username': 'pepass@yahoo.com'},
  'created_date_x': Timestamp('2014-03-11 10:48:42')
{'accounts':
       [{'account_number': 'xx6747',
       'bank_name': 'Fargo Bank',
       'bankid': 85,
       'created_date_y': Timestamp('2015-05-20 08:08:33'),
       'item_account_id': 20086385.0,
       'item_id': 17764259,
       'user_id': 18},
      {'account_number': '*819',
       'bank_name': 'Central Alabama - Bank',
       'bankid': 88,
       'created_date_y': Timestamp('2015-05-20 08:08:33'),
       'item_account_id': 20637127.0,
       'item_id': 17761624,
       'user_id': 18},
      {'account_number': '*056',
       'bank_name': 'Central Alabama - Bank',
       'bankid': 88,
       'created_date_y': Timestamp('2015-05-20 08:08:33'),
       'item_account_id': 20087284.0,
       'item_id': 17761624,
       'user_id': 18}]}}

After converting it into a dictionary, I want to convert this into a JSON. The problem in converting it into json is that the timestamp fields give an error as timestamp is not json serializale. The code I have so far which does not work as I want is:

 import pandas as pd
 #importing files
 df1 = pd.read_excel("C:\\Users\\Desktop\\yod_user.xlsx")
 df2 = pd.read_excel("C:\\Users\\Desktop\\yod_bank.xlsx")

 df1['created_date'] = df1['created_date'].astype(str)
 df2['created_date'] = df2['created_date'].astype(str)

 df1.dtypes
 #id               int64
 #username        object
 #password        object
 #uid              int64
 #created_date    object
 #status           int64
 #dtype: object
 df2.dtypes
 #user_id              int64
 #bankid                      int64
 #account_number             object
 #item_id              int64
 #item_account_id    float64
 #created_date               object
 #bank_name                  object
 #dtype: object

 df_merge = pd.merge(df1, df2, left_on = 'id', right_on ='user_id', how ='inner')
 df_merge.dtypes
 #id                        object
 #username                  object
 #password                  object
 #uid                       object
 #created_date_x            object
 #status                    object
 #user_id                   object
 #bankid                    object
 #account_number            object
 #item_id                   object
 #item_account_id           object
 #created_date_y            object
 #bank_name                 object
 #dtype: object
j = df_merge.groupby(['id', 'username', 'password',   'uid',created_date_x',  'status'], as_index=False)\
         .apply(lambda x: x[['account_number','user_id','bankid', 'item_id', 'item_account_id','created_date_y', 'bank_name' ]].to_dict('r'))\
         .reset_index()\
         .rename(columns={0:'accounts'})\

 j.dtypes
 #id                 int64
 #username          object
 #password          object
 #uid                int64
 #created_date_x    object
 #status             int64
 #accounts          object
 #dtype: object
 jdict = j.to_dict('records')

 import json
 json.dumps(jdict) #This gives an error: TypeError: Object of type     'Timestamp' is not JSON serializable

If the initial list can be converted into a json like a dictionary that will also do. Please Help.

Body:
A simple solution to this problem would be to avoid using Timestamp entirely. Instead of calling Timestamp you could instead use the built in datetime module and create a function that returns the actual, numeric timestamp. For example

from datetime import datetime
from pytz import utc

def timestamp_from_str(date_str):

    date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
    return date.replace(tzinfo=utc).timestamp()

Note that the .timestamp method is not available in Python 2.7, in which case you will have to calculate the timestamp manually. This is a simple process, but I won't mention it here as it has already been described in depth by another question.


问:
TypeError: Must be str, not int error occuring
I am trying to send the data from a CGI script to a C server in order to write the data down to an XML file.

Client.cgi:

```<code>import cgi, cgitb
import os
import sys
import argparse
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings()
import sys
import socket

form = cgi.FieldStorage()

#--PARSING THE ARGUMENTS
#--To be used to get arguments from Command Line or Php Script
parser = argparse.ArgumentParser(description ='parser script')
parser.add_argument('--serverId', required=True, help='Server ID to find device info')
parser.add_argument('--name', required=True, help='Name Of the Policy')
parser.add_argument('--host', default='any', help='Host of the IP Address')
parser.add_argument('--port', default='any', help='Port used')
parser.add_argument('--proto', default='any', help='Protocol used')
parser.add_argument('--username', default='any', help='Username')
parser.add_argument('--password', default='any', help='Password')
parser.add_argument('--key', default='any', help='')
parser.add_argument('--companyName', default='any', help='Name of the Company')
parser.add_argument('--officeAddress', default='any', help='Address of the Company')
parser.add_argument('--state', default='any', help='State')
parser.add_argument('--country', default='any', help='Country')
parser.add_argument('--ladmin', default='any', help='Local Admin')
parser.add_argument('--phone', default='any', help='Phone Number')
parser.add_argument('--mobile', default='any', help='Mobile Number')
parser.add_argument('--email', default='any', help='Email Address')
parser.add_argument('--designation', default='any', help='Designation of the concerned')
parser.add_argument('--rManager', default='any', help='Reporting Manager of the concerned Person')

args = parser.parse_args()

#--Associating variables to parsed arguments
serverId = str(args.serverId)
name = str(args.name)
host = str(args.host)
port = str(args.port)
proto = str(args.proto)
user = str(args.username)
password = str(args.password)
key = str(args.key)
company = str(args.companyName)
officeAddr = str(args.officeAddress)
state = str(args.state)
country = str(args.country)
ladmin = str(args.ladmin)
phone = str(args.phone)
mobile = str(args.mobile)
email = str(args.email)
designation = str(args.designation)
reportingMgr = str(args.rManager)

def client_program():
    host = socket.gethostname()  # as both code is running on same pc
    port = 8888  # socket server port number

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # instantiate
    client_socket.connect((host, port))  # connect to the server

    sum = serverId+";"+name+";"+host+";"+port+";"+proto+";"+user+";"+password+";"+key+";"+company+";"+officeAddr+";"+state+";"+country+";"+ladmin+";"+phone+";"+mobile+";"+email+";"+designation+";"+reportingMgr

    client_socket.sendall(sum.encode('utf-8'))
    data = client_socket.recv(1024)
    text = str(data)

    print('received:' +text)
    print('closing socket')
    client_socket.close()

if __name__ == '__main__':
    client_program()
</code>```

when passing arguments through command line like

```<code>python dscr.cgi --serverId PA124 --name Devanshu
</code>```

I get a traceback call as folowing

```<code>Traceback (most recent call last):
  File "dscr.cgi", line 90, in <module>
    client_program()
  File "dscr.cgi", line 79, in client_program
    sum = serverId+";"+name+";"+host+";"+port+";"+proto+";"+user+";"+password+";"+key+";"+company+";"+officeAddr+";"+state+";"+country+";"+ladmin+";"+phone+";"+mobile+";"+email+";"+designation+";"+reportingMgr
TypeError: must be str, not int
</code>```

I realise that its nothing but a silly mistake but I'm unable to find out what. Thanks for the help in advance.

答:
Your port variable is an int, you must convert it to str first:

You are in fact converting port to a str at some moment, but later assign it to an int in the scope of the function: port = 8888.

Maybe the remnant of some debugging code?

```<code>#                                       **here**
    sum = serverId+";"+name+";"+host+";"+str(port)+";"+proto+";"+user+";"+password+";"+key+";"+company+";"+officeAddr+";"+state+";"+country+";"+ladmin+";"+phone+";"+mobile+";"+email+";"+designation+";"+reportingMgr
</code>```

At @COLDSPEED suggestion, you could group all these arguments and call join on them:

```<code>arguments =  [serverId,
              name,
              host,
              str(port),
              proto,
              user,
              password,
              key,
              company,
              officeAddr,
              state,
              country,
              ladmin,
              phone,
              mobile,
              email,
              designation,
              reportingMgr]

print(';'.join(arguments))
</code>```

Body:
I am trying to send the data from a CGI script to a C server in order to write the data down to an XML file.

Client.cgi:

import cgi, cgitb
import os
import sys
import argparse
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings()
import sys
import socket

form = cgi.FieldStorage()

#--PARSING THE ARGUMENTS
#--To be used to get arguments from Command Line or Php Script
parser = argparse.ArgumentParser(description ='parser script')
parser.add_argument('--serverId', required=True, help='Server ID to find device info')
parser.add_argument('--name', required=True, help='Name Of the Policy')
parser.add_argument('--host', default='any', help='Host of the IP Address')
parser.add_argument('--port', default='any', help='Port used')
parser.add_argument('--proto', default='any', help='Protocol used')
parser.add_argument('--username', default='any', help='Username')
parser.add_argument('--password', default='any', help='Password')
parser.add_argument('--key', default='any', help='')
parser.add_argument('--companyName', default='any', help='Name of the Company')
parser.add_argument('--officeAddress', default='any', help='Address of the Company')
parser.add_argument('--state', default='any', help='State')
parser.add_argument('--country', default='any', help='Country')
parser.add_argument('--ladmin', default='any', help='Local Admin')
parser.add_argument('--phone', default='any', help='Phone Number')
parser.add_argument('--mobile', default='any', help='Mobile Number')
parser.add_argument('--email', default='any', help='Email Address')
parser.add_argument('--designation', default='any', help='Designation of the concerned')
parser.add_argument('--rManager', default='any', help='Reporting Manager of the concerned Person')

args = parser.parse_args()

#--Associating variables to parsed arguments
serverId = str(args.serverId)
name = str(args.name)
host = str(args.host)
port = str(args.port)
proto = str(args.proto)
user = str(args.username)
password = str(args.password)
key = str(args.key)
company = str(args.companyName)
officeAddr = str(args.officeAddress)
state = str(args.state)
country = str(args.country)
ladmin = str(args.ladmin)
phone = str(args.phone)
mobile = str(args.mobile)
email = str(args.email)
designation = str(args.designation)
reportingMgr = str(args.rManager)

def client_program():
    host = socket.gethostname()  # as both code is running on same pc
    port = 8888  # socket server port number

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # instantiate
    client_socket.connect((host, port))  # connect to the server

    sum = serverId+";"+name+";"+host+";"+port+";"+proto+";"+user+";"+password+";"+key+";"+company+";"+officeAddr+";"+state+";"+country+";"+ladmin+";"+phone+";"+mobile+";"+email+";"+designation+";"+reportingMgr

    client_socket.sendall(sum.encode('utf-8'))
    data = client_socket.recv(1024)
    text = str(data)

    print('received:' +text)
    print('closing socket')
    client_socket.close()

if __name__ == '__main__':
    client_program()

when passing arguments through command line like

python dscr.cgi --serverId PA124 --name Devanshu

I get a traceback call as folowing

Traceback (most recent call last):
  File "dscr.cgi", line 90, in <module>
    client_program()
  File "dscr.cgi", line 79, in client_program
    sum = serverId+";"+name+";"+host+";"+port+";"+proto+";"+user+";"+password+";"+key+";"+company+";"+officeAddr+";"+state+";"+country+";"+ladmin+";"+phone+";"+mobile+";"+email+";"+designation+";"+reportingMgr
TypeError: must be str, not int

I realise that its nothing but a silly mistake but I'm unable to find out what. Thanks for the help in advance.

Body:
Your port variable is an int, you must convert it to str first:

You are in fact converting port to a str at some moment, but later assign it to an int in the scope of the function: port = 8888.

Maybe the remnant of some debugging code?

#                                       **here**
    sum = serverId+";"+name+";"+host+";"+str(port)+";"+proto+";"+user+";"+password+";"+key+";"+company+";"+officeAddr+";"+state+";"+country+";"+ladmin+";"+phone+";"+mobile+";"+email+";"+designation+";"+reportingMgr

At @COLDSPEED suggestion, you could group all these arguments and call join on them:

arguments =  [serverId,
              name,
              host,
              str(port),
              proto,
              user,
              password,
              key,
              company,
              officeAddr,
              state,
              country,
              ladmin,
              phone,
              mobile,
              email,
              designation,
              reportingMgr]

print(';'.join(arguments))


问:
NodeJS Change variable from within a function
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

```<code>app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});
</code>```

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

答:
Javascript is Async in nature, so before it fetches  the data you are trying to print it. You can write console.log() inside your callback function.
or please use promises.</p>

Body:
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.


答:
Code Dx accepts application inputs in the following formats (Built-in Code Scanners):

C/C++ source zip archives

Java source zip archives

Java bytecode zip archives

.Net source zip archives

.Net Dlls

Ruby on Rails archieves

PHP zip archives

Python zip archives

JavaScript zip archives

Scala zip archives

You upload a cs file that is not supported, you can include the source files (e.g. .cs) in a zip file and upload the zip file.

Title: How to setup CodeDX plugin for Visual Studio Team Services?

Body:
I have a CodeDx sever running at http://******:82/codedx

This is how my build task looks in VSTS.

And these are the logs for the build:
2017-11-13T22:17:14.6911243Z ==============================================================================
2017-11-13T22:17:14.6911243Z Task         : Code Dx - Upload Files
2017-11-13T22:17:14.6911243Z Description  : Upload files to Code Dx
2017-11-13T22:17:14.6911243Z Version      : 0.1.18
2017-11-13T22:17:14.6911243Z Author       : CodeDx
2017-11-13T22:17:14.6911243Z Help         :
2017-11-13T22:17:14.6911243Z ==============================================================================
2017-11-13T22:17:14.7536277Z Preparing task execution handler.
2017-11-13T22:17:15.8474356Z Executing the powershell script: C:\agent\_work\_tasks\CodeDxUploadFilse_7a5fadd7-438e-4e37-bba4-aac9d265893c\0.1.18\UploadSourceToCodeDx.ps1
2017-11-13T22:17:15.8630563Z Code Dx URL: http://*******:82/codedx
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Project ID: 1
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z API key: **********
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Paths: C:\agent\_work\4\s\***\****\Controllers\AccountController.cs
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Source/binaries filenames:
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Full URL: http://********:82/codedx/api/projects/1/analysis
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Processing C:\agent\_work\4\s\****\****\Controllers\AccountController.cs as file1...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Reading contents of AccountController.cs...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Content size: 45983 bytes
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Building HTTP content...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Building request message...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Sending source to Code Dx...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8942973Z Reading response...
2017-11-13T22:17:15.8942973Z
2017-11-13T22:17:15.8942973Z

2017-11-13T22:17:15.8942973Z Response: {"error":"No appropriate role for file AccountController.cs - it should be removed"}

2017-11-13T22:17:15.8942973Z
2017-11-13T22:17:15.8942973Z
2017-11-13T22:17:15.9411717Z ##[section]Finishing: Code Dx

How do I specify to scan all my files under a project to CodeDx?


问:
Exception handling : Thread v/s Task
Thread version results in unhandled exception, which crashes the app but the task version doesn't. Both are running exactly the same method Can someone explain the reason for this difference in exception behavior ?

Thread version:

```<code>            try
            {
                new Thread(new ThreadStart(DoWork)).Start();  // do work throws exception
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        static void DoWork()
        {
            Console.WriteLine("in thread");
            throw new Exception();
        }
</code>```

Task version:

```<code>      var errorTask = Task.Factory.StartNew<Func<string>>(() =>
                {
                    Console.WriteLine("in task");
                    throw new Exception();
                });

            try
            {
                string result = errorTask.Result();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
</code>```

答:
Thread.Start starts new thread, but you're handling exception in another thread:

```<code>try
{
    // DoWork throws exception in new thread;
    // threads don't catch exceptions out-of-the-box
    new Thread(new ThreadStart(DoWork)).Start();
}
catch (Exception e)
{
    // you're handling exception in "old" thread
    Console.WriteLine(e);
}
</code>```

Task.Factory.StartNew starts new task. Task catches exception inside it to set its Status property:

```<code>var errorTask = Task.Factory.StartNew<Func<string>>(() =>
{
    Console.WriteLine("in task");

    // this exception will be caught in Task's base code,
    // since tasks catch exceptions thrown by task methods;
    // note, that this will be wrapped into AggregateException
    throw new Exception();
});
</code>```

when you're trying to get Task.Result, and task is in faulted state, it just re-throws exception:

```<code>// this will re-throw exception in calling thread
string result = errorTask.Result;
</code>```

That's why your second catch catches it.

Title: Exception handling : Thread v/s Task

Body:
Thread version results in unhandled exception, which crashes the app but the task version doesn't. Both are running exactly the same method Can someone explain the reason for this difference in exception behavior ?

Thread version:

            try
            {
                new Thread(new ThreadStart(DoWork)).Start();  // do work throws exception
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        static void DoWork()
        {
            Console.WriteLine("in thread");
            throw new Exception();
        }

Task version:

      var errorTask = Task.Factory.StartNew<Func<string>>(() =>
                {
                    Console.WriteLine("in task");
                    throw new Exception();
                });

            try
            {
                string result = errorTask.Result();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

Body:
Thread.Start starts new thread, but you're handling exception in another thread:

try
{
    // DoWork throws exception in new thread;
    // threads don't catch exceptions out-of-the-box
    new Thread(new ThreadStart(DoWork)).Start();
}
catch (Exception e)
{
    // you're handling exception in "old" thread
    Console.WriteLine(e);
}

Task.Factory.StartNew starts new task. Task catches exception inside it to set its Status property:

var errorTask = Task.Factory.StartNew<Func<string>>(() =>
{
    Console.WriteLine("in task");

    // this exception will be caught in Task's base code,
    // since tasks catch exceptions thrown by task methods;
    // note, that this will be wrapped into AggregateException
    throw new Exception();
});

when you're trying to get Task.Result, and task is in faulted state, it just re-throws exception:

// this will re-throw exception in calling thread
string result = errorTask.Result;

That's why your second catch catches it.


问:
Lazy list loading with image and text in ionic2
I want to create lazy loading list with image and text. For each row of list, Image could be downloaded from server as separate http request. Please let me know if any caching is required for image download. Please let me know any sample for lazy loading list in ionic2.

Thanks,

答:
Here is a sample code for list

```<code><ion-list no-lines [virtualScroll]="partnerArray">
<ion-item-sliding *virtualItem="let item; let i=index">
  <ion-item (click)="view(i)">
    <ion-avatar item-start>
      <ion-img class="image" src="data:image/*;base64,{{item.imageUrl}}" style="height: 50px; width: 50px"></ion-img>
    </ion-avatar>
    <h2>{{item.name}}</h2>
    <p>{{item.email}}</p>
  </ion-item>
  <ion-item-options>
    <button ion-button color="danger" (click)="delete(i)">
      Delete
    </button>
  </ion-item-options>
</ion-item-sliding>
</code>```

and in .ts file

```<code>private partnerArray: Array<{
id: number
imageUrl: string,
name: string,
email: string
}> = []

 this.odooRpc.searchRead(this.partner,
 this.domain, this.fields, this.limit, this.offset,
 this.sort).then((partner: any) => {
   let json = JSON.parse(partners._body)["result"].records;
   for (let i in json) {
   this.partnerArray.push({
   id: json[i].id,
   imageUrl: json[i].image_small == false ? "N/A":json[i].image_small ,
   name: json[i].name == false ? "N/A" : json[i].name,
   email: json[i].email == false ? "N/A" : json[i].email
 })

}
})
</code>```

This is a code for odoo server. and i have fetch a record from the odoo server.
Hope it helps you

Body:
Here is a sample code for list

<ion-list no-lines [virtualScroll]="partnerArray">
<ion-item-sliding *virtualItem="let item; let i=index">
  <ion-item (click)="view(i)">
    <ion-avatar item-start>
      <ion-img class="image" src="data:image/*;base64,{{item.imageUrl}}" style="height: 50px; width: 50px"></ion-img>
    </ion-avatar>
    <h2>{{item.name}}</h2>
    <p>{{item.email}}</p>
  </ion-item>
  <ion-item-options>
    <button ion-button color="danger" (click)="delete(i)">
      Delete
    </button>
  </ion-item-options>
</ion-item-sliding>

and in .ts file

private partnerArray: Array<{
id: number
imageUrl: string,
name: string,
email: string
}> = []

 this.odooRpc.searchRead(this.partner,
 this.domain, this.fields, this.limit, this.offset,
 this.sort).then((partner: any) => {
   let json = JSON.parse(partners._body)["result"].records;
   for (let i in json) {
   this.partnerArray.push({
   id: json[i].id,
   imageUrl: json[i].image_small == false ? "N/A":json[i].image_small ,
   name: json[i].name == false ? "N/A" : json[i].name,
   email: json[i].email == false ? "N/A" : json[i].email
 })

}
})

This is a code for odoo server. and i have fetch a record from the odoo server.
Hope it helps you


问:
Error 403 Forbidden, When Logged in for almost 5 Minutes in Laravel App
I recently uploaded my laravel project to production server through git. Now Every time I browse my website, it works fine but when I logged in then after 4,5 minutes I start seeing error 403 Forbidden (You don't have permission to access / on this server.)

Then I clear the site's cookies from browser and it works fine again.

What could be the reason ? how can I fix this permanently ? I tried searching on internet and found something which is saying that it has something to do with login session. But I could not figured out what it is. Please help me to resolve this.

答:
Look's like you need to change the default value for the session tokens lifetime in config/session.php

there should be a part like this:

```<code>'lifetime' => 120,
</code>```

Hope it helps o/

Body:
Look's like you need to change the default value for the session tokens lifetime in config/session.php

there should be a part like this:

'lifetime' => 120,

Hope it helps o/


问:
Use different key for searching instead of value or label in react-select in reactJS
I am using react-select as a searchable drop-down in my react app.
I am referring this link https://github.com/JedWatson/react-select.

In the drop-down options structure, it needs label and value keys in the respective object in options.
My problem is, I dont have any label or value in my options data.
I am having different keys altogether.
I want the drop-down to be searched by different key tab.

My React version : 15.6.2

react-select version : 1.0.0-rc.10

My code for drop-down:

```<code><Select
   name="selectSubTag"
   id="selectSubTag"
   value={this.state.selectedFilter.subTag}
   options={this.state.jobSubTags}
   onChange={this.setSubTag}
   placeholder="Select Sub Tag"/>
</code>```

Where my options data looks like below:

```<code>    this.state.jobSubTags = [
{tab:"tabName 1",tabValue:1},
{tab:"tabName 2",tabValue:2},
{tab:"tabName 3",tabValue:3},
]
</code>```

and now I want the data to be searched by 'tab' key in the dropdown.

答: By default the react-select searches over value and label, but if you added additional keys it will also include them in the search, so just iterate over the array and append value label keys equal to the tab key or the tabValue key and it will search upon them all, but remember that for display, the react-select displays the label key content

Body:
I am using react-select as a searchable drop-down in my react app.
I am referring this link https://github.com/JedWatson/react-select.

In the drop-down options structure, it needs label and value keys in the respective object in options.
My problem is, I dont have any label or value in my options data.
I am having different keys altogether.
I want the drop-down to be searched by different key tab.

My React version : 15.6.2

react-select version : 1.0.0-rc.10

My code for drop-down:

<Select
   name="selectSubTag"
   id="selectSubTag"
   value={this.state.selectedFilter.subTag}
   options={this.state.jobSubTags}
   onChange={this.setSubTag}
   placeholder="Select Sub Tag"/>

Where my options data looks like below:

    this.state.jobSubTags = [
{tab:"tabName 1",tabValue:1},
{tab:"tabName 2",tabValue:2},
{tab:"tabName 3",tabValue:3},
]

and now I want the data to be searched by 'tab' key in the dropdown.


问:
jQuery IF statement not working
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

```<code>function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}
</code>```

答:
I use .post(). The third argument of post() is the returned data from the file where the data was posted.

I pass to validate.php the inputed email address, validate.php checks it and if it is valid, it returns 1.

```<code>$('a.post').click(function() {
$.post('validate.php',{email : $("#email-field").val()},

function(data){
if(data==1)
{
//do something if the email is valid
} else {
//do other thing
});

});
</code>```

Hope this helps.

Title: jQuery IF statement not working

Body:
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}

Body:
I use .post(). The third argument of post() is the returned data from the file where the data was posted.

I pass to validate.php the inputed email address, validate.php checks it and if it is valid, it returns 1.

$('a.post').click(function() {
$.post('validate.php',{email : $("#email-field").val()},

function(data){
if(data==1)
{
//do something if the email is valid
} else {
//do other thing
});

});

Hope this helps.


问:
Javascript rock paper scissors project

var rock = rock;
var paper= paper;
var snip = snip;

var playerOneName= prompt("what is your name");
playerOne = choice();
var playerTwoName = prompt("what is your name");
playerTwo=choice();

function choice(pick){
 prompt("rock paper or snip");
}
if(playerOne === rock && playerTwo === snip){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === paper && playerTwo === rock){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === snip && playerTwo === paper){
    alert(playerOneName + " " + "Wins");
}else if(playerTwo === rock && playerOne === snip){
   alert(playerTwoName + " " + "Wins");
}else if(playerTwo === paper && playerOne === rock){
    alert(playerTwoName + " " + "Wins");
}else if(playerTwo === snip && playerOne === paper){
   alert(playerTwoName + " " + "Wins");
}else if(playerOne === playerTwo){
 alert("it's a tie try again");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="rps.js"></script>
</head>
<body>

<ul>
 <li>Rock</li>
 <li>Paper</li>
 <li>Snip</li>
</ul>
</body>
</html></code>```

Hello All,
I'm back with a very new question. For some reason when I run my code for this game of rock paper scissors... it's constantly telling me that player one wins. The issue that I discovered is that it's always choosing the if statement and not the else if. If someone could help that would be great!
Thanks again for your time.Also this is my first week learning javascript... It's kinda of sad that this many people would down vote my question... This is the reason why most people are afraid to ask question fyi...

答:
Try this corrected and verified JavaScript Code -

```<code>var rock = rock;
var paper= paper;
var snip = snip;

var playerOneName= prompt("what is your name");
playerOne = choice();
var playerTwoName = prompt("what is your name");
playerTwo=choice();

alert('Player 1 Chose  - '+ playerOne + 'Player 2 Chose  - '+playerTwo);

function choice(pick){
    return(prompt("rock paper or snip"));  //return the prompt value
}

if(playerOne === 'rock' && playerTwo === 'snip'){
    alert(playerOneName + ' ' + 'Wins');
}else if(playerOne === 'paper' && playerTwo === 'rock'){
    alert(playerOneName + ' ' + 'Wins');
}else if(playerOne === 'snip' && playerTwo === 'paper'){
    alert(playerOneName + ' ' + 'Wins');
}else if(playerTwo === 'rock' && playerOne === 'snip'){
   alert(playerTwoName + ' ' + 'Wins');
}else if(playerTwo === 'paper' && playerOne === 'rock'){
    alert(playerTwoName + ' ' + 'Wins');
}else if(playerTwo === 'snip' && playerOne === 'paper'){
   alert(playerTwoName + ' ' + 'Wins');
}else if(playerOne === playerTwo){
    alert('its a tie try again');
}
</code>```

Corrections -

Return value in choice() function. Prompt has the return value which is to be received and returned in the function.

Alert and check the values for debugging purpose. Always try this to know whats happening inside the code.

Title: Javascript rock paper scissors project

Body:
var rock = rock;
var paper= paper;
var snip = snip;

var playerOneName= prompt("what is your name");
playerOne = choice();
var playerTwoName = prompt("what is your name");
playerTwo=choice();

function choice(pick){
 prompt("rock paper or snip");
}
if(playerOne === rock && playerTwo === snip){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === paper && playerTwo === rock){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === snip && playerTwo === paper){
    alert(playerOneName + " " + "Wins");
}else if(playerTwo === rock && playerOne === snip){
   alert(playerTwoName + " " + "Wins");
}else if(playerTwo === paper && playerOne === rock){
    alert(playerTwoName + " " + "Wins");
}else if(playerTwo === snip && playerOne === paper){
   alert(playerTwoName + " " + "Wins");
}else if(playerOne === playerTwo){
 alert("it's a tie try again");
}

<!doctype html>
<!DOCTYPE html>

 <title></title>

Rock

Paper

Snip

Hello All,
I'm back with a very new question. For some reason when I run my code for this game of rock paper scissors... it's constantly telling me that player one wins. The issue that I discovered is that it's always choosing the if statement and not the else if. If someone could help that would be great!
Thanks again for your time.Also this is my first week learning javascript... It's kinda of sad that this many people would down vote my question... This is the reason why most people are afraid to ask question fyi...

Body:
Try this corrected and verified JavaScript Code -

var rock = rock;
var paper= paper;
var snip = snip;

var playerOneName= prompt("what is your name");
playerOne = choice();
var playerTwoName = prompt("what is your name");
playerTwo=choice();

alert('Player 1 Chose  - '+ playerOne + 'Player 2 Chose  - '+playerTwo);

function choice(pick){
    return(prompt("rock paper or snip"));  //return the prompt value
}

if(playerOne === 'rock' && playerTwo === 'snip'){
    alert(playerOneName + ' ' + 'Wins');
}else if(playerOne === 'paper' && playerTwo === 'rock'){
    alert(playerOneName + ' ' + 'Wins');
}else if(playerOne === 'snip' && playerTwo === 'paper'){
    alert(playerOneName + ' ' + 'Wins');
}else if(playerTwo === 'rock' && playerOne === 'snip'){
   alert(playerTwoName + ' ' + 'Wins');
}else if(playerTwo === 'paper' && playerOne === 'rock'){
    alert(playerTwoName + ' ' + 'Wins');
}else if(playerTwo === 'snip' && playerOne === 'paper'){
   alert(playerTwoName + ' ' + 'Wins');
}else if(playerOne === playerTwo){
    alert('its a tie try again');
}

Corrections -

Return value in choice() function. Prompt has the return value which is to be received and returned in the function.

Alert and check the values for debugging purpose. Always try this to know whats happening inside the code.


问:
Combine Multiple Tables Rows Into Master Table
Happy Monday Everyone!

Have a question and hope you can help. I have a budget spreadsheet that has a budget tab. On this tab is about 8 tables broken down into different categories. Every table in the tab has the exact same columns. Is there a non-vbscript/marco way to create a master table that combines all of the tables into a single table in a different tab. This seems like it would be a no brainer but I have tried everything I can think of and find online and there doesn't seem to be a decent solution without an addon called power query.

答:
If you have Excel 2013 or later, then this is the perfect excuse to go play with PowerQuery, which is now called 'Get & Transform' in the ribbon. You can see something very similar to your requirement in my answer at excel indirect function to read dates and return dynamic values </p>

<p>I strongly suggest you go and look at that thread...even if for some reason you can't use PowerQuery for this particular challenge, because I reckon it's worth seeing just how simple it is to mash together identical tables using PowerQuery, even if just for future reference. It's basically a VBA developer in a box. It's a VBA gimp! </p>

Body:
If you have Excel 2013 or later, then this is the perfect excuse to go play with PowerQuery, which is now called 'Get & Transform' in the ribbon. You can see something very similar to your requirement in my answer at excel indirect function to read dates and return dynamic values

I strongly suggest you go and look at that thread...even if for some reason you can't use PowerQuery for this particular challenge, because I reckon it's worth seeing just how simple it is to mash together identical tables using PowerQuery, even if just for future reference. It's basically a VBA developer in a box. It's a VBA gimp!


问:
Forming linq query to get table data using table name
I have a table name stored in a string.
I want to be able to do something like this:

```<code>string tableName = "sometable";

var query = from m in _Context[tableName]
            select m;
</code>```

I am trawling the internet as I type this...

Any help appreciated.

答:
In your DbContext class, add a method say called Set that returns

```<code>public DbSet Set(string name)
{
  // you may need to fill in the namespace of your context
 return base.Set(Type.GetType(name));
}
</code>```

query like this:

```<code>  using (var db = new YourDataContext())
  {

      var results = db.Set("Namespace.EntityName") .AsQueryable();

  }
</code>```

Body:
I have a table name stored in a string.
I want to be able to do something like this:

string tableName = "sometable";

var query = from m in _Context[tableName]
            select m;

I am trawling the internet as I type this...

Any help appreciated.

Body:
In your DbContext class, add a method say called Set that returns

public DbSet Set(string name)
{
  // you may need to fill in the namespace of your context
 return base.Set(Type.GetType(name));
}

query like this:

  using (var db = new YourDataContext())
  {

      var results = db.Set("Namespace.EntityName") .AsQueryable();

  }


问:
Algorithm to efficiently find horizontal visibility graph (HVG)
Given a series of numbers, represented by vertices, let two vertices, i and j, be connected only if i,j>k for all k between i and j. This graph is called the HVG of the series. In other words, if the bars can "see" each other when plotted like such (ignore the numbers at the bottom):

I'm trying to come up with an efficient algorithm for determining the adjacency matrix of the HVG for a given series.

The algorithm I've currently come up with just uses three for loops, all nested. The outermost loop iterates over all values (placing them in i), then a loop within that iterates over all values that come after i (placing them in j), and then a loop within that which iterates over all values between i and j (placing them in k). Then if the k'th element is greater than either the i'th element or the j'th element, then i and j are not connected, so it moves onto checking the next value of j.

But I feel like there must exist a solution which is more efficient than using three nested loops. I know that if j>i we no longer need to check for any more vertices connected to i (because for all subsequent values of j, there exists a number between i and j that's greater than i)... but unfortunately this alone still gives that a lot of vertices are connected when they shouldn't be.

Is there a better way than my current loop-happy method?

答:
Moving from left to right, maintain a stack of all bars that could be seen by bars to the right of your current position.  The height of bars on the stack will always be decreasing from left to right.

When you encounter a new bar, it can see and be seen by all the bars on the stack with height less than the new height, plus one more.  Mark these edges in your visibility graph.  Then remove all bars with height less than or equal to the new bar (because they can't be seen anymore by bars to the right) and add the new bar.

Total time is O(N), not counting the O(N^2) time to initialize your adjacency matrix with zeros.


问:
Python - How to dynamically exclude a column name from a list of columns of a Panda Dataframe
So far I am able to get the list of all column names present in the dataframe or to get a specific column names based on its datatype, starting letters, etc...

Now my requirement is to get the whole list of column names or a sublist and to exclude one column from it (i.e Target variable / Label Column. This is a part of Machine Learning. So I am using the terms that are used in machine learning)

Please note I am not speaking about the data present in those columns. I am just taking the column names and want to exclude a particular column by its name

Please see below example for better understanding :

```<code># Get all the column names from a Dataframe
df.columns

Index(['transactionID', 'accountID', 'transactionAmountUSD',
       'transactionAmount', 'transactionCurrencyCode',
       'accountAge', 'validationid', 'LABEL'],
      dtype='object')

# Get only the Numeric Variables (Columns with numeric values in it)
df._get_numeric_data().columns

Index(['transactionAmountUSD', 'transactionAmount', 'accountAge', 'LABEL'],
      dtype='object')
</code>```

Now inorder to get remaining column names I am subtracting both the above commands

```<code>string_cols = list(set(list(df.columns))-set(df._get_numeric_data().columns))
</code>```

Ok everything goes well until I hit this.

I have found out that Label column though it has numeric values it should not be present in the list of numeric variables. It should be excluded.

(i.e) I want to exclude a particular column name (not using its index in the list but using its name explicitly)

I tried similar statements like the following ones but in vain. Any inputs on this will be helpful

```<code>set(df._get_numeric_data().columns-set(df.LABEL)
set(df._get_numeric_data().columns-set(df.LABEL.column)
set(df._get_numeric_data().columns-set(df['LABEL'])
</code>```

I am sure I am missing a very basic thing but not able to figure it out.

答:
First of all, you can exclude all numeric columns much more simply with

```<code>pd.DataFrame.select_dtypes(exclude=[np.number])

  transactionID accountID transactionCurrencyCode validationid
0             a         a                       a            a
1             a         a                       a            a
2             a         a                       a            a
3             a         a                       a            a
4             a         a                       a            a
</code>```

Second of all, there are many ways to drop a column.  See this post

```<code>df._get_numeric_data().drop('LABEL', 1)

   transactionAmountUSD  transactionAmount  accountAge
0                     1                  1           1
1                     1                  1           1
2                     1                  1           1
3                     1                  1           1
4                     1                  1           1
</code>```

If you really wanted the columns, use pd.Index.difference

```<code>df._get_numeric_data().columns.difference(['LABEL'])

Index(['accountAge', 'transactionAmount', 'transactionAmountUSD'], dtype='object')
</code>```

Setup

```<code>df = pd.DataFrame(
    [['a', 'a', 1, 1, 'a', 1, 'a', 1]] * 5,
    columns=[
        'transactionID', 'accountID', 'transactionAmountUSD',
        'transactionAmount', 'transactionCurrencyCode',
        'accountAge', 'validationid', 'LABEL']
)
</code>```

Body:
So far I am able to get the list of all column names present in the dataframe or to get a specific column names based on its datatype, starting letters, etc...

Now my requirement is to get the whole list of column names or a sublist and to exclude one column from it (i.e Target variable / Label Column. This is a part of Machine Learning. So I am using the terms that are used in machine learning)

Please note I am not speaking about the data present in those columns. I am just taking the column names and want to exclude a particular column by its name

Please see below example for better understanding :

# Get all the column names from a Dataframe
df.columns

Index(['transactionID', 'accountID', 'transactionAmountUSD',
       'transactionAmount', 'transactionCurrencyCode',
       'accountAge', 'validationid', 'LABEL'],
      dtype='object')

# Get only the Numeric Variables (Columns with numeric values in it)
df._get_numeric_data().columns

Index(['transactionAmountUSD', 'transactionAmount', 'accountAge', 'LABEL'],
      dtype='object')

Now inorder to get remaining column names I am subtracting both the above commands

string_cols = list(set(list(df.columns))-set(df._get_numeric_data().columns))

Ok everything goes well until I hit this.

I have found out that Label column though it has numeric values it should not be present in the list of numeric variables. It should be excluded.

(i.e) I want to exclude a particular column name (not using its index in the list but using its name explicitly)

I tried similar statements like the following ones but in vain. Any inputs on this will be helpful

set(df._get_numeric_data().columns-set(df.LABEL)
set(df._get_numeric_data().columns-set(df.LABEL.column)
set(df._get_numeric_data().columns-set(df['LABEL'])

I am sure I am missing a very basic thing but not able to figure it out.

Body:
First of all, you can exclude all numeric columns much more simply with

pd.DataFrame.select_dtypes(exclude=[np.number])

  transactionID accountID transactionCurrencyCode validationid
0             a         a                       a            a
1             a         a                       a            a
2             a         a                       a            a
3             a         a                       a            a
4             a         a                       a            a

Second of all, there are many ways to drop a column.  See this post

df._get_numeric_data().drop('LABEL', 1)

   transactionAmountUSD  transactionAmount  accountAge
0                     1                  1           1
1                     1                  1           1
2                     1                  1           1
3                     1                  1           1
4                     1                  1           1

If you really wanted the columns, use pd.Index.difference

df._get_numeric_data().columns.difference(['LABEL'])

Index(['accountAge', 'transactionAmount', 'transactionAmountUSD'], dtype='object')

Setup

df = pd.DataFrame(
    [['a', 'a', 1, 1, 'a', 1, 'a', 1]] * 5,
    columns=[
        'transactionID', 'accountID', 'transactionAmountUSD',
        'transactionAmount', 'transactionCurrencyCode',
        'accountAge', 'validationid', 'LABEL']
)


问:
Does Java support Currying?
I was wondering if there is any way to pull that in Java. I think it is not possible without native support for closures.</p>

答:
An another choice is here for Java 6+

```<code>abstract class CurFun<Out> {

    private Out result;
    private boolean ready = false;

    public boolean isReady() {
        return ready;
    }

    public Out getResult() {
        return result;
    }

    protected void setResult(Out result) {
        if (isReady()) {
            return;
        }

        ready = true;
        this.result = result;
    }

    protected CurFun<Out> getReadyCurFun() {
        final Out finalResult = getResult();
        return new CurFun<Out>() {
            @Override
            public boolean isReady() {
                return true;
            }
            @Override
            protected CurFun<Out> apply(Object value) {
                return getReadyCurFun();
            }
            @Override
            public Out getResult() {
                return finalResult;
            }
        };
    }

    protected abstract CurFun<Out> apply(final Object value);
}
</code>```

then you could achieve currying by this way

```<code>CurFun<String> curFun = new CurFun<String>() {
    @Override
    protected CurFun<String> apply(final Object value1) {
        return new CurFun<String>() {
            @Override
            protected CurFun<String> apply(final Object value2) {
                return new CurFun<String>() {
                    @Override
                    protected CurFun<String> apply(Object value3) {
                        setResult(String.format("%s%s%s", value1, value2, value3));
//                        return null;
                        return getReadyCurFun();
                    }
                };
            }
        };
    }
};

CurFun<String> recur = curFun.apply("1");
CurFun<String> next = recur;
int i = 2;
while(next != null && (! next.isReady())) {
    recur = next;
    next = recur.apply(""+i);
    i++;
}

// The result would be "123"
String result = recur.getResult();
</code>```

Title: Does Java support Currying?

Body:
An another choice is here for Java 6+

abstract class CurFun<Out> {

    private Out result;
    private boolean ready = false;

    public boolean isReady() {
        return ready;
    }

    public Out getResult() {
        return result;
    }

    protected void setResult(Out result) {
        if (isReady()) {
            return;
        }

        ready = true;
        this.result = result;
    }

    protected CurFun<Out> getReadyCurFun() {
        final Out finalResult = getResult();
        return new CurFun<Out>() {
            @Override
            public boolean isReady() {
                return true;
            }
            @Override
            protected CurFun<Out> apply(Object value) {
                return getReadyCurFun();
            }
            @Override
            public Out getResult() {
                return finalResult;
            }
        };
    }

    protected abstract CurFun<Out> apply(final Object value);
}

then you could achieve currying by this way

CurFun<String> curFun = new CurFun<String>() {
    @Override
    protected CurFun<String> apply(final Object value1) {
        return new CurFun<String>() {
            @Override
            protected CurFun<String> apply(final Object value2) {
                return new CurFun<String>() {
                    @Override
                    protected CurFun<String> apply(Object value3) {
                        setResult(String.format("%s%s%s", value1, value2, value3));
//                        return null;
                        return getReadyCurFun();
                    }
                };
            }
        };
    }
};

CurFun<String> recur = curFun.apply("1");
CurFun<String> next = recur;
int i = 2;
while(next != null && (! next.isReady())) {
    recur = next;
    next = recur.apply(""+i);
    i++;
}

// The result would be "123"
String result = recur.getResult();


问:
Reload image without refreshing the page
Javascript:

```<code>function atualiza() {
  document.getElementById('badge').innerHTML = location.reload();
}
</code>```

I know the "location.reload()" will refresh the page...

HTML:

```<code><img id="badge" src="<?php echo $cms_url; ?>/imaging/badge.php?badge=$mygroup['badge']; ?>" />
</code>```

I need to freshed the src="" or  without refreshing the page.

答:
For AngularJs, we can add directly in html file like this:

Html:

```<code><div ng-controller="MyCtrl1"><div ng-repeat="img in images"> <img ng-src="{{img.image}}?_={{generatingNewDate}}"></div></div>
</code>```

Ctrl:
$scope.generatingNewDate = new Date().getTime();

You can have a look at this : https://jsfiddle.net/k614L8tt/

Body:
Javascript:

function atualiza() {
  document.getElementById('badge').innerHTML = location.reload();
}

I know the "location.reload()" will refresh the page...

HTML:

<img id="badge" src="<?php echo $cms_url; ?>/imaging/badge.php?badge=$mygroup['badge']; ?>" />

I need to freshed the src="" or  without refreshing the page.

Body:
For AngularJs, we can add directly in html file like this:

Html:

<div ng-controller="MyCtrl1"><div ng-repeat="img in images"> <img ng-src="{{img.image}}?_={{generatingNewDate}}"></div></div>

Ctrl:
$scope.generatingNewDate = new Date().getTime();

You can have a look at this : https://jsfiddle.net/k614L8tt/


问:
Error calling Instagram API in python
I call instagram api but this error How can I solve it?

this is my code:

```<code> params = {
                "access_token" :"xxxxxxxxxxxxxxx",
                "count": 1,
                "q": "xxxxxxxxxxxxxxxx"
            }
            api_uri = 'https://api.instagram.com/v1/users/search'

            req = requests.get(api_uri, params = params)
            searched_user_data = json.loads(req.text)
            logging.info(searched_user_data)
</code>```

This is error code:

```<code>INFO     2017-11-14 05:08:10,743 connectionpool.py:788] Starting new HTTPS
connection (1): api.instagram.com
ERROR    2017-11-14 05:08:11,734 spiderlogic.py:110] ('Connection aborted.',
error(13, 'Permission denied'))
ERROR    2017-11-14 05:08:11,736 baselogic.py:48] Traceback (most recent call
last):
File "D:\Python\GitHub\tagzy\api\logic\spiderlogic.py", line 88, in
__save_instagram_account_info__
req = requests.get(api_uri, params = params)
File "D:\Python\GitHub\tagzy\lib\requests\api.py", line 71, in get
return request('get', url, params=params, **kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\api.py", line 57, in request
return session.request(method=method, url=url, **kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\sessions.py", line 585, in send
r = adapter.send(request, **kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\adapters.py", line 453, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))
</code>```

My sdk version

Google Cloud SDK 177.0.0
app-engine-python 1.9.62 bq 2.0.27 core 2017.10.20 gsutil 4.28

答:
Solution 1:

Downgrade requests module to version 2.1.0 using following command.

pip install requests==2.1.0

Solution 2:

As per official docs you can monkey patch requests to play nicely with Google App Engine.

install requests-toolbelt:

pip install -t lib requests-toolbelt

Then in your main.py file (or equivalent):

```<code>import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
</code>```

Title: Error calling Instagram API in python

Body:
I call instagram api but this error How can I solve it?

this is my code:

 params = {
                "access_token" :"xxxxxxxxxxxxxxx",
                "count": 1,
                "q": "xxxxxxxxxxxxxxxx"
            }
            api_uri = 'https://api.instagram.com/v1/users/search'

            req = requests.get(api_uri, params = params)
            searched_user_data = json.loads(req.text)
            logging.info(searched_user_data)

This is error code:

INFO     2017-11-14 05:08:10,743 connectionpool.py:788] Starting new HTTPS
connection (1): api.instagram.com
ERROR    2017-11-14 05:08:11,734 spiderlogic.py:110] ('Connection aborted.',
error(13, 'Permission denied'))
ERROR    2017-11-14 05:08:11,736 baselogic.py:48] Traceback (most recent call
last):
File "D:\Python\GitHub\tagzy\api\logic\spiderlogic.py", line 88, in
__save_instagram_account_info__
req = requests.get(api_uri, params = params)
File "D:\Python\GitHub\tagzy\lib\requests\api.py", line 71, in get
return request('get', url, params=params, **kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\api.py", line 57, in request
return session.request(method=method, url=url, **kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\sessions.py", line 585, in send
r = adapter.send(request, **kwargs)
File "D:\Python\GitHub\tagzy\lib\requests\adapters.py", line 453, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))

My sdk version

Google Cloud SDK 177.0.0
app-engine-python 1.9.62 bq 2.0.27 core 2017.10.20 gsutil 4.28

Body:
Solution 1:

Downgrade requests module to version 2.1.0 using following command.

pip install requests==2.1.0

Solution 2:

As per official docs you can monkey patch requests to play nicely with Google App Engine.

install requests-toolbelt:

pip install -t lib requests-toolbelt

Then in your main.py file (or equivalent):

import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()


问:
Not getting desired behaviour of translucentstatusbar when navigation drawer is used
I'm getting the desired result of translucentstatusbar when I'm not having a navigation drawer in the activity. But when there is a navigation drawer, the status bar doesn't become translucent as desired. I do not have an AppBar or a ToolBar in the activity.

content_homey.xml

```<code>    <TextView
        android:id="@+id/check_internet_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:text="Please check your internet\n connection and try again"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/try_again_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="TRY AGAIN"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/check_internet_text"
        app:layout_constraintVertical_bias="0.163" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view_home_categories"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <com.arlib.floatingsearchview.FloatingSearchView
        android:id="@+id/floating_search_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="32dp"
        app:floatingSearch_close_search_on_keyboard_dismiss="true"
        app:floatingSearch_leftActionMode="showHamburger"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/recycler_view_home_categories"
        app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>
</code>```

activity_homey.xml

```<code><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme" >

    <include
        layout="@layout/content_homey"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_homey"
        app:menu="@menu/activity_homey_drawer" />

</android.support.v4.widget.DrawerLayout>
</code>```

nav_header_homey.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/AppTheme"
    android:fitsSystemWindows="true">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>
</code>```

v21/styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">false</item>
    <item name="android:windowActivityTransitions">true</item>
    <item name="android:windowContentTransitions">true</item>

    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>

</style>
</code>```

答:
Change

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
     <!-- Customize your theme here. -->
     <item name="colorPrimary">@color/colorPrimary</item>
     <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
     <item name="colorAccent">@color/colorAccent</item>

     <item name="android:windowTranslucentStatus">true</item>
     <item name="android:windowTranslucentNavigation">false</item>
     <item name="android:windowActivityTransitions">true</item>
     <item name="android:windowContentTransitions">true</item>

     <item name="windowActionBar">false</item>
     <item name="windowNoTitle">true</item>

</style>
</code>```

To

```<code><style name="AppTheme" parent="Theme.AppCompat.Light">
     <!-- Customize your theme here. -->
     <item name="colorPrimary">@color/colorPrimary</item>
     <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
     <item name="colorAccent">@color/colorAccent</item>

     <item name="android:windowTranslucentStatus">true</item>
     <item name="android:windowTranslucentNavigation">false</item>
     <item name="android:windowActivityTransitions">true</item>
     <item name="android:windowContentTransitions">true</item>

     <item name="windowActionBar">false</item>
     <item name="windowNoTitle">true</item>

</style>
</code>```

Body:
I'm getting the desired result of translucentstatusbar when I'm not having a navigation drawer in the activity. But when there is a navigation drawer, the status bar doesn't become translucent as desired. I do not have an AppBar or a ToolBar in the activity.

content_homey.xml

    <TextView
        android:id="@+id/check_internet_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:text="Please check your internet\n connection and try again"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/try_again_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="TRY AGAIN"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/check_internet_text"
        app:layout_constraintVertical_bias="0.163" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view_home_categories"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <com.arlib.floatingsearchview.FloatingSearchView
        android:id="@+id/floating_search_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="32dp"
        app:floatingSearch_close_search_on_keyboard_dismiss="true"
        app:floatingSearch_leftActionMode="showHamburger"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/recycler_view_home_categories"
        app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>

activity_homey.xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme" >

    <include
        layout="@layout/content_homey"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_homey"
        app:menu="@menu/activity_homey_drawer" />

</android.support.v4.widget.DrawerLayout>

nav_header_homey.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/AppTheme"
    android:fitsSystemWindows="true">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>

v21/styles.xml

Body:
Change

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
     <!-- Customize your theme here. -->
     <item name="colorPrimary">@color/colorPrimary</item>
     <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
     <item name="colorAccent">@color/colorAccent</item>

     <item name="android:windowTranslucentStatus">true</item>
     <item name="android:windowTranslucentNavigation">false</item>
     <item name="android:windowActivityTransitions">true</item>
     <item name="android:windowContentTransitions">true</item>

     <item name="windowActionBar">false</item>
     <item name="windowNoTitle">true</item>

</style>

To

<style name="AppTheme" parent="Theme.AppCompat.Light">
     <!-- Customize your theme here. -->
     <item name="colorPrimary">@color/colorPrimary</item>
     <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
     <item name="colorAccent">@color/colorAccent</item>

     <item name="android:windowTranslucentStatus">true</item>
     <item name="android:windowTranslucentNavigation">false</item>
     <item name="android:windowActivityTransitions">true</item>
     <item name="android:windowContentTransitions">true</item>

     <item name="windowActionBar">false</item>
     <item name="windowNoTitle">true</item>

</style>


问:
Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.longtailvideo.jwplayer:jwplayer-common:+
I am using the Android code provided by JWPlayer https://github.com/jwplayer/jwplayer-sdk-android-demo. When do I compile this project then I am getting following error.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.longtailvideo.jwplayer:jwplayer-common:+.

Could not resolve com.longtailvideo.jwplayer:jwplayer-common:+.
Required by:
    project :app

Could not resolve com.longtailvideo.jwplayer:jwplayer-common:+.
  Failed to list versions for com.longtailvideo.jwplayer:jwplayer-common.
  Unable to load Maven meta-data from https://mvn.jwplayer.com/content/repositories/releases/com/longtailvideo/jwplayer/jwplayer-common/maven-metadata.xml.
  Could not HEAD 'https://mvn.jwplayer.com/content/repositories/releases/com/longtailvideo/jwplayer/jwplayer-common/maven-metadata.xml'.
  sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
  PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
  timestamp check failed
  NotAfter: Sat Nov 11 19:48:03 IST 2017

答:
It seems the SSL Certificate had expired for mvn.jwplayer.com. It is now back online as I have successfully built my Android Studio project with Maven.

Future reference, you can always use the AAR’s to build your Android Studio Project available in your JWPlayer Dashboard or use the HTTP version of our Maven domain.

```<code>maven {
      url ‘http://mvn.jwplayer.com/content/repositories/releases/’
}
</code>```

Body:
It seems the SSL Certificate had expired for mvn.jwplayer.com. It is now back online as I have successfully built my Android Studio project with Maven.

Future reference, you can always use the AAR’s to build your Android Studio Project available in your JWPlayer Dashboard or use the HTTP version of our Maven domain.

maven {
      url ‘http://mvn.jwplayer.com/content/repositories/releases/’
}