问:
Unable to upload and image in googledrive using goolge ruby API
I am first time using Google APIs. I am unable to upload any file in Google Drive. I tried below complete code.

```<code>require 'google/apis/drive_v2'
require 'google/api_client/client_secrets'

# I downloaded 'client_secrets.json' file from 'https://console.developers.google.com/projectselector/apis/library' and put in lib folder

CLIENT_SECRETS_FILE = "client_secrets.json"
client_secrets_filepath = File.expand_path(CLIENT_SECRETS_FILE ,"#{File.dirname(__FILE__)}/../../lib/")

 CLIENT_SECRETS = Google::APIClient::ClientSecrets.load(client_secrets_filepath)
 authorization = CLIENT_SECRETS.to_authorization

 Drive = Google::Apis::DriveV2
 @drive = Drive::DriveService.new
 @drive.authorization = authorization

file_path = File.expand_path(@ScreenShot_dir)+'/'+"imageName" +'.png'

metadata = Drive::File.new(title: 'My document')
metadata = @drive.insert_file(metadata, upload_source: file_path, content_type: 'image/png')
</code>```

It is not uploading the file in drive but giving an error like "missing authorization code".

my client_secrets.json look like below:

```<code>{"installed":{
"client_id":"<some digits>.apps.googleusercontent.com",
"project_id":"<projectname>","auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"<secret key>",
"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
</code>```

I am not sure what I am missing in it. Appreciate any help on this issue.

答:
"missing authorization code"

Means that you have not properly authenticated your code.

You should check the Ouath2 documentation for the client library.  Get one of the samples there working then you should be able to alter it for Drive without to much trouble.

```<code># AdSense Management API command-line sample.
require 'google/apis/adsense_v1_4'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/storage'
require 'google/api_client/auth/storages/file_store'
require 'logger'
require 'json'

CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"

# Handles authentication and loading of the API.
def setup
  log_file = File.open('adsense.log', 'a+')
  log_file.sync = true
  logger = Logger.new(log_file)
  logger.level = Logger::DEBUG

  adsense = Google::Apis::AdsenseV1_4::AdSenseService.new

  # Stores auth credentials in a file, so they survive multiple runs
  # of the application. This avoids prompting the user for authorization every
  # time the access token expires, by remembering the refresh token.
  # Note: FileStorage is not suitable for multi-user applications.
  storage = Google::APIClient::Storage.new(
    Google::APIClient::FileStore.new(CREDENTIAL_STORE_FILE))
  adsense.authorization = storage.authorize
  if storage.authorization.nil?
    client_secrets = Google::APIClient::ClientSecrets.load
    # The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed
    # application flow, which ties in with Stroage to store credentials
    # between runs.
    flow = Google::APIClient::InstalledAppFlow.new(
      :client_id => client_secrets.client_id,
      :client_secret => client_secrets.client_secret,
      :scope => ['https://www.googleapis.com/auth/adsense.readonly']
    )
    adsense.authorization = flow.authorize(storage)
  end
  return adsense
end

# Generates a report for the default account.
def generate_report(adsense)
  report = adsense.generate_report(start_date: '2011-01-01', end_date: '2011-08-31',
                                   metric: %w(PAGE_VIEWS AD_REQUESTS AD_REQUESTS_COVERAGE
                                              CLICKS AD_REQUESTS_CTR COST_PER_CLICK
                                              AD_REQUESTS_RPM EARNINGS),
                                   dimension: %w(DATE),
                                   sort: %w(+DATE))

  # Display headers.
  report.headers.each do |header|
    print '%25s' % header.name
  end
  puts

  # Display results.
  report.rows.each do |row|
    row.each do |column|
      print '%25s' % column
    end
    puts
  end
end

if __FILE__ == $0
  adsense = setup()
  generate_report(adsense)
end
</code>```

Body:
I am first time using Google APIs. I am unable to upload any file in Google Drive. I tried below complete code.

require 'google/apis/drive_v2'
require 'google/api_client/client_secrets'

# I downloaded 'client_secrets.json' file from 'https://console.developers.google.com/projectselector/apis/library' and put in lib folder

CLIENT_SECRETS_FILE = "client_secrets.json"
client_secrets_filepath = File.expand_path(CLIENT_SECRETS_FILE ,"#{File.dirname(__FILE__)}/../../lib/")

 CLIENT_SECRETS = Google::APIClient::ClientSecrets.load(client_secrets_filepath)
 authorization = CLIENT_SECRETS.to_authorization

 Drive = Google::Apis::DriveV2
 @drive = Drive::DriveService.new
 @drive.authorization = authorization

file_path = File.expand_path(@ScreenShot_dir)+'/'+"imageName" +'.png'

metadata = Drive::File.new(title: 'My document')
metadata = @drive.insert_file(metadata, upload_source: file_path, content_type: 'image/png')

It is not uploading the file in drive but giving an error like "missing authorization code".

my client_secrets.json look like below:

{"installed":{
"client_id":"<some digits>.apps.googleusercontent.com",
"project_id":"<projectname>","auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"<secret key>",
"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}

I am not sure what I am missing in it. Appreciate any help on this issue.

Body:
"missing authorization code"

Means that you have not properly authenticated your code.

You should check the Ouath2 documentation for the client library.  Get one of the samples there working then you should be able to alter it for Drive without to much trouble.

# AdSense Management API command-line sample.
require 'google/apis/adsense_v1_4'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/storage'
require 'google/api_client/auth/storages/file_store'
require 'logger'
require 'json'

CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"

# Handles authentication and loading of the API.
def setup
  log_file = File.open('adsense.log', 'a+')
  log_file.sync = true
  logger = Logger.new(log_file)
  logger.level = Logger::DEBUG

  adsense = Google::Apis::AdsenseV1_4::AdSenseService.new

  # Stores auth credentials in a file, so they survive multiple runs
  # of the application. This avoids prompting the user for authorization every
  # time the access token expires, by remembering the refresh token.
  # Note: FileStorage is not suitable for multi-user applications.
  storage = Google::APIClient::Storage.new(
    Google::APIClient::FileStore.new(CREDENTIAL_STORE_FILE))
  adsense.authorization = storage.authorize
  if storage.authorization.nil?
    client_secrets = Google::APIClient::ClientSecrets.load
    # The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed
    # application flow, which ties in with Stroage to store credentials
    # between runs.
    flow = Google::APIClient::InstalledAppFlow.new(
      :client_id => client_secrets.client_id,
      :client_secret => client_secrets.client_secret,
      :scope => ['https://www.googleapis.com/auth/adsense.readonly']
    )
    adsense.authorization = flow.authorize(storage)
  end
  return adsense
end

# Generates a report for the default account.
def generate_report(adsense)
  report = adsense.generate_report(start_date: '2011-01-01', end_date: '2011-08-31',
                                   metric: %w(PAGE_VIEWS AD_REQUESTS AD_REQUESTS_COVERAGE
                                              CLICKS AD_REQUESTS_CTR COST_PER_CLICK
                                              AD_REQUESTS_RPM EARNINGS),
                                   dimension: %w(DATE),
                                   sort: %w(+DATE))

  # Display headers.
  report.headers.each do |header|
    print '%25s' % header.name
  end
  puts

  # Display results.
  report.rows.each do |row|
    row.each do |column|
      print '%25s' % column
    end
    puts
  end
end

if __FILE__ == $0
  adsense = setup()
  generate_report(adsense)
end


来源: stackexchange

问:
Why is it better to choose Struts 2 than Struts 1?
1) What are the major advantages of preferring Struts 2 over the Struts 1?  What are all the advantages in Struts 1?

2) What is the use of having filter dispatcher in Struts 2?

3) Is it good to use filter dispatcher over servlet(Struts 1 uses servlet)?

As i am new to Struts can anyone give an elaborated description for these questions?

答:
If you are new and not started - DO NOT start with struts 1.

Apache release End of Life message in 2013.

The Apache Struts Project Team would like to inform you that the
  Struts 1.x web framework has reached its end of life and is no longer
  officially supported.

For other questions please post different question(s) if still relevant.

ContentLicense: CC BY-SA 3.0


问:
How to find Android tablet or mobile in Phonegap?
I need set android device smart phone portrait only? window.isTablet is find the mobile or tablet only, so I need to set screen lock orientation and write code too.

答:
If you want to allow potrait mode only, then add -

```<code><platform name="android">
    <preference name="Orientation" value="portrait" />
    <allow-intent href="market:*" />
</platform>
</code>```

inside <widget> tag in config.xml in your project folder.

You may not be able to find Tablet or Mobile version as far as this Cordova Device plugin is considered.

You can get the following properties -

device.cordova  //version of Cordova running on the device.

device.model   //name of the device's model or product

device.platform  //device's operating system name

device.uuid

device.version

device.manufacturer  //the device's manufacturer.

device.isVirtual  //device is virtual(emulated) or real

device.serial

Body:
If you want to allow potrait mode only, then add -

<platform name="android">
    <preference name="Orientation" value="portrait" />
    <allow-intent href="market:*" />
</platform>

inside <widget> tag in config.xml in your project folder.

You may not be able to find Tablet or Mobile version as far as this Cordova Device plugin is considered.

You can get the following properties -

device.cordova  //version of Cordova running on the device.

device.model   //name of the device's model or product

device.platform  //device's operating system name

device.uuid

device.version

device.manufacturer  //the device's manufacturer.

device.isVirtual  //device is virtual(emulated) or real

device.serial


问:
Making calls to web-services on AWS Lambda using Java
I am just trying to call an external web-service from my Java AWS Lambda function.  To do this I can't get the org.apache.http client to work.  I have the code:

```<code>public static String get(String get) throws ClientProtocolException, IOException{
    RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true).build();
    HttpGet httpGetRequest = new HttpGet(get);
    RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
    httpGetRequest.setConfig(requestConfig);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse httpResponse = httpClient.execute(httpGetRequest); <<<<<
    HttpEntity entity = httpResponse.getEntity();
    StringBuffer all = new StringBuffer();
    if (entity != null) {
        InputStream inputStream = entity.getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream)));
        String read;
        while ((read = in.readLine()) != null){
            all.append(read);
            all.append("\n");
        }
        httpClient.close();
    }
    return all.toString();
}
</code>```

Once it is deployed it hangs on the line HttpResponse httpResponse = httpClient.execute(httpGetRequest); <<<<< above.

I can prove that I have connectivity from the lambda function to the internet by setting up a Socket connection e.g. Socket s = new Socket(InetAddress.getByName("bbc.co.uk"), 80); and I can retrieve data this way.

So the question is either what is wrong with the first code fragment which works locally but not when deployed? or is there a preferred way to call web-services from AWS lambda functions in Java (I have had a search but can't find a best practice) ?  I would prefer not to have to hand craft the HTTP requests using Sockets if I can help it.

答:
```<code>try {
    String url = "baseurl for AWS insatnce +8080/Testing/mailGenration/generate?msg=20;

    logger.log("Building HttpClient......");
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);

    HttpResponse response = client.execute(request);
    logger.log("Response Code : " + response.getStatusLine().getStatusCode());
} catch (Exception e) {
    logger.log("Exception in sendhttpclient:" + e);
}
</code>```

Body:
I am just trying to call an external web-service from my Java AWS Lambda function.  To do this I can't get the org.apache.http client to work.  I have the code:

public static String get(String get) throws ClientProtocolException, IOException{
    RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true).build();
    HttpGet httpGetRequest = new HttpGet(get);
    RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
    httpGetRequest.setConfig(requestConfig);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse httpResponse = httpClient.execute(httpGetRequest); <<<<<
    HttpEntity entity = httpResponse.getEntity();
    StringBuffer all = new StringBuffer();
    if (entity != null) {
        InputStream inputStream = entity.getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream)));
        String read;
        while ((read = in.readLine()) != null){
            all.append(read);
            all.append("\n");
        }
        httpClient.close();
    }
    return all.toString();
}

Once it is deployed it hangs on the line HttpResponse httpResponse = httpClient.execute(httpGetRequest); <<<<< above.

I can prove that I have connectivity from the lambda function to the internet by setting up a Socket connection e.g. Socket s = new Socket(InetAddress.getByName("bbc.co.uk"), 80); and I can retrieve data this way.

So the question is either what is wrong with the first code fragment which works locally but not when deployed? or is there a preferred way to call web-services from AWS lambda functions in Java (I have had a search but can't find a best practice) ?  I would prefer not to have to hand craft the HTTP requests using Sockets if I can help it.


问:
How to place image correctly in input tag
I created a input tag with two images cross and arrow.

Here is my code.

```<code><div id="chart_line" style="position: relative;">
    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">
        <div id="triggers">
            <img class="trigger" onclick="deleteValue()" src="css/clearT.png" id="cross">
            <img class="trigger" src="css/combo_arrow.png" onclick="openingList()" id="arrow">
        </div>
</div>
</code>```

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks

答:
You need to add position:relative to your parent div and to input and triggers add position:absolute.

Then add width: 100% to your input to take all the place of parent div and add right: 5px to your triggers to place them to the right.

And at the end add some padding to your input to avoid that text goes onder the trigger images.

Thus, something like this :

* {
  box-sizing: border-box;
}

#chart_line {
  position: relative;
  width: 30%;
}

#myInput {
  position: absolute;
  border: 1px solid #95B8E7;
  height: 30px;
  width: 100%;
  padding-right: 50px;
}

#triggers {
  position: absolute;
  right: 5px;
  top: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="chart_line">
  <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" />
  <div id="triggers">
    <img onclick="deleteValue()" src="css/clearT.png" id="cross">
    <img src="css/combo_arrow.png" onclick="openingList()" id="arrow">
  </div>
</div></code>```

Here can you play with it. Fiddle.

Body:
I created a input tag with two images cross and arrow.

Here is my code.

    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks

Body:
You need to add position:relative to your parent div and to input and triggers add position:absolute.

Then add width: 100% to your input to take all the place of parent div and add right: 5px to your triggers to place them to the right.

And at the end add some padding to your input to avoid that text goes onder the trigger images.

Thus, something like this :

* {
  box-sizing: border-box;
}

#chart_line {
  position: relative;
  width: 30%;
}

#myInput {
  position: absolute;
  border: 1px solid #95B8E7;
  height: 30px;
  width: 100%;
  padding-right: 50px;
}

#triggers {
  position: absolute;
  right: 5px;
  top: 5px;
}

<div id="chart_line">
  <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" />
  <div id="triggers">
    <img onclick="deleteValue()" src="css/clearT.png" id="cross">
    <img src="css/combo_arrow.png" onclick="openingList()" id="arrow">
  </div>
</div>

Here can you play with it. Fiddle.


问:
Highlight multiple fields on validate javascript
I want when textfields empty it will highlight it. Following is my code its only highlight one field at one time. If both fields empty it will highlight one field.

```<code><script>
function ValidateForm(){

    var summary=document.getElementById("<%=summary.ClientID%>");
    if (summary.value == "" && txtTest.value == "") {
        summary.style.backgroundColor = "Yellow";
        return false;
    }
    var txtTest = document.getElementById("<%=txtTest.ClientID%>");
    if (txtTest.value == "" ) {

        txtTest.style.backgroundColor = "Yellow";
        return false;
    }

   return true;

}
</script>
</code>```

Please help me to solve this problem. I don't want to use default validators.

答:
that is because you are returning false before checking for the second input. you need to return true or false only after all inputs have been checked.  Also you must first get txtTest before checking for its value. you can do something like this:

```<code><script>
function ValidateForm(){

    var validate = true;

    var summary=document.getElementById("<%=summary.ClientID%>");
    if (summary.value == "") {
        summary.style.backgroundColor = "Yellow";
        validate = false;
    }
    var txtTest = document.getElementById("<%=txtTest.ClientID%>");
    if (txtTest.value == "" ) {

        txtTest.style.backgroundColor = "Yellow";
        validate = false;
    }

   return validate;

}
</script>
</code>```

Body:
I want when textfields empty it will highlight it. Following is my code its only highlight one field at one time. If both fields empty it will highlight one field.

Please help me to solve this problem. I don't want to use default validators.

Body:
that is because you are returning false before checking for the second input. you need to return true or false only after all inputs have been checked.  Also you must first get txtTest before checking for its value. you can do something like this:

<script>
function ValidateForm(){

    var validate = true;

    var summary=document.getElementById("<%=summary.ClientID%>");
    if (summary.value == "") {
        summary.style.backgroundColor = "Yellow";
        validate = false;
    }
    var txtTest = document.getElementById("<%=txtTest.ClientID%>");
    if (txtTest.value == "" ) {

        txtTest.style.backgroundColor = "Yellow";
        validate = false;
    }

   return validate;

}
</script>


问:
How to edit the top level default.aspx in WSS3 site with VS(2010)?
I can open the default.aspx of a sub-site no problem.( file open,type or browse to the url )

BUT I can't open the default.aspx of the top-level site or a WSS site, in VS2010.

I have to use SPD.

Is there a permission to set somewhere?

答:
You can edit sharepoint sites in VS 2010. Indirect way would be to download default.aspx, edit in VS 2010 and upload it back. However its cumbersome and not recommended.

SharePoint Designer is the preferred way to edit Sharepoint sitse.

ContentLicense: CC BY-SA 2.5


问:
MySQL - At least one of something and greater than between 3 tables
I have 3 tables :

I need to retrieve the name of the sellers that have sold during January AT LEAST one product where the total amount of sales of this said product during January is greater than 1000.

I thought about starting like this :

```<code>SELECT c.nom, c.prenom
FROM Commerciaux c
LEFT JOIN Ventes v ON c.id_commerciaux = v.id_commerciaux
WHERE  EXISTS (SELECT 1
FROM Produits p, Ventes v
WHERE p.id_produits = v.id_produits
AND MONTH(v.date) = 1
GROUP BY p.nom
HAVING SUM(v.montant) > 200)
AND MONTH(v.date) = 1
GROUP BY c.nom, c.prenom
</code>```

The SELECT in the WHERE EXISTS seems to be working, but when I have to get link the table Sellers, I don't know how to write it.

Any help would be great !

答:
try this </p>

```<code>SELECT C.name
FROM Sales A
JOIN Product B ON A.produit_id  = B.id
JOIN Seller C ON A.commercial_id = C.id
WHERE MONTH(A.date) = 1
HAVING SUM(A.nAmount) > 100
GROUP BY C.name
</code>```

Body:
I have 3 tables :

I need to retrieve the name of the sellers that have sold during January AT LEAST one product where the total amount of sales of this said product during January is greater than 1000.

I thought about starting like this :

SELECT c.nom, c.prenom
FROM Commerciaux c
LEFT JOIN Ventes v ON c.id_commerciaux = v.id_commerciaux
WHERE  EXISTS (SELECT 1
FROM Produits p, Ventes v
WHERE p.id_produits = v.id_produits
AND MONTH(v.date) = 1
GROUP BY p.nom
HAVING SUM(v.montant) > 200)
AND MONTH(v.date) = 1
GROUP BY c.nom, c.prenom

The SELECT in the WHERE EXISTS seems to be working, but when I have to get link the table Sellers, I don't know how to write it.

Any help would be great !

Body:
try this

SELECT C.name
FROM Sales A
JOIN Product B ON A.produit_id  = B.id
JOIN Seller C ON A.commercial_id = C.id
WHERE MONTH(A.date) = 1
HAVING SUM(A.nAmount) > 100
GROUP BY C.name


问:
How to parse a file matching all the lines for a string and keep track of count?
We have a file with following lines in it,
we need to find all the lines with "Error" message type..
save the message and its count and print the messages in the descending order of count,can anyone provide guidance on how to do this?

file.txt

```<code><TIMESTAMP><MESSAGETYPE><MESSAGE>
<4:02><ERROR><Error message1>
<14:13><Error><Error message2>
<10:03><Warning><Warning message1>
<12:03><Warning><Warning message2>
</code>```

CODE:-

答:
Open the file and read all lines

```<code>with open("file.txt") as f:
    lines = f.read().splitlines()
</code>```

Make a list of lines that contain the word "Error"

```<code>data = [ line.lstrip('<').rstrip('>').split('><') for line in lines if 'Error' in line  ]
</code>```

Get the time and message items from the data list

```<code>errors = [ { 'time' : line[0], 'message': line[-1] } for line in data ]
</code>```

Sort the errors list by 'time' in descending order

```<code>errors.sort(key=lambda e : e['time'], reverse=True)
</code>```

Note that errors is a list of dictionaries, you can use lists if you like.

If you want to print the results :

```<code>print '\n'.join( 'Time {:8} Error {}'.format(e['time'], e['message']) for e in errors )
</code>```

Output :

```<code>Time: 4:02   Error: Error message1
Time: 14:13  Error: Error message2
</code>```

Body:
We have a file with following lines in it,
we need to find all the lines with "Error" message type..
save the message and its count and print the messages in the descending order of count,can anyone provide guidance on how to do this?

file.txt

<TIMESTAMP><MESSAGETYPE><MESSAGE>
<4:02><ERROR><Error message1>
<14:13><Error><Error message2>
<10:03><Warning><Warning message1>
<12:03><Warning><Warning message2>

CODE:-

Body:
Open the file and read all lines

with open("file.txt") as f:
    lines = f.read().splitlines()

Make a list of lines that contain the word "Error"

data = [ line.lstrip('<').rstrip('>').split('><') for line in lines if 'Error' in line  ]

Get the time and message items from the data list

errors = [ { 'time' : line[0], 'message': line[-1] } for line in data ]

Sort the errors list by 'time' in descending order

errors.sort(key=lambda e : e['time'], reverse=True)

Note that errors is a list of dictionaries, you can use lists if you like.

If you want to print the results :

print '\n'.join( 'Time {:8} Error {}'.format(e['time'], e['message']) for e in errors )

Output :

Time: 4:02   Error: Error message1
Time: 14:13  Error: Error message2


问:
PHP, SQL Insert no works
i would like to know why i am not able to insert new data to my Database.
in vardump i get good result but nothing is added to my database

Database : c_id = AutoInc. | a_id | u_id | c_head | c_content | c_date
  =TIMESTAMP

```<code>if (isset($_POST['c_submit'])) {
   $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
   $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
   if (mysqli_num_rows($vysledokHladania) == 1) {
       while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], $_POST[c_hlavicka], $_POST[c_obsah], 'NOW()')";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}
</code>```

答:
You can use date('Y-m-d h:i:s') to store current date time in our DB by PHP code and in your query you just missed to put '' in array index.

Try this one

```<code>if (isset($_POST['c_submit'])) {
    $date=date('Y-m-d h:i:s');
    $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '".$_SESSION['username']."'";
    $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
    if (mysqli_num_rows($vysledokHladania) == 1) {
        while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES
                                (".$_GET['a_id'].",".$db_data_prihlaseneho_uzivatela['u_id']." ,".$_POST['c_hlavicka']." ,".$_POST['c_obsah']." ,$date)";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}
</code>```

I thing it will help you.

Title: PHP, SQL Insert no works

Body:
i would like to know why i am not able to insert new data to my Database.
in vardump i get good result but nothing is added to my database

Database : c_id = AutoInc. | a_id | u_id | c_head | c_content | c_date
  =TIMESTAMP

if (isset($_POST['c_submit'])) {
   $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
   $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
   if (mysqli_num_rows($vysledokHladania) == 1) {
       while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], $_POST[c_hlavicka], $_POST[c_obsah], 'NOW()')";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}

Body:
You can use date('Y-m-d h:i:s') to store current date time in our DB by PHP code and in your query you just missed to put '' in array index.

Try this one

if (isset($_POST['c_submit'])) {
    $date=date('Y-m-d h:i:s');
    $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '".$_SESSION['username']."'";
    $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
    if (mysqli_num_rows($vysledokHladania) == 1) {
        while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES
                                (".$_GET['a_id'].",".$db_data_prihlaseneho_uzivatela['u_id']." ,".$_POST['c_hlavicka']." ,".$_POST['c_obsah']." ,$date)";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}

I thing it will help you.


问:
How can I find all subsets of a list which have specific items?
I am working on a program which I need to repeatedly make a subset list with 2 items out of a list with n items.

for example let's assume this is the list (The actual list has more items):

list = [50, 100, 250, 500, 750, 1000, 2000]

I need a function which takes list and a number like 2 and then give back a list like this:

[[50,100], [50,250], [50, 500], [50, 750], [50, 1000], [50, 2000], [100, 250],...]

As you can see I don't want items with the same numbers in the answer like [50,100], [100, 50].

I figure this out as the algorithm for finding All the subsets of list:

```<code>from itertools import chain, combinations

   def powerset(iterable):

     xs = list(iterable)
     return list(chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)))
</code>```

Thanks for the helps.

Body:
I am working on a program which I need to repeatedly make a subset list with 2 items out of a list with n items.

for example let's assume this is the list (The actual list has more items):

list = [50, 100, 250, 500, 750, 1000, 2000]

I need a function which takes list and a number like 2 and then give back a list like this:

[[50,100], [50,250], [50, 500], [50, 750], [50, 1000], [50, 2000], [100, 250],...]

As you can see I don't want items with the same numbers in the answer like [50,100], [100, 50].

I figure this out as the algorithm for finding All the subsets of list:

from itertools import chain, combinations

   def powerset(iterable):

     xs = list(iterable)
     return list(chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)))

Thanks for the helps.

Body:
What's wrong with combinations(l,2) ?

print list(combinations(l,2))
# [(50, 100), (50, 250), (50, 500), (50, 750), (50, 1000), (50, 2000), (100, 250), (100, 500), (100, 750), (100, 1000), (100, 2000), (250, 500), (250, 750), (250, 1000), (250, 2000), (500, 750), (500, 1000), (500, 2000), (750, 1000), (750, 2000), (1000, 2000)]


问:
Clean approach to finding a folder's parent
I have this piece of code that searches for a folder given a starting directory. Once the folder is found I need the name of it's parent. The following piece of code works but it is terribly ugly. I have a flag, "sessionFound" to assist with breaking from nested foreach loops. The following works. I was hoping I could get some eyes on this and see if I could get some suggestions on how to make this less verbose and a bit more concise.

Thanks.

```<code>    private void SetProjectFolder(string sessionid)
        {

//IoC container gives the root directory to begin search.
            string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);
            bool sessionFound = false;

            foreach (string directory in supportDirs)
            {
                if (!sessionFound)
                {
                    foreach (string folder in Directory.GetDirectories(directory))
                    {
                        if (!sessionFound)
                        {
                            foreach (string productSubFolder in Directory.GetDirectories(folder))
                            {
                                if (productSubFolder.Contains(sessionid))
                                {
                                    _productName = Directory.GetParent(productSubFolder).Parent.Name;
                                    sessionFound = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }
</code>```

答:
By removing sessionFound you end up with a pretty clear and straightforward code:

```<code>private void SetProjectFolder(string sessionid)
{
    //IoC container gives the root directory to begin search.
    string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);

    // search for product subfolder
    foreach (string directory in supportDirs)
    {
        foreach (string folder in Directory.GetDirectories(directory))
        {
            foreach (string productSubFolder in Directory.GetDirectories(folder))
            {
                if (productSubFolder.Contains(sessionid))
                {
                    // product sub-folder found, set it and exit
                    _productName = Directory.GetParent(productSubFolder).Parent.Name;
                    return;
                }
            }
        }
    }

    // product sub-folder not found
    !!! handle error path
}
</code>```

In case your directory structure is static in the sense of the abovementioned search algorithm, I don't think there's something wrong with the nested foreach statements. Maybe you could extract the code starting with the middle foreach into a separate method like string FindProductSubfolderInFolder(Directory).

Body:
I have this piece of code that searches for a folder given a starting directory. Once the folder is found I need the name of it's parent. The following piece of code works but it is terribly ugly. I have a flag, "sessionFound" to assist with breaking from nested foreach loops. The following works. I was hoping I could get some eyes on this and see if I could get some suggestions on how to make this less verbose and a bit more concise.

Thanks.

    private void SetProjectFolder(string sessionid)
        {

//IoC container gives the root directory to begin search.
            string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);
            bool sessionFound = false;

            foreach (string directory in supportDirs)
            {
                if (!sessionFound)
                {
                    foreach (string folder in Directory.GetDirectories(directory))
                    {
                        if (!sessionFound)
                        {
                            foreach (string productSubFolder in Directory.GetDirectories(folder))
                            {
                                if (productSubFolder.Contains(sessionid))
                                {
                                    _productName = Directory.GetParent(productSubFolder).Parent.Name;
                                    sessionFound = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }

Body:
By removing sessionFound you end up with a pretty clear and straightforward code:

private void SetProjectFolder(string sessionid)
{
    //IoC container gives the root directory to begin search.
    string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);

    // search for product subfolder
    foreach (string directory in supportDirs)
    {
        foreach (string folder in Directory.GetDirectories(directory))
        {
            foreach (string productSubFolder in Directory.GetDirectories(folder))
            {
                if (productSubFolder.Contains(sessionid))
                {
                    // product sub-folder found, set it and exit
                    _productName = Directory.GetParent(productSubFolder).Parent.Name;
                    return;
                }
            }
        }
    }

    // product sub-folder not found
    !!! handle error path
}

In case your directory structure is static in the sense of the abovementioned search algorithm, I don't think there's something wrong with the nested foreach statements. Maybe you could extract the code starting with the middle foreach into a separate method like string FindProductSubfolderInFolder(Directory).


问:
Creating custom LockScreen in android
I am developing custom lockscreen app.its working fine in below 4.0 but above 4.0,when we press home button the app stops.is there any solution for this no apps will stop when pressing home button untill unlocking the screen.(like go locker app)</p>

答:
I think first of all you should ask yourself if you really want to hijack the home key. Sometimes you may want it. But I think placing the app on the Android lock screen, letting the home key act normally and letting the underlying Android lock screen take care of password-protecting the device is what you actually want in a lot of cases (unless you want to change the way this is done by default).

Bottom line, letting an app be displayed on the Android lock screen comes pretty close to writing your own custom lock screen. And is decidedly easier since you don't have to manage passwords yourself. Not to mention it's safer and more reliable since you don't hijack the home key.

I did it like this and it works very well. You can see the details here:

show web site on Android lock screen

The question is about displaying a website on the lock screen, since that's what I was interested in, but the answer is more general, it works with any app.
You can see here an app that's on Google Play and has been written like this:

https://play.google.com/store/apps/details?id=com.a50webs.intelnav.worldtime

Title: Creating custom LockScreen in android


问:
Javascript JSON.Stringify() what is undefined
I am using JSON.Stringify() in my javascript...

```<code>var jsonProp;
var json = { };
json.prop= { };
json.prop.Brand = $('.Brand' + val).val();
json.prop.Name = $('.Name' + val).val();
json.prop.Desc = $('.Desc' + val).val();
json.prop.Address = $('.Address' + val).val();
json.prop.Phone = $('.Phone' + val).val();
json.prop.Tag = $('.Tag' + val).val();
json.prop.City = $('.City' + val).val();
json.prop.Status = $('.Status' + val).val();
jsonProp = jsonProp + JSON.stringify(json);
</code>```

and the result is :

```<code>"undefined{"prop":{"Brand":"","Name":"apotik AA","Desc":"","Address":"Address","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}
{"prop":{"Brand":"","Name":"apotik AAaaaa. Bina Farma","Desc":"","Address":"Jl. RA. Kartini, Margahayu-Bekasi Tim., Kota Bks, Jawa Barat 17113","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}"
</code>```

why is "undefined" there? how can I set it? all I want to have is a JSONArray like this :

```<code>Prop{{"Brand":"value","Name":"value"},{"Brand":"value","Name":"value"}}
</code>```

Please help

答:
Your variable jsonBiz wasn't defined yet.

So when you do

```<code>jsonBiz = jsonBiz + JSON.stringify(json)
</code>```

You add an undefined value and a string. The first value is turned into the string "undefined", and the two are added.

Body:
I am using JSON.Stringify() in my javascript...

var jsonProp;
var json = { };
json.prop= { };
json.prop.Brand = $('.Brand' + val).val();
json.prop.Name = $('.Name' + val).val();
json.prop.Desc = $('.Desc' + val).val();
json.prop.Address = $('.Address' + val).val();
json.prop.Phone = $('.Phone' + val).val();
json.prop.Tag = $('.Tag' + val).val();
json.prop.City = $('.City' + val).val();
json.prop.Status = $('.Status' + val).val();
jsonProp = jsonProp + JSON.stringify(json);

and the result is :

"undefined{"prop":{"Brand":"","Name":"apotik AA","Desc":"","Address":"Address","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}
{"prop":{"Brand":"","Name":"apotik AAaaaa. Bina Farma","Desc":"","Address":"Jl. RA. Kartini, Margahayu-Bekasi Tim., Kota Bks, Jawa Barat 17113","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}"

why is "undefined" there? how can I set it? all I want to have is a JSONArray like this :

Prop{{"Brand":"value","Name":"value"},{"Brand":"value","Name":"value"}}

Please help

Body:
Your variable jsonBiz wasn't defined yet.

So when you do

jsonBiz = jsonBiz + JSON.stringify(json)

You add an undefined value and a string. The first value is turned into the string "undefined", and the two are added.


问:
Will this function cause dead-lock in multi-thread conditions?
Will this function cause dead-lock in multi-thread conditions?  What's the problem of this code?

This code tries to connect a website through a given proxy in order to decide if this proxy is usable(the response code should be 200 if usable).

But this function will never return in some time.

```<code>public static boolean verifyProxy(String ip, int port ){
  boolean useful;
  try {
    URL url = new URL(VERIFY_URL);
    InetSocketAddress addr = new InetSocketAddress(ip, port);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
    connection.setConnectTimeout(4 * 1000);
    int rCode = connection.getResponseCode();
    connection.disconnect();
    useful =  rCode == 200;
  } catch (IOException e1){
    logger.warn(String.format("verify proxy %s:%d exception: "+e1.getMessage(),ip, port));
            useful = false;
  }
  logger.info(String.format("verify proxy %s:%d useful: "+useful, ip, port));
  return useful;
}
</code>```

答:
Dead-locks occur when more than one thread tries to enter a mutex.

Meaning: a section of code that is somehow guarded. Either implicitly, because the synchronized is used; or by explicitly acquiring a lock from some lock object.

The code you are showing here does nothing like that.

No locking translates to: no dead-locking either.

Given the latest comment by the OP: as said; you can't have a dead-lock. So when this code hangs, the obvious reason: a network problem. Yes, networking can result in all kinds of strange problems.

And reading the javadoc, I am wondering if there is a way for you to call connect() after setting that timeout.

Body:
Will this function cause dead-lock in multi-thread conditions?  What's the problem of this code?

This code tries to connect a website through a given proxy in order to decide if this proxy is usable(the response code should be 200 if usable).

But this function will never return in some time.

public static boolean verifyProxy(String ip, int port ){
  boolean useful;
  try {
    URL url = new URL(VERIFY_URL);
    InetSocketAddress addr = new InetSocketAddress(ip, port);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
    connection.setConnectTimeout(4 * 1000);
    int rCode = connection.getResponseCode();
    connection.disconnect();
    useful =  rCode == 200;
  } catch (IOException e1){
    logger.warn(String.format("verify proxy %s:%d exception: "+e1.getMessage(),ip, port));
            useful = false;
  }
  logger.info(String.format("verify proxy %s:%d useful: "+useful, ip, port));
  return useful;
}


问:
Show/hide a record based on condition inside ng-repeat not working
Below are my records :

```<code>$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];
</code>```

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <ul ng-app="myApp" ng-controller="MyController">
     <li ng-repeat="item in records">
         <div ng-show="currentSelection=='Admin' && item.id=='Statistics'">{{item.id}}
         </div>
    </li>
</ul></code>```

答:
You can put a check on li tag itself. no need of extra div to put check. This will remove blank li bulltes.

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Admin";

 $scope.records = [
{ id: 'Employee', params:[]},
{ id: 'Skills', params:[]},
{ id: 'Payroll', params:[]},
{ id: 'Appraisal', params:[]},
{ id : 'Statistics',params:[]}
];

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

 <ul ng-app="myApp" ng-controller="MyController">
     <li ng-repeat="item in records" ng-if="currentSelection=='Admin' && item.id!=='Statistics'">
         <div >{{item.id}}
          </div>
    </li>
</ul></code>```

Body:
Below are my records :

$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });

{{item.id}}

Body:
You can put a check on li tag itself. no need of extra div to put check. This will remove blank li bulltes.

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Admin";

 $scope.records = [
{ id: 'Employee', params:[]},
{ id: 'Skills', params:[]},
{ id: 'Payroll', params:[]},
{ id: 'Appraisal', params:[]},
{ id : 'Statistics',params:[]}
];

        });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

 <ul ng-app="myApp" ng-controller="MyController">
     <li ng-repeat="item in records" ng-if="currentSelection=='Admin' && item.id!=='Statistics'">
         <div >{{item.id}}
          </div>
    </li>
</ul>


问:
How to access remote hive using pyhive
Used this link to try to connect to a remote hive. Below is the code used. The error msg received is also given below

How to Access Hive via Python?

Code

```<code>   from pyhive import hive
    conn = hive.Connection(host="10.111.22.11", port=10000, username="user1" ,database="default")
</code>```

Error msg

```<code>Could not connect to any of [('10.111.22.11', 10000)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda3/lib/python3.6/site-packages/pyhive/hive.py", line 131, in __init__
    self._transport.open()
  File "/opt/anaconda3/lib/python3.6/site-packages/thrift_sasl/__init__.py", line 61, in open
    self._trans.open()
  File "/opt/anaconda3/lib/python3.6/site-packages/thrift/transport/TSocket.py",line 113, in open
    raise TTransportException(TTransportException.NOT_OPEN, msg)
thrift.transport.TTransport.TTransportException: Could not connect to any of [('10.111.22.11', 10000)]
</code>```

What are the other requirements for successful connection? I am able to connect to the server directly (using putty) and run hive. But when tried from another server X i get this error. Also i can ping the hive server from server X.

Could the port number be the problem? How do i check the correct port number?

As discussed in the below answer i tried to start hiveserver2 . But the command doesnt seem to work. Any help is really appreciated.

Also the port i see in the log when i execute a query from hive shell is 8088. wonder if this should be the port instead of 10000(both did not work anyway)

答:
Could not make it work using pyhive. Had to use paramiko insted
below is the sample code

```<code>import os
import paramiko
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect('1.1.1.1', username='uid', password='pwd')
sshin, sshout, ssherr= ssh.exec_command('hive -e "create table test(key varchar(10),keyval varchar(200))"')
</code>```

Title: How to access remote hive using pyhive

Body:
Used this link to try to connect to a remote hive. Below is the code used. The error msg received is also given below

How to Access Hive via Python?

Code

   from pyhive import hive
    conn = hive.Connection(host="10.111.22.11", port=10000, username="user1" ,database="default")

Error msg

Could not connect to any of [('10.111.22.11', 10000)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda3/lib/python3.6/site-packages/pyhive/hive.py", line 131, in __init__
    self._transport.open()
  File "/opt/anaconda3/lib/python3.6/site-packages/thrift_sasl/__init__.py", line 61, in open
    self._trans.open()
  File "/opt/anaconda3/lib/python3.6/site-packages/thrift/transport/TSocket.py",line 113, in open
    raise TTransportException(TTransportException.NOT_OPEN, msg)
thrift.transport.TTransport.TTransportException: Could not connect to any of [('10.111.22.11', 10000)]

What are the other requirements for successful connection? I am able to connect to the server directly (using putty) and run hive. But when tried from another server X i get this error. Also i can ping the hive server from server X.

Could the port number be the problem? How do i check the correct port number?

As discussed in the below answer i tried to start hiveserver2 . But the command doesnt seem to work. Any help is really appreciated.

Also the port i see in the log when i execute a query from hive shell is 8088. wonder if this should be the port instead of 10000(both did not work anyway)

Body:
Could not make it work using pyhive. Had to use paramiko insted
below is the sample code

import os
import paramiko
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect('1.1.1.1', username='uid', password='pwd')
sshin, sshout, ssherr= ssh.exec_command('hive -e "create table test(key varchar(10),keyval varchar(200))"')


问:
VSTS Release Manager copy only specific files
I want to download a specific folder from my team project in VSTS and copy it to a server on premise. I've setup the vsts agent and it can copy files just fine by using the "Windows Machine File Copy", but my problem is the agent downloads my whole team project starting from the root.

In Artifacts when I choose Link an artifact source and under type choose Team Foundation Version Control, under Source (repository) I can only choose my team project $/myTeamProject in the dropdown list. I'm not able to provide a path in VSTS like $/myTeamProjet/Main/subfolder.

Is this the wrong approach? I basically want to copy some files from a subfolder in my team project in VSTS to a on premise machine, without downloading everything from the whole root folder ($/myTeamProject). It takes forever when I trigger a Release with a singe task that copies files. How can the agent map only a specific folder and not the whole root folder?

答:
In release definition, you can’t specify part of files to download from the artifacts (and the artifact source link is for you to choose artifact from which build definition).

But you can specify the files you want to copy by Windows Machine File Copy task. For the source option in Windows Machine File Copy you can specify the subfolder you want to copy, such as $(System.DefaultWorkingDirectory)/BuildDefinition/drop/Main/subfolder.


问:
Java Regex Email replacing all Whitespaces and "[at]" sign
I have a method that  uses regular expression to validate an Email adress.

```<code>public String searchFormail(String searchWord) {

    Pattern pattern = Pattern
            .compile("([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})");
    Pattern pattern2 = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+  \\(at\\)([\\w\\-]+\\.)+[A-Za-z]{2,4})");

    Matcher matchs = pattern.matcher(searchWord);
    Matcher matchs2 = pattern2.matcher(searchWord);

    if (matchs.find() || matchs2.find()) {
        return searchWord.substring(matchs.start(), matchs.end());

    }

    return null;
}
</code>```

First Question: If searchFormail gets this string as input "support@ google.com" , notice the whitespace after @. How can I replace this whitespace so that the string input becomes "support@google.com". I tried //s  inside of regex, but that justs ignores whitespaces. So, that does not help.

Second Question: My second pattern, which validates mails with "google[at]support.com" does not work. How can improve this regex in order to get emails like "google[at]support.com" so that it becomes "google@support.com", like transforming "[at]" to @.

Thank you in advance.

答:
First Question: Actually a mail address never allows whitespaces, so I would simply remove all whitespaces by something like

searchWord = searchWord.replaceAll("\\s+","")

Second Question: Your pattern2 includes whitespaces ([\\w\\-]([\\.\\w])+[\\w]+_HERE_ARE_WHITESPACES_\\(at\\)([\\w\\-]+\\.)+[A-Za-z]{2,4}).
Thus it does not find a mail address.

Furthermore your pattern looks for a email format like "google(at)support.com" rather then "google[at]support.com".

To replace the "(at)" with an actual "@" you adapt your pattern2 and use the replaceFirst method.
This is the full code that works for me. I hope it helps.

```<code>public static String searchFormail(String searchWord) {

    searchWord = searchWord.replaceAll("\\s+","");

    Pattern pattern = Pattern
            .compile("([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})");
    Pattern pattern2 = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+)(\\(at\\))(([\\w\\-]+\\.)+[A-Za-z]{2,4})");

    Matcher matchs = pattern.matcher(searchWord);
    Matcher matchs2 = pattern2.matcher(searchWord);

    if(matchs.find()){
        return searchWord.substring(matchs.start(), matchs.end());
    }
    else if(matchs2.find()){
        return matchs2.replaceFirst("$1@$4");
    }

    return null;
}
</code>```

Body:
I have a method that  uses regular expression to validate an Email adress.

public String searchFormail(String searchWord) {

    Pattern pattern = Pattern
            .compile("([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})");
    Pattern pattern2 = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+  \\(at\\)([\\w\\-]+\\.)+[A-Za-z]{2,4})");

    Matcher matchs = pattern.matcher(searchWord);
    Matcher matchs2 = pattern2.matcher(searchWord);

    if (matchs.find() || matchs2.find()) {
        return searchWord.substring(matchs.start(), matchs.end());

    }

    return null;
}

First Question: If searchFormail gets this string as input "support@ google.com" , notice the whitespace after @. How can I replace this whitespace so that the string input becomes "support@google.com". I tried //s  inside of regex, but that justs ignores whitespaces. So, that does not help.

Second Question: My second pattern, which validates mails with "google[at]support.com" does not work. How can improve this regex in order to get emails like "google[at]support.com" so that it becomes "google@support.com", like transforming "[at]" to @.

Thank you in advance.

Body:
First Question: Actually a mail address never allows whitespaces, so I would simply remove all whitespaces by something like

searchWord = searchWord.replaceAll("\\s+","")

Second Question: Your pattern2 includes whitespaces ([\\w\\-]([\\.\\w])+[\\w]+_HERE_ARE_WHITESPACES_\\(at\\)([\\w\\-]+\\.)+[A-Za-z]{2,4}).
Thus it does not find a mail address.

Furthermore your pattern looks for a email format like "google(at)support.com" rather then "google[at]support.com".

To replace the "(at)" with an actual "@" you adapt your pattern2 and use the replaceFirst method.
This is the full code that works for me. I hope it helps.

public static String searchFormail(String searchWord) {

    searchWord = searchWord.replaceAll("\\s+","");

    Pattern pattern = Pattern
            .compile("([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})");
    Pattern pattern2 = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+)(\\(at\\))(([\\w\\-]+\\.)+[A-Za-z]{2,4})");

    Matcher matchs = pattern.matcher(searchWord);
    Matcher matchs2 = pattern2.matcher(searchWord);

    if(matchs.find()){
        return searchWord.substring(matchs.start(), matchs.end());
    }
    else if(matchs2.find()){
        return matchs2.replaceFirst("$1@$4");
    }

    return null;
}


问:
git push: permission denied (public key)
I'm trying to push a file to a git repo of a friend but errors on public key.

```<code>git push origin testbranch
Permission denied (publickey).
fatal: Could not read from remote repository.
</code>```

Where and how do we define public / private keys?

git remote -v returns:

```<code>origin  git@github.com:Sesamzaad/NET.git (fetch)
origin  git@github.com:Sesamzaad/NET.git (push)
</code>```

Any help is appreciated.

答:
This worked for me.

first of all, remove current remote :

```<code>git remote rm origin
</code>```

second, add remote through HTTPS but git@xxx :

```<code>git remote add origin https://github.com/Sesamzaad/NET.git
</code>```

then push has worked for me :

```<code>git push origin master
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to push a file to a git repo of a friend but errors on public key.

git push origin testbranch
Permission denied (publickey).
fatal: Could not read from remote repository.

Where and how do we define public / private keys?

git remote -v returns:

origin  git@github.com:Sesamzaad/NET.git (fetch)
origin  git@github.com:Sesamzaad/NET.git (push)

Any help is appreciated.

Body:
This worked for me.

first of all, remove current remote :

git remote rm origin

second, add remote through HTTPS but git@xxx :

git remote add origin https://github.com/Sesamzaad/NET.git

then push has worked for me :

git push origin master


问:
Calling function in a mxml component from a main flex application
In my main application I have a viewstack with 3 child views. In the viewstack change handler, I programmatically change the selectedchild property.

I understand that the initialize method for the view is not called every time I change the selectedChild Property. So I tried to invoke the init method programmatically too..

view1.mxml

```<code>    <fx:Script>
    <![CDATA[
    public function init():void{
     //something
    }
    ]]>
    </fx:Script>
</code>```

main.mxml

```<code>viewStack.selectedChild = viewStack.getChildByName("viewname") as NavigatorContent;
var v1:view1 = new view1();
v1.init();
</code>```

But I get a null pointer error. Am I missing anything?
Any help would be appreciated. I am a beginner here.

答:
I used

```<code>FlexGlobals.topLevelApplication.[viewId].init();
</code>```

And it works!!

Body:
In my main application I have a viewstack with 3 child views. In the viewstack change handler, I programmatically change the selectedchild property.

I understand that the initialize method for the view is not called every time I change the selectedChild Property. So I tried to invoke the init method programmatically too..

view1.mxml

    <fx:Script>
    <![CDATA[
    public function init():void{
     //something
    }
    ]]>
    </fx:Script>

main.mxml

viewStack.selectedChild = viewStack.getChildByName("viewname") as NavigatorContent;
var v1:view1 = new view1();
v1.init();

But I get a null pointer error. Am I missing anything?
Any help would be appreciated. I am a beginner here.

Body:
I used

FlexGlobals.topLevelApplication.[viewId].init();

And it works!!


问:
how to get number of days between two java.sql.timestamp field in scala
I am having two fields of java.sql.timestamp type in my dataframe and I want to find number of days between these two column

Below is the format of my data : *2016-12-23 23:56:02.0 (yyyy-MM-dd HH:mm:ss.S)

I had tried lots of method but did not find any solution. So can any one help here.

答:
org.apache.spark.sql.functions is a treasure trove. For example, there is the datediff method that does exactly what you want: here is the ScalaDoc.

An example:

```<code>val spark: SparkSession = ??? // your spark session
val sc: SparkContext = ??? // your spark context

import spark.implicits._ // to better work with spark sql

import java.sql.Timestamp

final case class Data(id: Int, from: Timestamp, to: Timestamp)

val ds =
  spark.createDataset(sc.parallelize(Seq(
    Data(1, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-11 00:00:00")),
    Data(2, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-21 00:00:00")),
    Data(3, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-23 00:00:00")),
    Data(4, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-07 00:00:00"))
  )))

import org.apache.spark.sql.functions._

ds.select($"id", datediff($"from", $"to")).show()
</code>```

By running this snippet you would end up with the following output:

```<code>+---+------------------+
| id|datediff(from, to)|
+---+------------------+
|  1|               -10|
|  2|               -20|
|  3|               -22|
|  4|                -6|
+---+------------------+
</code>```

Body:
org.apache.spark.sql.functions is a treasure trove. For example, there is the datediff method that does exactly what you want: here is the ScalaDoc.

An example:

val spark: SparkSession = ??? // your spark session
val sc: SparkContext = ??? // your spark context

import spark.implicits._ // to better work with spark sql

import java.sql.Timestamp

final case class Data(id: Int, from: Timestamp, to: Timestamp)

val ds =
  spark.createDataset(sc.parallelize(Seq(
    Data(1, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-11 00:00:00")),
    Data(2, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-21 00:00:00")),
    Data(3, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-23 00:00:00")),
    Data(4, Timestamp.valueOf("2017-01-01 00:00:00"), Timestamp.valueOf("2017-01-07 00:00:00"))
  )))

import org.apache.spark.sql.functions._

ds.select($"id", datediff($"from", $"to")).show()

By running this snippet you would end up with the following output:

+---+------------------+
| id|datediff(from, to)|
+---+------------------+
|  1|               -10|
|  2|               -20|
|  3|               -22|
|  4|                -6|
+---+------------------+


答:
you need to define jsonBiz before using it.

```<code>var jsonBiz = "";

jsonBiz = jsonBiz + JSON.stringify(json);
</code>```

please try this.

Title: Javascript JSON.Stringify() what is undefined

Body:
you need to define jsonBiz before using it.

var jsonBiz = "";

jsonBiz = jsonBiz + JSON.stringify(json);

please try this.


问:
Throw exception from within a future
I need to throw an exception in my program, but the exception happens within a future, so it is thrown in a different thread. How to make this example work?

```<code>object TestFutures extends App {

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map {
    seq => seq.map {  i =>
        println("i="+i)
        if (i == 1)
              throw new Exception("This is an exception")

    }
  }

  Thread.sleep(5000)
}
</code>```

This is the program output, but I need it to throw the exception:

```<code>i=0
i=1
</code>```

答:
Result is still a Future

```<code> val stillFutures: Seq[Future[Unit]] = fx.map {
    seq => seq.map {  i =>
      println("i="+i)
      if (i == 1)
        throw new Exception("This is an exception")

    }
  }
</code>```

You can check each future on Success/Failure

```<code>stillFutures.foreach{
_.onComplete{
  case Success(_) => // do nothing
  case Failure(ex) => throw ex
}}
</code>```

Title: Throw exception from within a future

Body:
I need to throw an exception in my program, but the exception happens within a future, so it is thrown in a different thread. How to make this example work?

object TestFutures extends App {

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map {
    seq => seq.map {  i =>
        println("i="+i)
        if (i == 1)
              throw new Exception("This is an exception")

    }
  }

  Thread.sleep(5000)
}

This is the program output, but I need it to throw the exception:

i=0
i=1

Body:
Result is still a Future

 val stillFutures: Seq[Future[Unit]] = fx.map {
    seq => seq.map {  i =>
      println("i="+i)
      if (i == 1)
        throw new Exception("This is an exception")

    }
  }

You can check each future on Success/Failure

stillFutures.foreach{
_.onComplete{
  case Success(_) => // do nothing
  case Failure(ex) => throw ex
}}


问:
link individual user's profile to user in comment section - Django
I need to link respective user's profile to the comments. Currently all my links are taking me to the logged in user's profile itself.

My user model @ user_profile/models.py:

```<code>class MyUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    .......
    .......

    objects = manager.CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.email)
</code>```

My profile model:

```<code>class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                related_name="profile",
                                on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True, default='')
    .....
    .....

    objects = manager.CustomProfileManager()

    def get_absolute_url(self):
        return reverse("user_profile:commenters_profile")

    @property
    def get_profile(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type
</code>```

Comments/models.py:

```<code>class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comment_by', default=1)
    ....
</code>```

View:

```<code>@login_required
def commenters_profile(request):
    instance = get_object_or_404(Profile)

    context = {
        "title": instance.title,
        "instance": instance.get_profile(),
        }
    return render(request, "profile.html", context)
</code>```

user_profile/urls.py:

```<code>urlpatterns = [
    url(r'^$', myProfile, name='myProfile'),
    url(r'^$', commenters_profile, name='commenters_profile'),
]
</code>```

template:

```<code><p><a href="{{ comment.user.profile.get_absolute_url }}"> {{ comment.user.get_full_name }}</a></p>
</code>```

Please help.

Update:

Traceback (most recent call last):

```<code>File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/surajit/website/PubNet/user_profile/views.py", line 173, in commenters_profile
    "instance": instance.get_profile(),
TypeError: 'ContentType' object is not callable
</code>```

profile.html:

```<code><div class="col-sm-8 col-md-3">
            <img src="{{ user.profile.photo.url }}", width="220", alt="", class="img-rounded img-responsive" />
            <br/><p> <i class="glyphicon glyphicon-envelope"></i> {{ user.email }}
                <br /> <i class="glyphicon glyphicon-gift"></i> {{ user.date_of_birth }}</p>
        </div>
        <div class="col-sm-4 col-md-6">
            <blockquote>
                <p><h2>{{ user.first_name }} {{ user.last_name }}</h2></p>
                <small><cite title="Source Title">Some Text Here <i class="glyphicon glyphicon-map-marker"></i></cite></small>
            </blockquote>
            <br/><p> {{ user.profile.bio }}</p>
        </div>
</code>```

Screenshot of Comments Section:

答:
Because myProfile and commenters_profile have same regular expressions, you never reach commenters_profile, all request will be send to myProfile. Change commenters_profile url:

```<code>url(r'^(?P<pk>\d+)/$', commenters_profile, name='commenters_profile'),
</code>```

fix get_absolute_url method:

```<code>def get_absolute_url(self):
    return reverse("user_profile:commenters_profile", kwargs={'pk': self.pk})
</code>```

and view:

```<code>@login_required
def commenters_profile(request, pk):
    instance = get_object_or_404(Profile, pk=pk)

    context = {
        "title": instance.title,
        "instance": instance.get_profile(),
        }
    return render(request, "profile.html", context)
</code>```

Body:
I need to link respective user's profile to the comments. Currently all my links are taking me to the logged in user's profile itself.

My user model @ user_profile/models.py:

class MyUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    .......
    .......

    objects = manager.CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.email)

My profile model:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                related_name="profile",
                                on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True, default='')
    .....
    .....

    objects = manager.CustomProfileManager()

    def get_absolute_url(self):
        return reverse("user_profile:commenters_profile")

    @property
    def get_profile(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type

Comments/models.py:

class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comment_by', default=1)
    ....

View:

@login_required
def commenters_profile(request):
    instance = get_object_or_404(Profile)

    context = {
        "title": instance.title,
        "instance": instance.get_profile(),
        }
    return render(request, "profile.html", context)

user_profile/urls.py:

urlpatterns = [
    url(r'^$', myProfile, name='myProfile'),
    url(r'^$', commenters_profile, name='commenters_profile'),
]

template:

 {{ comment.user.get_full_name }}

Please help.

Update:

Traceback (most recent call last):

File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/surajit/website/PubNet/user_profile/views.py", line 173, in commenters_profile
    "instance": instance.get_profile(),
TypeError: 'ContentType' object is not callable

profile.html:

  {{ user.email }}

  {{ user.date_of_birth }}

{{ user.first_name }} {{ user.last_name }}

                Some Text Here

 {{ user.profile.bio }}

Screenshot of Comments Section:

Body:
Because myProfile and commenters_profile have same regular expressions, you never reach commenters_profile, all request will be send to myProfile. Change commenters_profile url:

url(r'^(?P<pk>\d+)/$', commenters_profile, name='commenters_profile'),

fix get_absolute_url method:

def get_absolute_url(self):
    return reverse("user_profile:commenters_profile", kwargs={'pk': self.pk})

and view:

@login_required
def commenters_profile(request, pk):
    instance = get_object_or_404(Profile, pk=pk)

    context = {
        "title": instance.title,
        "instance": instance.get_profile(),
        }
    return render(request, "profile.html", context)


问:
Is there a way to make vscode line number field smaller width?
The vertical column that contains the code line number is VSC is too wide. Is there a way to narrow it down?

答:
You can't change the size of this column.

Actually there are three columns:

left of the linenumber is the column called glyphMargin, the place to set debugging breakpoints (red dot). (When you edit settings, the column displays a pen when you point on the line as seen in the screenshots below)

the line number itself

right of it you can fold/unfold your code.

If all three are active, it looks like this (settings) or a like above (code)

To save space you can

switch off the display of line numbers:

```<code>"editor.lineNumbers": "off"
</code>```

switch off the code folding feature:

```<code>"editor.folding": false
</code>```

if you don't use the debugger, disable the glyphMargin:

```<code>"editor.glyphMargin": false
</code>```

This is probably not what you want, but if you don't use code folding or the debugger or don't need linenumbers, you can at least save a little bit of space.
To change these settings press ctrl, or click on the menu file/preferences/settings.

Body:
You can't change the size of this column.

Actually there are three columns:

left of the linenumber is the column called glyphMargin, the place to set debugging breakpoints (red dot). (When you edit settings, the column displays a pen when you point on the line as seen in the screenshots below)

the line number itself

right of it you can fold/unfold your code.

If all three are active, it looks like this (settings) or a like above (code)

To save space you can

switch off the display of line numbers:

"editor.lineNumbers": "off"

switch off the code folding feature:

"editor.folding": false

if you don't use the debugger, disable the glyphMargin:

"editor.glyphMargin": false

This is probably not what you want, but if you don't use code folding or the debugger or don't need linenumbers, you can at least save a little bit of space.
To change these settings press ctrl, or click on the menu file/preferences/settings.


问:
SQL - how to get all rows in parent based on number of children of that parent?
I have 2 tables:

parent table: id, name

child table: id, name, id_parent

Now, I want to list rows in parent table have the number rows of children is 3.

答:
Can be done in several ways. Easiest is perhaps a correlated sub-query in the WHERE clause to count the number of children:

```<code>select *
from parents p
where (select count(*) from children c
       where c.id_parent = p.id) = 3
</code>```

Or a GROUP BY, with HAVING:

```<code>select p.*
from parents p
join children c
     on c.id_parent = p.id
group by p.id
having count(*) = 3
</code>```

Body:
Can be done in several ways. Easiest is perhaps a correlated sub-query in the WHERE clause to count the number of children:

select *
from parents p
where (select count(*) from children c
       where c.id_parent = p.id) = 3

Or a GROUP BY, with HAVING:

select p.*
from parents p
join children c
     on c.id_parent = p.id
group by p.id
having count(*) = 3


问:
jquery slow when using children() with rows
Recently I asked a question on SO regarding changing row background color on click and hover using jquery.  Below is the link to it, and I implemented the solution marked as answer. The problem is when I am having lot of rows, the hover as well as click takes a lot of time. I am using IE8 with latest version of jquery. Below is the link to question

jquery row hover and click events

Here is the code I implemented:

http://jsfiddle.net/EPUrh/

if you hover and click, its working and its fast for less rows, but if there are lot of rows/columns, it gets really slow and sometimes throws an error if I want to stop the script. When I compare the same in Firefox, it very fast. I have problem with this only in IE8. Can any one suggest a workaround for this?

答:
In the click handler, add a class to the
 that was clicked so when it comes time to remove the class on its .children(), you can target that specific row.

```<code>  $(".simplehighlight").click(function() {
        $(this).addClass('wasClicked').children().addClass('clicked');

           // Get the sibling <tr> with the class "wasClicked"
           //   and remove that class, and the "clicked" class from  its children
        $(this).siblings('.wasClicked').removeClass('wasClicked')
                                       .children().removeClass('clicked');
  });
</code>```

Body:
In the click handler, add a class to the <tr> that was clicked so when it comes time to remove the class on its .children(), you can target that specific row.

  $(".simplehighlight").click(function() {
        $(this).addClass('wasClicked').children().addClass('clicked');

           // Get the sibling <tr> with the class "wasClicked"
           //   and remove that class, and the "clicked" class from  its children
        $(this).siblings('.wasClicked').removeClass('wasClicked')
                                       .children().removeClass('clicked');
  });


问:
python using pip package different than default one
I would like to install a version of a python package that is newer than the one in the system.

The instructions describe how to do it with pip:

https://github.com/ewels/MultiQC

By running this command:

```<code>pip install git+https://github.com/ewels/MultiQC.git
</code>```

Adding the --user flag does an installation, but when I try to see which is the default binary, it points to the older one which is available system-wide:

```<code>which multiqc
</code>```

How do I call the one I just installed with pip install --user URL?

答:
For any googlers - the trick is to get your own version of MultiQC to take preference over the system-wide version. The easiest way to do this is by prepending your personal installation directory to your PATH. So, taking the directory in the answer by @719016, you would add the following line to your ~/.bashrc file:

```<code>export PATH="$HOME/.local/bin/:$PATH"
</code>```

Apologies for the very late response. I'm the author of MultiQC and just found this post ;)

Body:
I would like to install a version of a python package that is newer than the one in the system.

The instructions describe how to do it with pip:

https://github.com/ewels/MultiQC

By running this command:

pip install git+https://github.com/ewels/MultiQC.git

Adding the --user flag does an installation, but when I try to see which is the default binary, it points to the older one which is available system-wide:

which multiqc

How do I call the one I just installed with pip install --user URL?

Body:
For any googlers - the trick is to get your own version of MultiQC to take preference over the system-wide version. The easiest way to do this is by prepending your personal installation directory to your PATH. So, taking the directory in the answer by @719016, you would add the following line to your ~/.bashrc file:

export PATH="$HOME/.local/bin/:$PATH"

Apologies for the very late response. I'm the author of MultiQC and just found this post ;)


答: Because you declared jsonProp but didn't define it: var jsonProp;. When you don't set a value to a variable, it will be undefined.

Body:
I am using JSON.Stringify() in my javascript...

var jsonProp;
var json = { };
json.prop= { };
json.prop.Brand = $('.Brand' + val).val();
json.prop.Name = $('.Name' + val).val();
json.prop.Desc = $('.Desc' + val).val();
json.prop.Address = $('.Address' + val).val();
json.prop.Phone = $('.Phone' + val).val();
json.prop.Tag = $('.Tag' + val).val();
json.prop.City = $('.City' + val).val();
json.prop.Status = $('.Status' + val).val();
jsonProp = jsonProp + JSON.stringify(json);

and the result is :

"undefined{"prop":{"Brand":"","Name":"apotik AA","Desc":"","Address":"Address","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}
{"prop":{"Brand":"","Name":"apotik AAaaaa. Bina Farma","Desc":"","Address":"Jl. RA. Kartini, Margahayu-Bekasi Tim., Kota Bks, Jawa Barat 17113","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}"

why is "undefined" there? how can I set it? all I want to have is a JSONArray like this :

Prop{{"Brand":"value","Name":"value"},{"Brand":"value","Name":"value"}}

Please help


问:
How can a BASH script automatically elevate to root on a remote server, without using sudoers nopasswd option?
o's!

Maybe you can help me with this. I can't find an answer to my specific questions, because there is an obvious solution which I'm not allowed to use. But first things first, the context:

In my company, which is a service provider, we administrate a bunch of
  Linux servers.  Some of my colleagues has for a long time been running
  a BASH script from a source server, that then performs some tasks over
  SSH on a number of remote Linux servers. The tasks it performs has to
  be executed as root, so what the script does is it authorizes the
  source server as root on the remote Linux servers via SSH  (the remote
  servers has the source servers public SSH key). Then what happened is
  a new security policy was enforced and now root login over SSH is
  denied. So the mentioned method no longer works.

The solution I keep finding, which we are by policy not allowed to do, is to create an entry in the sudoers file allowing sudo to root without password for the specific user.
This is the terms and they have to obey that. The only procedure that is allowed is to log on to the target server with your personal user, and then sudo su - to root WITH password.
Cocky as I apparently was, I said, "It should be possible to have the script do that automatically", and the management was like "Cool, you do it then!" and now I'm here at Stack Overflow,
because I know this is where bright minds are.

So this is exactly what I want to do with a BASH script, and I do not know if it's possible or how it's done, I really hope you can help me out:

Imagine Bob, he's logged into the source server, and he wants to
  execute the script against a target server. Knowing that root over SSH
  doesn't work, the authorization part of the script has been upgraded.
  When Bob runs the script, it prompts him for his password. The
  password is then stored in a variable (encrypted would be amazing) and
  the script then logs on the target server as his user (which is
  allowed)  and then automatically elevates him to root on the target
  server using the password he entered on the source server. Now the
  script is root and it runs its tasks as usual.

Can it be done with BASH? and how?

UPDATE:

The Script:

```<code>    ## define code to be run on the remote system
remote_script='sudo -S hostname'

## local system

# on the local machine: prompt the user for the password
read -r -p "Enter password for $host: " password

# ...and write the password, followed by a NUL delimiter, to stdin of ssh
ssh -t 10.0.1.40 "$remote_script" < <(printf '%s\0' "$password")
</code>```

The error:

```<code>    [worker@source ~]$ sh elevate.sh
Enter password for : abc123
elevate.sh: line 10: syntax error near unexpected token `<'
elevate.sh: line 10: `ssh -t 10.0.1.40 "$remote_script" < <(printf '%s\0' "$password")'
</code>```

答: Just make a daemon or cron script running as root, that in turn will check for any new scripts in specified secure location (ie. DB that it only has READ access to), and if they exist, it will download and execute them.</p>

Body:
o's!

Maybe you can help me with this. I can't find an answer to my specific questions, because there is an obvious solution which I'm not allowed to use. But first things first, the context:

In my company, which is a service provider, we administrate a bunch of
  Linux servers.  Some of my colleagues has for a long time been running
  a BASH script from a source server, that then performs some tasks over
  SSH on a number of remote Linux servers. The tasks it performs has to
  be executed as root, so what the script does is it authorizes the
  source server as root on the remote Linux servers via SSH  (the remote
  servers has the source servers public SSH key). Then what happened is
  a new security policy was enforced and now root login over SSH is
  denied. So the mentioned method no longer works.

The solution I keep finding, which we are by policy not allowed to do, is to create an entry in the sudoers file allowing sudo to root without password for the specific user.
This is the terms and they have to obey that. The only procedure that is allowed is to log on to the target server with your personal user, and then sudo su - to root WITH password.
Cocky as I apparently was, I said, "It should be possible to have the script do that automatically", and the management was like "Cool, you do it then!" and now I'm here at Stack Overflow,
because I know this is where bright minds are.

So this is exactly what I want to do with a BASH script, and I do not know if it's possible or how it's done, I really hope you can help me out:

Imagine Bob, he's logged into the source server, and he wants to
  execute the script against a target server. Knowing that root over SSH
  doesn't work, the authorization part of the script has been upgraded.
  When Bob runs the script, it prompts him for his password. The
  password is then stored in a variable (encrypted would be amazing) and
  the script then logs on the target server as his user (which is
  allowed)  and then automatically elevates him to root on the target
  server using the password he entered on the source server. Now the
  script is root and it runs its tasks as usual.

Can it be done with BASH? and how?

UPDATE:

The Script:

    ## define code to be run on the remote system
remote_script='sudo -S hostname'

## local system

# on the local machine: prompt the user for the password
read -r -p "Enter password for $host: " password

# ...and write the password, followed by a NUL delimiter, to stdin of ssh
ssh -t 10.0.1.40 "$remote_script" < <(printf '%s\0' "$password")

The error:

    [worker@source ~]$ sh elevate.sh
Enter password for : abc123
elevate.sh: line 10: syntax error near unexpected token `<'
elevate.sh: line 10: `ssh -t 10.0.1.40 "$remote_script" < <(printf '%s\0' "$password")'


问:
Detect clicks inside a Div but outside of a particular child Div in VueJS
I have a page in which I have MCQ Options which looks like this:

This is the HTML Code for the options parts till now:

```<code><div v-for="(option, index) in optionsForFrontend">
            <div class="option">
                <div class="radio-check-item">
                    <input type="radio"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Single'">
                    <input type="checkbox"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Multiple'">
                </div>
                <div class="divider">

                </div>
                <div class="content-item">
                    <vue-markdown :source="option.option"></vue-markdown>
                </div>
            </div>
        </div>
</code>```

I want to select the options by clicking on the option content. So I put a :click="functionToSelectOption" on the outer div ("option") containing checkbox and option content.

The problem is when I select the checkbox, it gets selected and the function "functionToSelectOption" gets called as well since the checkbox is inside the "option" div.

I want to be able to detect a click inside the "option" div but outside radio/checkbox div so I can call the function to toggle the option.

I mostly found similar questions under jquery tags and nothing with VueJS.

答:
I would avoid event.stopPropagation(). All kinds of things might be listening higher up in the tree. For instance, you might want an onclick on the window to close a modal dialog if the user clicks outside the dialog. The much less radical way to do this is to look at event.target. This jsfiddle tests (event.target == event.currentTarget) so it only reacts to clicks on the parent div.

Markup

```<code><div id="ctr">
  <div v-for="(option,index) in options"
    style="margin:10px;padding:10px;border:solid;border-radius:4px"
    @click="parent"
  >
    <input type="checkbox" :name="'invidiousChoice' + index" @click='child'> {{option.label}}
  </div>
</div>
</code>```

JS

```<code>var vm = new Vue({
  el:"#ctr",
  data : {
  options:[{label:'terrible option'},{label:'disastorous option'}]
  },
  methods: {
    parent: function(event) {
      if(event.target == event.currentTarget)
        alert( 'parent clicked');
    }
  }
})
</code>```

Body:
I have a page in which I have MCQ Options which looks like this:

This is the HTML Code for the options parts till now:

                    <input type="radio"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Single'">
                    <input type="checkbox"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Multiple'">

                    <vue-markdown :source="option.option"></vue-markdown>

I want to select the options by clicking on the option content. So I put a :click="functionToSelectOption" on the outer div ("option") containing checkbox and option content.

The problem is when I select the checkbox, it gets selected and the function "functionToSelectOption" gets called as well since the checkbox is inside the "option" div.

I want to be able to detect a click inside the "option" div but outside radio/checkbox div so I can call the function to toggle the option.

I mostly found similar questions under jquery tags and nothing with VueJS.

Body:
I would avoid event.stopPropagation(). All kinds of things might be listening higher up in the tree. For instance, you might want an onclick on the window to close a modal dialog if the user clicks outside the dialog. The much less radical way to do this is to look at event.target. This jsfiddle tests (event.target == event.currentTarget) so it only reacts to clicks on the parent div.

Markup

<div id="ctr">
  <div v-for="(option,index) in options"
    style="margin:10px;padding:10px;border:solid;border-radius:4px"
    @click="parent"
  >
    <input type="checkbox" :name="'invidiousChoice' + index" @click='child'> {{option.label}}
  </div>
</div>

JS

var vm = new Vue({
  el:"#ctr",
  data : {
  options:[{label:'terrible option'},{label:'disastorous option'}]
  },
  methods: {
    parent: function(event) {
      if(event.target == event.currentTarget)
        alert( 'parent clicked');
    }
  }
})


问:
Proportional layout for iPhones (from 5 to 6 Plus) with Size Classes
I have passed through a number of tutorials about Size Classes but still I cannot figure out one thing.

iPhone 5, iPhone 6 and iPhone 6 Plus have absolutely the same screen aspect ratios, so I want them to use the same content layout. By saying the same I mean proportional to width and height of the screen.

But! I cannot find a way to make it proportional for all iPhones!

There are just a few constraints that truly support proportions: "Aspect Ratio", "Same Width" + "Multiplier", "Same Height" + "Multiplier"

Constrains, such as Leading Edges, Horizontal Center In Container, all Pin constraints operate with absolute values in logical points, and all iPhones' screens have different sizes in logical points; thereby I cannot achieve the same picture on all iPhones.

Update

I'm adding an image to explain what I want to achieve:

答:
Check this Sample Project i have made for you.

Suppose you have a button, then follow the steps i have mentioned below to make proportional height, width and position of the Button to the parent View.

Give your Button Aspect ratio.

Give width equal to the parent View's width.

Add Constraint Center Horizontally in container and Center
Vertically in container.

Select Your Button and then go to size inspector and set the
multiplier for the width (like 0.3 or 0.4 etc).

Then set the multiplier for "align center X to.." (if you want your
button to be left of center then set multiplier below 1 like 0.8,
0.7,0.5 etc And if you want your button to be in the right of the center then set the multiplier value bigger than 1 like 1.2 etc).

Set the multiplier value for "Align center y to.." as like in Step

Its all done.. Just run and check.

Hope this will help you.