问:
Python 3.6 TypeError: string indices must be integers when trying to send office 365 email
Trying to automate some emails I send out every morning. Having some issues when including multiple attachments and can't seem to figure out where I'm going wrong.

```<code>from O365 import Message, Attachment
import getpass

email_list = {
    'email1': {
        'recipients': 'adiosz@outlook.com',
        'subject': 'test subject',
        'body': 'test body',
        'files': ["file1.xlsx", "file2.xlsx"]
    }
    'email2': {
        'recipients': 'adiosz@outlook.com',
        'subject': 'test subject',
        'body': 'test body',
        'files': ["file3.xlsx", "file4.xlsx"]
    }
}

username = input('Enter your email: ')
password = getpass.getpass('Enter your password: ')
o365_auth = (username, password)

def daily_email(recipients, subject, body, files):
    m = Message(auth=o365_auth)
    m.setRecipients(recipients)
    m.setSubject(subject)
    m.setBody(body)
    for file in files:
        att = Attachment(file)
        m.attachments.append(att)
    m.sendMessage()

for email, email_contents in email_list.items():
    daily_email(email_contents['recipients'], email_contents['subject'], email_contents['body'], email_contents['files'])
</code>```

Here is the error I receive:

```<code>Traceback (most recent call last):
  File ".\emails2.py", line 46, in <module>
    email_contents['files'])
  File ".\emails2.py", line 34, in daily_emails
    att = Attachment(file)
  File "C:\Users\adiosz\AppData\Local\Programs\Python\Python36-32\lib\site-packages\O365\attachment.py", line 50,
 in __init__
    self.isPDF = '.pdf' in self.json['Name']
TypeError: string indices must be integers
</code>```

Thank you!

答:
The path to the filename to add as attachment is supposed to be in the second parameter. See :

https://github.com/Narcolapser/python-o365/blob/master/O365/attachment.py#L35

So change the line att = Attachment(file) with att = Attachment(path=file) and it should work.

BTW, do not use the file variable name, you are overriding a builtin type.

Body:
Trying to automate some emails I send out every morning. Having some issues when including multiple attachments and can't seem to figure out where I'm going wrong.

from O365 import Message, Attachment
import getpass

email_list = {
    'email1': {
        'recipients': 'adiosz@outlook.com',
        'subject': 'test subject',
        'body': 'test body',
        'files': ["file1.xlsx", "file2.xlsx"]
    }
    'email2': {
        'recipients': 'adiosz@outlook.com',
        'subject': 'test subject',
        'body': 'test body',
        'files': ["file3.xlsx", "file4.xlsx"]
    }
}

username = input('Enter your email: ')
password = getpass.getpass('Enter your password: ')
o365_auth = (username, password)

def daily_email(recipients, subject, body, files):
    m = Message(auth=o365_auth)
    m.setRecipients(recipients)
    m.setSubject(subject)
    m.setBody(body)
    for file in files:
        att = Attachment(file)
        m.attachments.append(att)
    m.sendMessage()

for email, email_contents in email_list.items():
    daily_email(email_contents['recipients'], email_contents['subject'], email_contents['body'], email_contents['files'])

Here is the error I receive:

Traceback (most recent call last):
  File ".\emails2.py", line 46, in <module>
    email_contents['files'])
  File ".\emails2.py", line 34, in daily_emails
    att = Attachment(file)
  File "C:\Users\adiosz\AppData\Local\Programs\Python\Python36-32\lib\site-packages\O365\attachment.py", line 50,
 in __init__
    self.isPDF = '.pdf' in self.json['Name']
TypeError: string indices must be integers

Thank you!


来源: stackexchange

问:
How to make a custom hoverinfo lables for Plotly boxplot?
Basically I have a problem with the current version of Plotly which doesn't display hoverinfo for box plot correctly. It omits labels (min, max, median etc.), so when I plot the following plot:

```<code>plot_ly(y = ~rnorm(50), type = "box")
</code>```

I don't have the necessary labels.

Is there a way for me to give custom hover labels so they go like this Max: 1.97, q3: 0.84, Median: 0.25 etc.?

My Plotly version is ‘4.7.1’

答:
Here is an example using ggplot2, that you can map through to plotly.

I hope it helps point you in the right direction. The latest version of plotly and ggplot2 do now display hover values. My approach has been to create text labels as this allows me to roll into a template function that I can use.

T.

Graphics Output (ggplot2)

Graphics Output (plotly)

Code Example

```<code>require(DAAG)
require(ggplot2)
require(plotly)
data("possum")

dset <- possum
here <- possum$sex == "f"
dname <- as.character(substitute(possum))
xnam <- as.character(substitute(x))
x <- dset[here, "totlngth"]

yLabel <- c("Total length (cm)")

## Pull in boxplot stats for use in mapping data later to boxplot
z <- boxplot.stats(x)
xlim <- range(c(z$stats, z$out))
xlim <- xlim + c(-0.025, 0.05) * diff(xlim)
ylim <- c(0.55, 1.5)

top <- 0.7
chh <- par()$cxy[2]
chw <- par()$cxy[1]

gp <- ggplot(data = possum, aes(y = totlngth, x = ""))
gp <- gp + stat_boxplot(geom = 'errorbar', width = .1)
gp <- gp + geom_boxplot(#width = .3,
                        outlier.color = "blue",
                        outlier.shape = 2)
gp <- gp + stat_summary(fun.y = mean,
                        geom = "point",
                        shape = 5,
                        size = 4)
gp <- gp + xlab(NULL)
gp <- gp + ylab(yLabel)
gp <- gp + theme(axis.ticks.x = element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 panel.background = element_blank())

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                            y = z$stats[5],
                                            label = "Largest value \n(there are no outliers)"
                                            ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[4],
                                              label = "upper quartile"
                                              ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[3],
                                              label = "median"
                                              ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[2],
                                              label = "lower quartile"
                                              ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[1],
                                              label = "Smallest value \n(outliers excepted)"
                                              ))
if (!is.null(z$out)) {
  gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$out[1],
                                              label = "Outlier \n"
                                              ))
  # Display outlier
  gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                                 y = z$out[1] + .5,
                                                 label = c(format(round(z$out[1], 2)))))

}

av <- mean(z$stats[c(2, 4)])
q1 <- z$stats[2]
q3 <- z$stats[4]
qtop <- q3 + 0.5 * chh

# Largest Value
gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                               y = z$stats[5],
                                               label = c(format(round(z$stats[5], 2)))))

# Upper Quartile
gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                               y = q1,
                                               label = c(format(round(q1, 2)))))

# Lower Quartile
gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                               y = q3,
                                               label = c(format(round(q3, 2)))))

gp

p <- ggplotly(gp)
p
</code>```

Note: The code above is an evolution from a base graphics package boxplot example in:

Data Analysis and Graphics Using R, Third Edition By: John Maindonald; W. John Braun

the book covers the base package in great detail, it was published in 2010, still a great source of insight.

ContentLicense: CC BY-SA 3.0

Body:
Basically I have a problem with the current version of Plotly which doesn't display hoverinfo for box plot correctly. It omits labels (min, max, median etc.), so when I plot the following plot:

plot_ly(y = ~rnorm(50), type = "box")

I don't have the necessary labels.

Is there a way for me to give custom hover labels so they go like this Max: 1.97, q3: 0.84, Median: 0.25 etc.?

My Plotly version is ‘4.7.1’

Body:
Here is an example using ggplot2, that you can map through to plotly.

I hope it helps point you in the right direction. The latest version of plotly and ggplot2 do now display hover values. My approach has been to create text labels as this allows me to roll into a template function that I can use.

T.

Graphics Output (ggplot2)

Graphics Output (plotly)

Code Example

require(DAAG)
require(ggplot2)
require(plotly)
data("possum")

dset <- possum
here <- possum$sex == "f"
dname <- as.character(substitute(possum))
xnam <- as.character(substitute(x))
x <- dset[here, "totlngth"]

yLabel <- c("Total length (cm)")

## Pull in boxplot stats for use in mapping data later to boxplot
z <- boxplot.stats(x)
xlim <- range(c(z$stats, z$out))
xlim <- xlim + c(-0.025, 0.05) * diff(xlim)
ylim <- c(0.55, 1.5)

top <- 0.7
chh <- par()$cxy[2]
chw <- par()$cxy[1]

gp <- ggplot(data = possum, aes(y = totlngth, x = ""))
gp <- gp + stat_boxplot(geom = 'errorbar', width = .1)
gp <- gp + geom_boxplot(#width = .3,
                        outlier.color = "blue",
                        outlier.shape = 2)
gp <- gp + stat_summary(fun.y = mean,
                        geom = "point",
                        shape = 5,
                        size = 4)
gp <- gp + xlab(NULL)
gp <- gp + ylab(yLabel)
gp <- gp + theme(axis.ticks.x = element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 panel.background = element_blank())

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                            y = z$stats[5],
                                            label = "Largest value \n(there are no outliers)"
                                            ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[4],
                                              label = "upper quartile"
                                              ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[3],
                                              label = "median"
                                              ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[2],
                                              label = "lower quartile"
                                              ))

gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$stats[1],
                                              label = "Smallest value \n(outliers excepted)"
                                              ))
if (!is.null(z$out)) {
  gp <- gp + geom_text(data = data.frame(), aes(x = top + 1.5 * chh,
                                              y = z$out[1],
                                              label = "Outlier \n"
                                              ))
  # Display outlier
  gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                                 y = z$out[1] + .5,
                                                 label = c(format(round(z$out[1], 2)))))

}

av <- mean(z$stats[c(2, 4)])
q1 <- z$stats[2]
q3 <- z$stats[4]
qtop <- q3 + 0.5 * chh

# Largest Value
gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                               y = z$stats[5],
                                               label = c(format(round(z$stats[5], 2)))))

# Upper Quartile
gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                               y = q1,
                                               label = c(format(round(q1, 2)))))

# Lower Quartile
gp <- gp + geom_text(data = data.frame(), aes( x = rep(top - chh, 2),
                                               y = q3,
                                               label = c(format(round(q3, 2)))))

gp

p <- ggplotly(gp)
p

Note: The code above is an evolution from a base graphics package boxplot example in:

Data Analysis and Graphics Using R, Third Edition By: John Maindonald; W. John Braun

the book covers the base package in great detail, it was published in 2010, still a great source of insight.


问:
Trying to use show/hide to slowly fade In/ fade Out a paragraph
I'm trying to make to show/hide a paragraph when buttons are pressed.
But also to look like slow movement up and down.

That's how the HTML look like for example :

```<code><button class="hideA">Hide</button>
<button class="showA">show</button>
<p id>Helloooooooooooooooooooooo.</p>
</code>```

And that's how the Jquery code looks like:

```<code>$(".hideA").click(function(){
    $(".hideA p").hide(function(){
    });
});
$(".showA").click(function(){
    $(".hideA p").show(function(){
    });
});
</code>```

But this code is not running for some reason. please let me know the reason if you can!

答:
First of all, you need to remove the $(".hideA p")  and use $("p") otherwise you are hiding the Button!

Also, you can specify the paragraph by adding an id to it:

```<code><p id="paragraph">Helloooooooooooooooooooooo.</p>
</code>```

Then Try the following code to run it:

```<code>$(document).ready(function(){
    $(".hideA").click(function(){
        $("#paragraph").hide("slow");
    });
    $(".showA").click(function(){
        $("#paragraph").show("slow");
    });
});
</code>```

Body:
I'm trying to make to show/hide a paragraph when buttons are pressed.
But also to look like slow movement up and down.

That's how the HTML look like for example :

<button class="hideA">Hide</button>
<button class="showA">show</button>

Helloooooooooooooooooooooo.

And that's how the Jquery code looks like:

$(".hideA").click(function(){
    $(".hideA p").hide(function(){
    });
});
$(".showA").click(function(){
    $(".hideA p").show(function(){
    });
});

But this code is not running for some reason. please let me know the reason if you can!

Body:
First of all, you need to remove the $(".hideA p")  and use $("p") otherwise you are hiding the Button!

Also, you can specify the paragraph by adding an id to it:

<p id="paragraph">Helloooooooooooooooooooooo.</p>

Then Try the following code to run it:

$(document).ready(function(){
    $(".hideA").click(function(){
        $("#paragraph").hide("slow");
    });
    $(".showA").click(function(){
        $("#paragraph").show("slow");
    });
});


问:
Is there any function to get an unlimited input string from standard input
The condition is:

I want to input a line from standard input, and I don't know the size of it, maybe very long.

method like scanf, getsneed to know the max length you may input, so that your input size is less than your buffer size.

So Is there any good ways to handle it?

Answer must be only in C, not C++, so c++ string is not what I want. I want is C standard string, something like char* and end with '\0'.

答:
One of the method is using getchar() function we can get input in a character and transfer it to dynamicall created array. You can see that when it exceeds the default length set by us, we reallocated space for storing character</p>

```<code>#include<stdio.h>
#include<stdlib.h>

void main(){
    int size = 10;
    char* str;
    str = (char*) calloc(size,sizeof(char));
    char c;
    c = getchar();
    int t = 0;
    int cnt = 0;
    int len;

    while(c!='\n') {
        if(cnt > size) {
            str = (char*) realloc(str,2*cnt);
        }

        str[t] = c;
        c = getchar();
        t++;
        cnt++;
    }
        str[t]='\0';
    printf("The string is %s\n",str);
    len = strlen(str);
    printf("The size is %d",len);
}
</code>```

Body:
One of the method is using getchar() function we can get input in a character and transfer it to dynamicall created array. You can see that when it exceeds the default length set by us, we reallocated space for storing character

#include<stdio.h>
#include<stdlib.h>

void main(){
    int size = 10;
    char* str;
    str = (char*) calloc(size,sizeof(char));
    char c;
    c = getchar();
    int t = 0;
    int cnt = 0;
    int len;

    while(c!='\n') {
        if(cnt > size) {
            str = (char*) realloc(str,2*cnt);
        }

        str[t] = c;
        c = getchar();
        t++;
        cnt++;
    }
        str[t]='\0';
    printf("The string is %s\n",str);
    len = strlen(str);
    printf("The size is %d",len);
}


问:
What does a weighted word embedding mean?
In the paper that I am trying to implement, it says,

In this work, tweets were modeled using three types of text
  representation. The first one is a bag-of-words model weighted by
  tf-idf (term frequency
  - inverse document frequency) (Section
  2.1.1). The second represents a sentence by averaging the word embeddings of all words (in the sentence) and the third represents a
  sentence by averaging the weighted word embeddings of all words, the
  weight of a word is given by tf-idf (Section
  2.1.2).

I am not sure about the third representation which is mentioned as the weighted word embeddings which is using the weight of a word is given by tf-idf. I am not even sure if they can used together.

答:
In this article or this one, we use weighted sums, idf weighting and Part-of-speech weighting and a mixed method which use both. The mixed method is the best and help us to be first in the SemEval 2017 similarity task for english-spanish and for arabic-arabic (actually we were officially second for arabic because we did not send the mixed method for some reasons).

It is very easy to implement and to use, you have formula in the article but in a nutshell, the vector of a sentence is simply V =  sum_i^k=1 Posweight(w_i) * IDFWeight(w_i) * V_i


问:
How to append out and err stream print in log file using log4j through properties file
How to append System.out.println() and System.err.println() in log file by using log4j properties file in project.

```

    log=E:/log

    log4j.rootLogger=DEBUG,CONSOLE,FILE

    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE.File=${log}/log_out.txt
    log4j.appender.CONSOLE.Target=System.out
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

    log4j.appender.FILE=org.apache.log4j.RollingFileAppender
    log4j.appender.FILE.File=${log}/log_err.txt
    log4j.appender.FILE.MaxFileSize=512KB
    log4j.appender.FILE.MaxBackupIndex=3
    log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
    log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

```

I'm facing an error log4j:WARN No such property [file] in org.apache.log4j.ConsoleAppender.

答:
log4j.appender.CONSOLE.File=${log}/log_out.txt is not needed here, only log4j.appender.FILE.File=${log}/log_err.txt will do.

You are getting above error because log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender represents this class needs to be used as an appender in log4j, which does not contain file field. ConsoleAppender is used to append the console and RollingFileAppender writes it to the file specified.

Body:
How to append System.out.println() and System.err.println() in log file by using log4j properties file in project.

    log=E:/log

    log4j.rootLogger=DEBUG,CONSOLE,FILE

    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE.File=${log}/log_out.txt
    log4j.appender.CONSOLE.Target=System.out
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

    log4j.appender.FILE=org.apache.log4j.RollingFileAppender
    log4j.appender.FILE.File=${log}/log_err.txt
    log4j.appender.FILE.MaxFileSize=512KB
    log4j.appender.FILE.MaxBackupIndex=3
    log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
    log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

I'm facing an error log4j:WARN No such property [file] in org.apache.log4j.ConsoleAppender.


问:
How many users have got the updated app version
I have recently pushed a new version of an Android App to the play store, and would like to see how many of our users have managed to get the update already.

There seems to be stats for days on the android version and the devices that are being used, but I cant seem to find anything on what version of the app my users are using.

答: The play console has changed, now you need to go to "Statistics" in the left menu, then click on "configure report", choose "app version" in the right column. Then you have the statistics by app version in the last section of the page.</p>


问:
How do i click on a link that loads a html page and then using ajax (without clicking anything) load an external html page?
Hi i want to click on a button that loads a different html page and then i want to automatically load via ajax an external html page. How do i do that? Thanks

UPDATE

{
//link icon to correspoding link on what we do
$('#websites').click(function() {
$('#loading_content').hide().load('what-we-do/istoselides.html').fadeIn(1000)
return false;
});
}

That doesnt work cause of the return false. But it doesnt work neither when i take it away! Any ideas?? Thanks a bunch!

答: You can use .load() for this.

ContentLicense: CC BY-SA 2.5

Body: You can use .load() for this.


问:
Python3 - using pandas to group rows, where two colums contain values in forward or reverse order: v1,v2 or v2,v1
I'm fairly new to python and pandas, but I've written code that reads an excel workbook, and groups rows based on the values contained in two columns.

So where Col_1=A and Col_2=B, or Col_1=B and Col_2=A, both would be assigned a GroupID=1.

sample spreadsheet data, with rows color coded for ease of visibility
I've manged to get this working, but I wanted to know if there's a more simpler/efficient/cleaner/less-clunky way to do this.

```<code>import pandas as pd
df = pd.read_excel('test.xlsx')

# get column values into a list
col_group = df.groupby(['Header_2','Header_3'])
original_list = list(col_group.groups)

# parse list to remove 'reverse-duplicates'
new_list = []
for a,b in original_list:
    if (b,a) not in new_list:
        new_list.append((a,b))

# iterate through each row in the DataFrame
# check to see if values in the new_list[] exist, in forward or reverse
for index, row in df.iterrows():
    for a,b in new_list:
        # if the values exist in forward direction
        if (a in df.loc[index, "Header_2"]) and (b in df.loc[index,"Header_3"]):
            # GroupID value given, where value is index in the new_list[]
            df.loc[index,"GroupID"] = new_list.index((a,b))+1
        # else check if value exists in the reverse direction
        if (b in df.loc[index, "Header_2"]) and (a in df.loc[index,"Header_3"]):
            df.loc[index,"GroupID"] = new_list.index((a,b))+1

# Finally write the DataFrame to a new spreadsheet
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer, 'Sheet1')
</code>```

I know of the pandas.groupby([columnA, columnB]) option, but I couldn't figure a way to create groups that contained both (v1, v2) and (v2,v1).

答:
I would do something like this.

```<code>import pandas as pd
df = pd.read_excel('test.xlsx')

#make the ordering consistent
df["group1"] = df[["Header_2","Header_3"]].max(axis=1)
df["group2"] = df[["Header_2","Header_3"]].min(axis=1)

#group them together
df = df.sort_values(by=["group1","group2"])
</code>```

If you need to deal with more than two columns, I can write up a more general way to do this.

Body:
I'm fairly new to python and pandas, but I've written code that reads an excel workbook, and groups rows based on the values contained in two columns.

So where Col_1=A and Col_2=B, or Col_1=B and Col_2=A, both would be assigned a GroupID=1.

sample spreadsheet data, with rows color coded for ease of visibility
I've manged to get this working, but I wanted to know if there's a more simpler/efficient/cleaner/less-clunky way to do this.

import pandas as pd
df = pd.read_excel('test.xlsx')

# get column values into a list
col_group = df.groupby(['Header_2','Header_3'])
original_list = list(col_group.groups)

# parse list to remove 'reverse-duplicates'
new_list = []
for a,b in original_list:
    if (b,a) not in new_list:
        new_list.append((a,b))

# iterate through each row in the DataFrame
# check to see if values in the new_list[] exist, in forward or reverse
for index, row in df.iterrows():
    for a,b in new_list:
        # if the values exist in forward direction
        if (a in df.loc[index, "Header_2"]) and (b in df.loc[index,"Header_3"]):
            # GroupID value given, where value is index in the new_list[]
            df.loc[index,"GroupID"] = new_list.index((a,b))+1
        # else check if value exists in the reverse direction
        if (b in df.loc[index, "Header_2"]) and (a in df.loc[index,"Header_3"]):
            df.loc[index,"GroupID"] = new_list.index((a,b))+1

# Finally write the DataFrame to a new spreadsheet
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer, 'Sheet1')

I know of the pandas.groupby([columnA, columnB]) option, but I couldn't figure a way to create groups that contained both (v1, v2) and (v2,v1).

Body:
I would do something like this.

import pandas as pd
df = pd.read_excel('test.xlsx')

#make the ordering consistent
df["group1"] = df[["Header_2","Header_3"]].max(axis=1)
df["group2"] = df[["Header_2","Header_3"]].min(axis=1)

#group them together
df = df.sort_values(by=["group1","group2"])

If you need to deal with more than two columns, I can write up a more general way to do this.


问:
The program is not running in visual studio 2017
I am Trying to make phone book in c++ using unordered map.There is no error in the code its executing perfectly in cpp.sh but not in visual studio 2017 can any one help me with it? Am I missing any library or any statement or should I try Any thing else.
Here is my code:</p>

```<code>  #include <iostream>
 #include <string>
#include <unordered_map>
 using namespace std;
 int a;
    class phoneBook {
 public:
int y;
string name;
long int number;
unordered_map <string, long int>::iterator it;
unordered_map<string, long int> m;
void enter()
{

    cout << "Enter Name: ";
    cin.ignore();
    getline(cin, name);
    cout << "Enter Phone Number: ";
    cin >> number;
    m.insert(make_pair(name, number));
    return;
}
void search()
{
    cout << "Enter Name: ";
    cin.ignore();
    getline(cin, name);
    it = m.find(name);
    if (it != m.end())
    {
        cout << "Name:- " << name << endl;
        cout << "Number:- " << it->second << endl;
    }
    else {
        cout << "Not Found";
       }
       cout << endl;
        return;
       }
      };
     int main()
    {
        phoneBook p;
       while (a != 0)
      {
            cout << "Enter 1 to add phone number" << endl;
              cout << "Enter 2 to search for phone number" << endl;
          cout << "Enter 0 to exit" << endl;
            cin >> a;
    if (a == 1)
    {
        p.enter();
    }
    if (a == 0 || a == 0)
    {
        break;
    }
    else if (a == 2)
    {
        p.search();
    }
}
return 0;
system("pause");
}
</code>```

答:
a is global variable, its default value is 0, hence when main function starts condition in your while loop a != 0 returns false and main ends working.

Initialize a variable with value other than 0.

Body:
I am Trying to make phone book in c++ using unordered map.There is no error in the code its executing perfectly in cpp.sh but not in visual studio 2017 can any one help me with it? Am I missing any library or any statement or should I try Any thing else.
Here is my code:

  #include <iostream>
 #include <string>
#include <unordered_map>
 using namespace std;
 int a;
    class phoneBook {
 public:
int y;
string name;
long int number;
unordered_map <string, long int>::iterator it;
unordered_map<string, long int> m;
void enter()
{

    cout << "Enter Name: ";
    cin.ignore();
    getline(cin, name);
    cout << "Enter Phone Number: ";
    cin >> number;
    m.insert(make_pair(name, number));
    return;
}
void search()
{
    cout << "Enter Name: ";
    cin.ignore();
    getline(cin, name);
    it = m.find(name);
    if (it != m.end())
    {
        cout << "Name:- " << name << endl;
        cout << "Number:- " << it->second << endl;
    }
    else {
        cout << "Not Found";
       }
       cout << endl;
        return;
       }
      };
     int main()
    {
        phoneBook p;
       while (a != 0)
      {
            cout << "Enter 1 to add phone number" << endl;
              cout << "Enter 2 to search for phone number" << endl;
          cout << "Enter 0 to exit" << endl;
            cin >> a;
    if (a == 1)
    {
        p.enter();
    }
    if (a == 0 || a == 0)
    {
        break;
    }
    else if (a == 2)
    {
        p.search();
    }
}
return 0;
system("pause");
}


问:
How to use HttpClient to consume the data from an xml content site and return them as List of Json object?
Here, I have a sample link which contains xml data as shown below. As you can see on the xml content from the given link,
there are xml element <DisplayName>Name of the employee</DisplayName>.I want to get all the values from the DisplayName elements. How to get the content of every xml element DisplayName and return them as
list of json objects? So far, here's what I have tried below but it doesn't return anything. When I put a breakpoint, I found out that the response.IsSuccessStatusCode = false
and the ReasonPhrase and StatusCode is Unauthorized. How do I get this thing done and what I've been missing?

```<code> private const string URL = "https://apidev.mysite.net/employees/";
        [Route("api/Personnel/UserNames")]
        [HttpGet]
       public List<ADGroup> AutocompleteUserNames(string searchText)
        {

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(searchText).Result;
            //  response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsStringAsync().Result;
                List<ADGroup> result = AutoMapper.Mapper.Map<List<ADGroup>>(data);
                return result;
            }
            else
            {
                 return new List<ADGroup>();

            }
        }
</code>```

Sample link:
https://apidev.mysite.net/employees/shea

XML content of the link:

```<code><ArrayOfEmployeeVm xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MySite.Api.WebApi.Models">
<EmployeeVm>
<ActiveDirectoryName>dfhdfhdffhf</ActiveDirectoryName>
<BusinessPhone>4646456</BusinessPhone>
<DisplayName>Shea, Danny J.</DisplayName>
<Email>timothy.shea@mysite.com</Email>
<EmployeeId>19072</EmployeeId>
<EmployeeIdOriginal>19072</EmployeeIdOriginal>
<FirstName>Danny J.</FirstName>
<FullName>Danny J. Shea</FullName>
<IsActive>true</IsActive>
<LastName>Shea</LastName>
<Office>Boston</Office>
<PracticeGroup>HLB Consulting</PracticeGroup>
<Title>Of Counsel</Title>
</EmployeeVm>

<EmployeeVm>
<ActiveDirectoryName>MPtshdfh</ActiveDirectoryName>
<BusinessPhone>+4546556</BusinessPhone>
<DisplayName>Shearer, Dennis D.</DisplayName>
<Email>dennis.shearer@mysite.com</Email>
<EmployeeId>60048</EmployeeId>
<EmployeeIdOriginal>60048</EmployeeIdOriginal>
<FirstName>Dennis D.</FirstName>
<FullName>Dennis D. Shearer</FullName>
<IsActive>true</IsActive>
<LastName>Shearer</LastName>
<Office>San Francisco</Office>
<PracticeGroup>Office Services</PracticeGroup>
<Title>Facilities Manager</Title>
</EmployeeVm>

<EmployeeVm>
<ActiveDirectoryName>MPghdjgj</ActiveDirectoryName>
<BusinessPhone>+45645757</BusinessPhone>
<DisplayName>Shea, Ted P.</DisplayName>
<Email>ted.shea@mysite.com</Email>
<EmployeeId>74251</EmployeeId>
<EmployeeIdOriginal>74251</EmployeeIdOriginal>
<FirstName>Ted P.</FirstName>
<FullName>Ted P. Shea</FullName>
<IsActive>true</IsActive>
<LastName>Shea</LastName>
<Office>Philadelphia</Office>
<PracticeGroup>Information Technology</PracticeGroup>
<Title>Chief Information Officer</Title>
</EmployeeVm>
</ArrayOfEmployeeVm>
</code>```

答:
The remote service is returning response as "Unauthorized". So, before retrieving data from service, you should perform Authorization  and it depends on of remote service's authorization type. It might be Windows Authentication, Basic Authentication or something like that.

If the remote service is configured as Windows Authentication, you can try to set credentials for HttpClient;

```<code>var handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
var client = new HttpClient(handler);
</code>```

Body:
Here, I have a sample link which contains xml data as shown below. As you can see on the xml content from the given link,
there are xml element <DisplayName>Name of the employee</DisplayName>.I want to get all the values from the DisplayName elements. How to get the content of every xml element DisplayName and return them as
list of json objects? So far, here's what I have tried below but it doesn't return anything. When I put a breakpoint, I found out that the response.IsSuccessStatusCode = false
and the ReasonPhrase and StatusCode is Unauthorized. How do I get this thing done and what I've been missing?

 private const string URL = "https://apidev.mysite.net/employees/";
        [Route("api/Personnel/UserNames")]
        [HttpGet]
       public List<ADGroup> AutocompleteUserNames(string searchText)
        {

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(searchText).Result;
            //  response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsStringAsync().Result;
                List<ADGroup> result = AutoMapper.Mapper.Map<List<ADGroup>>(data);
                return result;
            }
            else
            {
                 return new List<ADGroup>();

            }
        }

Sample link:
https://apidev.mysite.net/employees/shea

XML content of the link:

<ArrayOfEmployeeVm xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MySite.Api.WebApi.Models">
<EmployeeVm>
<ActiveDirectoryName>dfhdfhdffhf</ActiveDirectoryName>
<BusinessPhone>4646456</BusinessPhone>
<DisplayName>Shea, Danny J.</DisplayName>
<Email>timothy.shea@mysite.com</Email>
<EmployeeId>19072</EmployeeId>
<EmployeeIdOriginal>19072</EmployeeIdOriginal>
<FirstName>Danny J.</FirstName>
<FullName>Danny J. Shea</FullName>
<IsActive>true</IsActive>
<LastName>Shea</LastName>
<Office>Boston</Office>
<PracticeGroup>HLB Consulting</PracticeGroup>
<Title>Of Counsel</Title>
</EmployeeVm>

<EmployeeVm>
<ActiveDirectoryName>MPtshdfh</ActiveDirectoryName>
<BusinessPhone>+4546556</BusinessPhone>
<DisplayName>Shearer, Dennis D.</DisplayName>
<Email>dennis.shearer@mysite.com</Email>
<EmployeeId>60048</EmployeeId>
<EmployeeIdOriginal>60048</EmployeeIdOriginal>
<FirstName>Dennis D.</FirstName>
<FullName>Dennis D. Shearer</FullName>
<IsActive>true</IsActive>
<LastName>Shearer</LastName>
<Office>San Francisco</Office>
<PracticeGroup>Office Services</PracticeGroup>
<Title>Facilities Manager</Title>
</EmployeeVm>

<EmployeeVm>
<ActiveDirectoryName>MPghdjgj</ActiveDirectoryName>
<BusinessPhone>+45645757</BusinessPhone>
<DisplayName>Shea, Ted P.</DisplayName>
<Email>ted.shea@mysite.com</Email>
<EmployeeId>74251</EmployeeId>
<EmployeeIdOriginal>74251</EmployeeIdOriginal>
<FirstName>Ted P.</FirstName>
<FullName>Ted P. Shea</FullName>
<IsActive>true</IsActive>
<LastName>Shea</LastName>
<Office>Philadelphia</Office>
<PracticeGroup>Information Technology</PracticeGroup>
<Title>Chief Information Officer</Title>
</EmployeeVm>
</ArrayOfEmployeeVm>

Body:
The remote service is returning response as "Unauthorized". So, before retrieving data from service, you should perform Authorization  and it depends on of remote service's authorization type. It might be Windows Authentication, Basic Authentication or something like that.

If the remote service is configured as Windows Authentication, you can try to set credentials for HttpClient;

var handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
var client = new HttpClient(handler);


问:
How to use in gradle a jar from the Local Maven repository
For some reason cannot find an example that shows publishing  a jar in one project and then using this jar in another project.

So, my first library project has the following build.gradle:

```<code>apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'

version = '1.0.0'
repositories {   mavenLocal() }
group = 'com-hlibrary'
publishing {
    publications {
         mavenJava(MavenPublication) {
             from components.java
          }
       }
   }
</code>```

This script publishes a jar with the following path:

```<code>~/.m2/repository/com-hlibrary/gradle-library/1.0.0/gradle-library-1.0.0.jar
</code>```

The pom file gradle-library-1.0.0.pom in the same directory is as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com-hlibrary</groupId>
<artifactId>gradle-library</artifactId>
<version>1.0.0</version>
</project>
</code>```

The Java file I want to use is as follows:

```<code>package com.hlibrary;
import java.time.LocalTime;
public class HourClass {
    public static int getHour() {
        LocalTime localTime = LocalTime.now();
        return localTime.getHour();
    }
}
</code>```

So, in my another project I have a gradle.build with the dependency to the built jar:

```<code>apply plugin: 'java-library'
apply plugin: 'maven'
apply plugin: 'maven-publish'
repositories {
    jcenter()
    mavenLocal()
}

dependencies {
    compile ("com.hlibrary:gradle-library:1.0.0")
}
</code>```

However after I type

```<code> gradle dependencies
</code>```

I see numerous errors like this:

```<code>compile - Dependencies for source set 'main' (deprecated, use 'implementation ' instead).
\--- com.hlibrary:gradle-library:1.0.0 FAILED
</code>```

答:
Try instead

```<code>compile ("com.hlibrary:gradle-library:1.0.0 )
</code>```

The format is "group:artifactId:version"

you can check the .pom file in

~/.m2/repository/com-hlibrary/gradle-library/1.0.0/gradle-library-1.0.0.pom

Body:
For some reason cannot find an example that shows publishing  a jar in one project and then using this jar in another project.

So, my first library project has the following build.gradle:

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'

version = '1.0.0'
repositories {   mavenLocal() }
group = 'com-hlibrary'
publishing {
    publications {
         mavenJava(MavenPublication) {
             from components.java
          }
       }
   }

This script publishes a jar with the following path:

~/.m2/repository/com-hlibrary/gradle-library/1.0.0/gradle-library-1.0.0.jar

The pom file gradle-library-1.0.0.pom in the same directory is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com-hlibrary</groupId>
<artifactId>gradle-library</artifactId>
<version>1.0.0</version>
</project>

The Java file I want to use is as follows:

package com.hlibrary;
import java.time.LocalTime;
public class HourClass {
    public static int getHour() {
        LocalTime localTime = LocalTime.now();
        return localTime.getHour();
    }
}

So, in my another project I have a gradle.build with the dependency to the built jar:

apply plugin: 'java-library'
apply plugin: 'maven'
apply plugin: 'maven-publish'
repositories {
    jcenter()
    mavenLocal()
}

dependencies {
    compile ("com.hlibrary:gradle-library:1.0.0")
}

However after I type

 gradle dependencies

I see numerous errors like this:

compile - Dependencies for source set 'main' (deprecated, use 'implementation ' instead).
\--- com.hlibrary:gradle-library:1.0.0 FAILED

Body:
Try instead

compile ("com.hlibrary:gradle-library:1.0.0 )

The format is "group:artifactId:version"

you can check the .pom file in

~/.m2/repository/com-hlibrary/gradle-library/1.0.0/gradle-library-1.0.0.pom


问:
What is the cost of calling jQuery and jQuery UI on every page?
I have an intranet site where half of the pages use jQuery, and ~20% use jQuery UI. Users who navigate the site will almost certainly open a page containing jQuery UI during their visit.

What I'd like to do is use for all pages a standard template that includes calls to jQuery and jQuery UI. It would make the site maintenance easier, but it also means that for 80% of my pages jQuery UI will be loaded for nothing.

What I have been told is that I should not worry too much about that. Calls to jQuery and jQuery UI will be cached by the browser, so anyway they'll only be called once during the user's visit.

Is this correct? Or are there other performance factors that could make the systematic call a bad idea?

答:
In short — yes. Don't worry about it too much. Especially in an intranet application. If you want to improve load times combine your JS files into on single file and compress this file.

Here's one of many questions on SO which deals with this solution (in this case using PHP): Combining and Compressing multiple JavaScript files in php


问:
Multiple document.getElementById
I have an image zoomer that I am using in a modal. The zoomer plugin uses an document.getElementById to open the image but I need it to open multiple images.

I have read many of your posts that say I need to use other selectors such as

```<code>(document.querySelectorAll("#galley1, #galley2, #galley3));
</code>```

or a class selector

```<code>(document.getElementsByClassName("galley"));
</code>```

I have tried these but still can't get it to open the image zoomer with multiple ID's.

The ID I am using on the divs and for the selector are #galley1, #galley2, #galley3.

You can see the entire code at my website http://www.fitzgeraldoilworks.com. The first image on the page works perfect but the rest of the images will not zoom in the modal.

```<code><html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<title>Photo Zoom</title>

<link rel="stylesheet" type="text/css" href="css/lity.css"/>
<link rel="stylesheet" type="text/css" href="css/viewer.css"/>

<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/lity.min.js"></script>
<script type="text/javascript" src="js/viewer.js"></script>

</head>

<body>

<div class="featured-body-wrap">
  <div class ="featured-image-container">

       <div class ="featured-image-holder">
           <div class="featured-title">KINGS CHOICE</div>

        <div class ="featured-image-wrap">
            <a href="#kings" data-lity> <img src="images/art/thmb/kings choice320.jpg"
            class="featured-image" style="width:100%;height:auto;border:0;"/></a>
        </div>
       </div>

<div id="kings" class="lity-hide">
<div id="galley1">

          <div class="modal-img-container">

                           <div class="modal-header">Kings Choice</div>

              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/kings choice1500.jpg" src="images/art/med/kings choice700.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/kings choice wall1500.jpg" src="images/art/med/kings choice wall700.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/kings choice head1400.jpg" src="images/art/med/kings choice head700.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>

          </div>
</div>
</div>

       <div class ="featured-image-holder">
           <div class="featured-title">WISPER</div>

        <div class ="featured-image-wrap">
            <a href="#wisper" data-lity> <img src="images/art/thmb/wisper thmb320.jpg"
            class="featured-image" style="width:100%;height:auto;border:0;"/></a>
        </div>
       </div>

<div id="wisper" class="lity-hide">
<div id="galley2">

          <div class="modal-img-container">

                           <div class="modal-header">WISPER</div>

              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/wisper hires.jpg" src="images/art/med/wisper md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/wisper face hires.jpg" src="images/art/med/wisper face md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/wisper wall hires.jpg" src="images/art/med/wisper wall md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>

          </div>
</div>
</div>

        <div class ="featured-image-wrap">
            <a href="#shadow" data-lity> <img src="images/art/thmb/shadow thmb.jpg"
            class="featured-image" style="width:100%;height:auto;border:0;"/></a>
        </div>
       </div>

<div id="shadow" class="lity-hide">
<div id="galley3">

          <div class="modal-img-container">

                           <div class="modal-header">SHADOW</div>

              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/shadow-hires.jpg" src="images/art/med/shadow-md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/shadow-easle-hires.jpg" src="images/art/med/shadow-easle-md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/shadow-wall-hires.jpg" src="images/art/med/shadow-wall-md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>

          </div>
</div>
</div>
</div>

      <script type="text/javascript">

    window.addEventListener('DOMContentLoaded', function () {
      var galley = (document.querySelectorAll("#galley1, #galley2, #galley3"));
      var viewer = new Viewer(galley, {
        url: 'data-original',
        button: true,
        navbar: false,
        title: true,
        toolbar: false,
        tooltip: true,
        movable: true,
        zoomable: true,
        scalable: true,
        transition: true,
        zoomRatio: 0.3,
        minZoomRatio: 0.01,
        maxZoomRatio: 100,
        zIndex: 2015,
        inline: false,
        minWidth: 200,
        minHeight: 100,
        viewed: function () {
var context = this;
$('.viewer-canvas').click(function(e){
if(e.target.className == 'viewer-canvas') {
context.viewer.hide();
}
});
}
      });
    });

          </script>

</body>
</html>
</code>```

答:
Your image viewer script probably does not handle multiple elements being passed into it. You will have to initialize it separately for every element:</p>

```<code>var $elements = document.querySelectorAll('...');

for (var i = 0; i < $elements.length; i++) {
    var viewer = new Viewer($elements[i], {...});
}
</code>```

Title: Multiple document.getElementById

Body:
I have an image zoomer that I am using in a modal. The zoomer plugin uses an document.getElementById to open the image but I need it to open multiple images.

I have read many of your posts that say I need to use other selectors such as

(document.querySelectorAll("#galley1, #galley2, #galley3));

or a class selector

(document.getElementsByClassName("galley"));

I have tried these but still can't get it to open the image zoomer with multiple ID's.

The ID I am using on the divs and for the selector are #galley1, #galley2, #galley3.

You can see the entire code at my website http://www.fitzgeraldoilworks.com. The first image on the page works perfect but the rest of the images will not zoom in the modal.

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<title>Photo Zoom</title>

<link rel="stylesheet" type="text/css" href="css/lity.css"/>
<link rel="stylesheet" type="text/css" href="css/viewer.css"/>

KINGS CHOICE

Kings Choice

WISPER

WISPER

SHADOW

Body:
Your image viewer script probably does not handle multiple elements being passed into it. You will have to initialize it separately for every element:

var $elements = document.querySelectorAll('...');

for (var i = 0; i < $elements.length; i++) {
    var viewer = new Viewer($elements[i], {...});
}


问:
Getting UID Reference for Firestore
I'm trying to get a reference to a document's UID so I can use the document elsewhere in my project by it's UID. As per the documentation, I'm doing the following with AngularFire2 (v5):

```<code>var ref= this.afs.collection(placeToAdd).doc();
</code>```

This gives me the following error: "Expected 1 arguments but got 0". It wants me to put an argument in the doc() method. So instead, I do:

```<code>var ref= this.afs.collection(placeToAdd).doc(thing);
</code>```

then I set my Firebase object:

```<code>ref.set({
        item1: 'value 1',
        item2: 'value 2',
        item3: 'value 3'
      });
</code>```

How do I get the ref's Firestore-generated UID now?

答:
To clarify: there is two ways of inserting data in firestore. One recieves the uid from you.

```<code>db.collection(collection).doc(uid).set(data);
</code>```

The other is adding the thocument but letting firestore generate the uid for you.

```<code>db.collection(collection).add(documentData)
.then(ref => {
    console.log("Document written with ID: ", ref.id);
});
</code>```

It's important to note that both set and add return a promise of document ref, in case you want to use it and for error handling.

The documentation covers this in much more detail.

Title: Getting UID Reference for Firestore

Body:
I'm trying to get a reference to a document's UID so I can use the document elsewhere in my project by it's UID. As per the documentation, I'm doing the following with AngularFire2 (v5):

var ref= this.afs.collection(placeToAdd).doc();

This gives me the following error: "Expected 1 arguments but got 0". It wants me to put an argument in the doc() method. So instead, I do:

var ref= this.afs.collection(placeToAdd).doc(thing);

then I set my Firebase object:

ref.set({
        item1: 'value 1',
        item2: 'value 2',
        item3: 'value 3'
      });

How do I get the ref's Firestore-generated UID now?

Body:
To clarify: there is two ways of inserting data in firestore. One recieves the uid from you.

db.collection(collection).doc(uid).set(data);

The other is adding the thocument but letting firestore generate the uid for you.

db.collection(collection).add(documentData)
.then(ref => {
    console.log("Document written with ID: ", ref.id);
});

It's important to note that both set and add return a promise of document ref, in case you want to use it and for error handling.

The documentation covers this in much more detail.


问:
Modifying the weights and biases of a restored CNN model in TensorFlow
I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, I've restored a pre-trained model, and I need to modify the weights and biases of one of its layers before I retest its accuracy. Now, my problem is the following:
how can I change the weights and biases using the assign method in TF? Is modifying the weights of a restored modeled even possible in TF?

Here is my code:

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
  LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
  LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

  # ( Here I'd like to modify the weights and biases of layer 1, set them to one for example, before I go ahead and test the accuracy ) #

  # Testing the acuracy of the model:
  X = g.get_tensor_by_name('ImageIn:0')
  Y = g.get_tensor_by_name('LabelIn:0')
  KP = g.get_tensor_by_name('KeepProb:0')
  Accuracy = g.get_tensor_by_name('NetAccuracy:0')
  feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
  print( 'Model Accuracy = ' )
  print( sess.run( Accuracy, feed_dict ) )
</code>```

答:
Thanks for everyone who responded. I'd just like to put the pieces together. This is the code the helped me accomplish what I want:</p>

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
   LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
   LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

   wc1 = g.get_tensor_by_name('wc1:0')
   sess.run( tf.assign( wc1,tf.multiply(wc1,0) ) )# Setting the values of the variable 'wc1' in the model to zero.

   # Testing the acuracy of the model:
   X = g.get_tensor_by_name('ImageIn:0')
   Y = g.get_tensor_by_name('LabelIn:0')
   KP = g.get_tensor_by_name('KeepProb:0')
   Accuracy = g.get_tensor_by_name('NetAccuracy:0')
   feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
   print( 'Model Accuracy = ' )
   print( sess.run( Accuracy, feed_dict ) )
</code>```

Body:
I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, I've restored a pre-trained model, and I need to modify the weights and biases of one of its layers before I retest its accuracy. Now, my problem is the following:
how can I change the weights and biases using the assign method in TF? Is modifying the weights of a restored modeled even possible in TF?

Here is my code:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
  LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
  LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

  # ( Here I'd like to modify the weights and biases of layer 1, set them to one for example, before I go ahead and test the accuracy ) #

  # Testing the acuracy of the model:
  X = g.get_tensor_by_name('ImageIn:0')
  Y = g.get_tensor_by_name('LabelIn:0')
  KP = g.get_tensor_by_name('KeepProb:0')
  Accuracy = g.get_tensor_by_name('NetAccuracy:0')
  feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
  print( 'Model Accuracy = ' )
  print( sess.run( Accuracy, feed_dict ) )

Body:
Thanks for everyone who responded. I'd just like to put the pieces together. This is the code the helped me accomplish what I want:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
   LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
   LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

   wc1 = g.get_tensor_by_name('wc1:0')
   sess.run( tf.assign( wc1,tf.multiply(wc1,0) ) )# Setting the values of the variable 'wc1' in the model to zero.

   # Testing the acuracy of the model:
   X = g.get_tensor_by_name('ImageIn:0')
   Y = g.get_tensor_by_name('LabelIn:0')
   KP = g.get_tensor_by_name('KeepProb:0')
   Accuracy = g.get_tensor_by_name('NetAccuracy:0')
   feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
   print( 'Model Accuracy = ' )
   print( sess.run( Accuracy, feed_dict ) )


问:
Android Studio - ADB start server fails, adbkey check fails
Problem: adb start-server fails.

```<code>--- adb starting (pid 1414) ---
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Version 27.0.0-4455170
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Installed as /Users/[username]/Library/Android/sdk/platform-tools/adb
adb I 12-05 17:28:30  1414 48453 main.cpp:57]
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:416]
adb_auth_init...
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:174] read_key_file '/Users/[username]/.android/adbkey'...
adb F 12-05 17:28:30  1414 48466 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)
</code>```

Catalyst: Installing platform tools v27.0.0

Solutions Tried: Restarting Android Studio, Restarting computer, Manually starting ADB via terminal, deleting /Users/[username]/.android/adbkey and adbkey.pub, and reinstalling platform tools

Also I am not using genymotion, just the stock emulator.

答:
I ran into the same issue.

I got 27.0.0 to work by "Revoke USB debugging authorizations" under Debug Settings on the phone and rebooting phone and rebooting Mac. And it worked.

However, I had switched to not using my dock and plugging a Pixel straight into the MacBook (USB-C) since I had earlier suspected that. But that is not my normal hook up.

When I switched back to the dock the whole problem started again.

So I guess I'll roll back to 26.0.2

Body:
Problem: adb start-server fails.

--- adb starting (pid 1414) ---
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Version 27.0.0-4455170
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Installed as /Users/[username]/Library/Android/sdk/platform-tools/adb
adb I 12-05 17:28:30  1414 48453 main.cpp:57]
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:416]
adb_auth_init...
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:174] read_key_file '/Users/[username]/.android/adbkey'...
adb F 12-05 17:28:30  1414 48466 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)

Catalyst: Installing platform tools v27.0.0

Solutions Tried: Restarting Android Studio, Restarting computer, Manually starting ADB via terminal, deleting /Users/[username]/.android/adbkey and adbkey.pub, and reinstalling platform tools

Also I am not using genymotion, just the stock emulator.


问:
Check the form input value to existing value in Django
In in my database there are some emails those should be checked with the form value which is entered in email field

models.py

```<code>class Friend(models.Model):
    email = models.EmailField(max_length=100)
</code>```

forms.py

```<code>class FriendForm(forms.ModelForm):

    class Meta:
        model = Friend
        fields = ['email']
</code>```

views.py

```<code>def check(request):
     if request.method == "POST":
        form = FriendForm(request.POST)
        if form.is_valid():
            queryset = Friend.objects.all
            return render(request,"two.html",{"queryset":queryset})
     else:
        form = FriendForm()
    return render(request, 'emaill.html', {'form': form})
</code>```

emaill.html

```<code><body>
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" name="Submit">
    </form>
 </body>
</code>```

two.html

```<code><body>
 <h1>found</h1>
 {% for obj in queryset %}
 {{obj.email}} </br>
 {% endfor %}
</body>
</code>```

when user submited any email that should be checked with models email that means with existing one if matches in should render to two.html it should show connect
if mail does not match with mail that is in database it should show no such mail

答:
Okay, I understand what you are trying to do. You are doing an email search.

```<code>def check(request):
    if request.method == "POST":
        form = FriendForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data("email")
            try:
                 friend = Friend.objects.get(email=email)
                 return render(request,"email1.html",
                       {"friend":friend})
            except Friend.DoesNotExist:
                return render(request, "email1.html", {"form":form})
</code>```

If you are interested in connecting them, then you should use the get method of the ModelManager (objects). That will return a single object if it exists.
In your template. As you can see I have saved some typing on an extra template by using conditions in the template.

```<code>{% if form %}
  #display your form
{% else %}
  #display the friend as you want
{% endif %}
</code>```

I recommend you go slow and do more reading of the documentation. I am here. Note that I changed your queryset to friend. queryset is misleading as it points that you want multiple objects. So in your template you cant iterate, instead you display friend without iterating.

```<code>{{ friend }}
</code>```

Body:
In in my database there are some emails those should be checked with the form value which is entered in email field

models.py

class Friend(models.Model):
    email = models.EmailField(max_length=100)

forms.py

class FriendForm(forms.ModelForm):

    class Meta:
        model = Friend
        fields = ['email']

views.py

def check(request):
     if request.method == "POST":
        form = FriendForm(request.POST)
        if form.is_valid():
            queryset = Friend.objects.all
            return render(request,"two.html",{"queryset":queryset})
     else:
        form = FriendForm()
    return render(request, 'emaill.html', {'form': form})

emaill.html

    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" name="Submit">
    </form>

two.html

found

 {% for obj in queryset %}
 {{obj.email}}

 {% endfor %}

when user submited any email that should be checked with models email that means with existing one if matches in should render to two.html it should show connect
if mail does not match with mail that is in database it should show no such mail

Body:
Okay, I understand what you are trying to do. You are doing an email search.

def check(request):
    if request.method == "POST":
        form = FriendForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data("email")
            try:
                 friend = Friend.objects.get(email=email)
                 return render(request,"email1.html",
                       {"friend":friend})
            except Friend.DoesNotExist:
                return render(request, "email1.html", {"form":form})

If you are interested in connecting them, then you should use the get method of the ModelManager (objects). That will return a single object if it exists.
In your template. As you can see I have saved some typing on an extra template by using conditions in the template.

{% if form %}
  #display your form
{% else %}
  #display the friend as you want
{% endif %}

I recommend you go slow and do more reading of the documentation. I am here. Note that I changed your queryset to friend. queryset is misleading as it points that you want multiple objects. So in your template you cant iterate, instead you display friend without iterating.

{{ friend }}


问:
over image preventing button from being clicked
Good afternoon
in an html site, I have one rectangular image and when I hover over it a second image pops out. The second image is bigger than the original image and it on top of a button.
The problem is, I can't click the button, it always triggers the hover image.
How can fix this so that I can click the button?
Here's a fiddle

HTML:

```<code>    <li id="menu-item-2365" class="positionabsolute menu-item menu-item-type-custom menu-item-object-custom current-menu-item menu-item-2365 has-image"><a href="como-ajudar/donativos/"
 class="menu-image-title-hide menu-image-hovered"><span class="menu-image-hover-wrapper">
    <img width="126" height="38" src="http://piq.codeus.net/static/media/userpics/piq_307293_400x400.png" class="menu-image menu-image-title-hide" style="position:absolute" alt=""><img width="126" height="145" src="http://piq.codeus.net/static/media/userpics/piq_307293_400x400.png" style="position:absolute" class="hovered-image menu-image-title-hide" alt="" ></span></a></li>
    <br/>
    <br/>
    <br/>
    <input type="button" value="click" style="margin-left:50px" />
</code>```

https://jsfiddle.net/u15qbh6w/

答:
You can set display: none to the second image and if it is hovered, then display: initial

So the css of your example would look like that:

```<code>.menu-item a.menu-image-hovered img.hovered-image,
.menu-item a.menu-image-hovered:hover img.menu-image {
  opacity: 0;
  transition: opacity 0.25s ease-in-out 0s;
}
.menu-item a.menu-image-hovered img.hovered-image {
  display: none;
}
.menu-item a.menu-image-hovered:hover img.hovered-image {
  display: initial;
  opacity: 1;
}
</code>```

Body:
Good afternoon
in an html site, I have one rectangular image and when I hover over it a second image pops out. The second image is bigger than the original image and it on top of a button.
The problem is, I can't click the button, it always triggers the hover image.
How can fix this so that I can click the button?
Here's a fiddle

HTML:

    <input type="button" value="click" style="margin-left:50px" />

https://jsfiddle.net/u15qbh6w/

Body:
You can set display: none to the second image and if it is hovered, then display: initial

So the css of your example would look like that:

.menu-item a.menu-image-hovered img.hovered-image,
.menu-item a.menu-image-hovered:hover img.menu-image {
  opacity: 0;
  transition: opacity 0.25s ease-in-out 0s;
}
.menu-item a.menu-image-hovered img.hovered-image {
  display: none;
}
.menu-item a.menu-image-hovered:hover img.hovered-image {
  display: initial;
  opacity: 1;
}


问:
Ledger encryption in Hyperledger Fabric 1.0
I am analyzing various attack vectors, including a successful attempt by a malicious party to take over one of Fabric peers and thus, owning a local copy of world state and blockchain ledger.

Is there a native (configurable) option that would allow me to encrypt ledger state and blockchain in Hyperledger Fabric 1.0?

Otherwise, what are best practices which can help me protecting blockchain data to be read by unauthorized parties outside a permissioned network?

答:
It's a great question.

by default, in the current version (HLF 1.0.4) the data will not be encrypted. I've checked this using the code snippet provided with this git repo.

I did some trivial tests just by reading all the World State key/values (it's regular levelDB) after invoking some test transactions with HLF cli container. In result all values have been written decrypted.

Fortunately, HLF developers did their job and data encryption will be available in HLF 1.1. According to the release notes available here:

FAB-830 Encryption library for chaincode
  Encrypt your data using the new chaincode encryption library.

So you can wait for official release of HLF 1.1 - or, with the current version of HLF 1.0.4, you can pass already encrypted data to the chaincode, but the side effect is that your Invoke function  will not be able add any custom logic (unless you pass also the key needed to decode it).


问:
Trying to use show/hide to slowly fade In/ fade Out a paragraph
I'm trying to make to show/hide a paragraph when buttons are pressed.
But also to look like slow movement up and down.

That's how the HTML look like for example :

```<code><button class="hideA">Hide</button>
<button class="showA">show</button>
<p id>Helloooooooooooooooooooooo.</p>
</code>```

And that's how the Jquery code looks like:

```<code>$(".hideA").click(function(){
    $(".hideA p").hide(function(){
    });
});
$(".showA").click(function(){
    $(".hideA p").show(function(){
    });
});
</code>```

But this code is not running for some reason. please let me know the reason if you can!

答:
for both the below way to work you need to set id of p element

```<code><button class="hideA">Hide</button>
<button class="showA">show</button>
<p id="para">Helloooooooooooooooooooooo.</p>
</code>```

you can try out this way also , by making use of animate function, this will give fill of hiding and lastly it get hidden by visiblity property.

```<code>   $(".hideA").click(function(){
    $( "#para" )
      .css({opacity: 1, visibility: "hidden"})
      .animate({opacity: 0}, 1000);
    });

    $(".showA").click(function(){
     $( "#para" )
     .css({opacity: 0, visibility: "visible"})
     .animate({opacity: 1}, 1000);
    });
</code>```

make use of slideUp and slideDown method . this method provide animation of hiding and showing element but your element stays in DOM

```<code>$(".hideA").click(function(){
    $("#para").slideUp(function(){
    });
});
$(".showA").click(function(){
    $("#para").slideDown(function(){
    });
});
</code>```

working demo at : https://jsfiddle.net/pranayamr/xttk3r6o/

Body:
I'm trying to make to show/hide a paragraph when buttons are pressed.
But also to look like slow movement up and down.

That's how the HTML look like for example :

<button class="hideA">Hide</button>
<button class="showA">show</button>

Helloooooooooooooooooooooo.

And that's how the Jquery code looks like:

$(".hideA").click(function(){
    $(".hideA p").hide(function(){
    });
});
$(".showA").click(function(){
    $(".hideA p").show(function(){
    });
});

But this code is not running for some reason. please let me know the reason if you can!

Body:
for both the below way to work you need to set id of p element

<button class="hideA">Hide</button>
<button class="showA">show</button>
<p id="para">Helloooooooooooooooooooooo.</p>

you can try out this way also , by making use of animate function, this will give fill of hiding and lastly it get hidden by visiblity property.

   $(".hideA").click(function(){
    $( "#para" )
      .css({opacity: 1, visibility: "hidden"})
      .animate({opacity: 0}, 1000);
    });

    $(".showA").click(function(){
     $( "#para" )
     .css({opacity: 0, visibility: "visible"})
     .animate({opacity: 1}, 1000);
    });

make use of slideUp and slideDown method . this method provide animation of hiding and showing element but your element stays in DOM

$(".hideA").click(function(){
    $("#para").slideUp(function(){
    });
});
$(".showA").click(function(){
    $("#para").slideDown(function(){
    });
});

working demo at : https://jsfiddle.net/pranayamr/xttk3r6o/


问:
How to select a video from the gallery and get it's real path?
I can open the gallery with this code,

```<code>    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("video/*");

    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST );
</code>```

It works well on a Samsung Galaxy S5. But in some phones, images are displayed along with videos.

What changes do I need to do to the code to open the gallery to display only videos?

How can I get the real path of the selected video when the results are returned?

答:
You will get real Path from this method getPath

```<code>public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

public static MultipartBody.Part getMultiPartBody(String key, String mMediaUrl) {
    if (mMediaUrl != null) {
        File file = new File(mMediaUrl);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        return MultipartBody.Part.createFormData(key, file.getName(), requestFile);
    } else {
        return MultipartBody.Part.createFormData(key, "");
    }
}
</code>```

}

Body:
I can open the gallery with this code,

    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("video/*");

    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST );

It works well on a Samsung Galaxy S5. But in some phones, images are displayed along with videos.

What changes do I need to do to the code to open the gallery to display only videos?

How can I get the real path of the selected video when the results are returned?

Body:
You will get real Path from this method getPath

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

public static MultipartBody.Part getMultiPartBody(String key, String mMediaUrl) {
    if (mMediaUrl != null) {
        File file = new File(mMediaUrl);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        return MultipartBody.Part.createFormData(key, file.getName(), requestFile);
    } else {
        return MultipartBody.Part.createFormData(key, "");
    }
}

}


问:
Why is event.stopPropagation not cancelling $('html').click?
I have an input field which has a focusout event on it. I also have a click event set on $('html') which transfers focus to a different input field. I wrote a click handler for my input field and put in event.stopPropagation(); but it doesn't seem to be working. What am I missing? What does $('html') refer to? My code:

```<code>p.replaceWith(
    "<input class='memoryEditField' type='text' value=" + p.text() + ">"
  );
var inputField = $(".memoryEditField");
  inputField
  .on("click", function(event) {
    event.stopPropagation();
  })
  .on("focusout", editFieldLostFocus)
  .on("keyup", editFieldKeyPressed);
</code>```

The other input field:

```<code>$("html").on("touchstart", function() {
    MQInput.focus();
});
$("html").on("click", function() {
    MQInput.focus();
});
</code>```

答:
Please provide all of code (what is p in Your code? Also editFieldLostFocus, editFieldKeyPressed).

I think You're missing something in methods editFieldLostFocus, editFieldKeyPressed and it makes illusion that stopPropogation does no work

In fact it works as expected:

$(function() {
  $('p').each(function() {
    var p = $(this);
    p.replaceWith(
      '<input class="memoryEditField" type="text" value="' + p.text() + '">'
    );
  });

  function editFieldLostFocus() {
    console.log('call editFieldLostFocus');
  }

  function editFieldKeyPressed() {
    console.log('call editFieldKeyPressed');
  }

  var inputFields = $(".memoryEditField");
  inputFields
    .on("click", function(event) {
      event.stopPropagation();
      console.log('memoryEditField clicked');
    })
    .on("focusout", editFieldLostFocus)
    .on("keyup", editFieldKeyPressed);

  $("html").on("touchstart", function() {
    console.log('MQInput.focus');
    //MQInput.focus();
  });
  $("html").on("click", function() {
    console.log('MQInput.focus');
    //MQInput.focus();
  });

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

<p>FIELD 1</p><br/>
<p>FIELD 2</p><br/></code>```

Body:
I have an input field which has a focusout event on it. I also have a click event set on $('html') which transfers focus to a different input field. I wrote a click handler for my input field and put in event.stopPropagation(); but it doesn't seem to be working. What am I missing? What does $('html') refer to? My code:

p.replaceWith(
    "<input class='memoryEditField' type='text' value=" + p.text() + ">"
  );
var inputField = $(".memoryEditField");
  inputField
  .on("click", function(event) {
    event.stopPropagation();
  })
  .on("focusout", editFieldLostFocus)
  .on("keyup", editFieldKeyPressed);

The other input field:

$("html").on("touchstart", function() {
    MQInput.focus();
});
$("html").on("click", function() {
    MQInput.focus();
});

Body:
Please provide all of code (what is p in Your code? Also editFieldLostFocus, editFieldKeyPressed).

I think You're missing something in methods editFieldLostFocus, editFieldKeyPressed and it makes illusion that stopPropogation does no work

In fact it works as expected:

$(function() {
  $('p').each(function() {
    var p = $(this);
    p.replaceWith(
      '<input class="memoryEditField" type="text" value="' + p.text() + '">'
    );
  });

  function editFieldLostFocus() {
    console.log('call editFieldLostFocus');
  }

  function editFieldKeyPressed() {
    console.log('call editFieldKeyPressed');
  }

  var inputFields = $(".memoryEditField");
  inputFields
    .on("click", function(event) {
      event.stopPropagation();
      console.log('memoryEditField clicked');
    })
    .on("focusout", editFieldLostFocus)
    .on("keyup", editFieldKeyPressed);

  $("html").on("touchstart", function() {
    console.log('MQInput.focus');
    //MQInput.focus();
  });
  $("html").on("click", function() {
    console.log('MQInput.focus');
    //MQInput.focus();
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>FIELD 1</p><br/>
<p>FIELD 2</p><br/>


问:
Create JSON object instead of an Array using LINQ/JavaScriptSerializer
Hey folks, hope you've all had a good break over the holidays.

I've created a WebService which returns a list of cities and companies within those cities as a JSON string using LINQ/JavaScriptSerializer.

My code is roughly

```<code>var data = from c in db.Companies
           group c by c.City into cities
           select new
           {
               city = cities.Key,
               companies = from company in cities
                     select company.Name
           };

JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(data);
</code>```

That produces the following JSON string

```<code>[
  {"city":"Auckland","companies":["Company1","Company2"]},
  {"city":"Wellington","companies":["Company3","Company4","Company5"]}
]
</code>```

However I want to make the city the key so I can easily search by it

For example

```<code>[
  "Auckland" : {"companies":["Company1","Company2"]},
  "Wellington" : {"companies":["Company3","Company4","Company5"]}
]
</code>```

Any ideas?

答:
Just an idea... try

```<code>var data = db.Companies
             .GroupBy(c => c.City)
             .ToDictionary(g => g.Key,
                           g => new { companies = g.Select(c => c.Name) });
</code>```

So this will build a Dictionary<string, xxx> where xxx is an anonymous type with a single property, "companies" which is a sequence of company names.

Body:
Hey folks, hope you've all had a good break over the holidays.

I've created a WebService which returns a list of cities and companies within those cities as a JSON string using LINQ/JavaScriptSerializer.

My code is roughly

var data = from c in db.Companies
           group c by c.City into cities
           select new
           {
               city = cities.Key,
               companies = from company in cities
                     select company.Name
           };

JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(data);

That produces the following JSON string

[
  {"city":"Auckland","companies":["Company1","Company2"]},
  {"city":"Wellington","companies":["Company3","Company4","Company5"]}
]

However I want to make the city the key so I can easily search by it

For example

[
  "Auckland" : {"companies":["Company1","Company2"]},
  "Wellington" : {"companies":["Company3","Company4","Company5"]}
]

Any ideas?

Body:
Just an idea... try

var data = db.Companies
             .GroupBy(c => c.City)
             .ToDictionary(g => g.Key,
                           g => new { companies = g.Select(c => c.Name) });

So this will build a Dictionary<string, xxx> where xxx is an anonymous type with a single property, "companies" which is a sequence of company names.


问:
Regex that match 3 consecutive words that start and end with the same letter
I have to match 3 consecutive words that start and end with same letters

I have a code like this:

```<code>import re

def regex(file):

    with open(file) as f:

         s=f.read()

    rx=re.compile(r"([a-z])+\s+\1",re.I)

    r=re.findall(rx,s)

    print(r)

    return len(r)
</code>```

The text from the file is something like this

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

and i'm expecting this result:

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

```<code>[('a','o'),('e','a')]
2
</code>```

but i'm getting this:

```<code>['a', 'o', 'e', 'a']
4
</code>```

Any clue?

答:
Use this pattern..

r"([a-z])\s\1\w*([a-z])\s\2"

In the pattern you are using, you are just searching for only 2 words that end and start with the same letter.

To search 3 words, you have to tell that the 3rd and 4th letters are from the same word. This is the simplest way that came into my mind. But this will not be the optimal way..

ps: the answer was edited as suggested in the comment..

Body:
I have to match 3 consecutive words that start and end with same letters

I have a code like this:

import re

def regex(file):

    with open(file) as f:

         s=f.read()

    rx=re.compile(r"([a-z])+\s+\1",re.I)

    r=re.findall(rx,s)

    print(r)

    return len(r)

The text from the file is something like this

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

and i'm expecting this result:

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

[('a','o'),('e','a')]
2

but i'm getting this:

['a', 'o', 'e', 'a']
4

Any clue?


问:
string comparison "=" != "+" , incorrect results
Task is to check whether string results true or false for following given condition:

If a letter a to z occurs it must have '+' before and after the particular letter
This works fine expect the case when '=' comes before or after the letter.
Why this condition is wrong for '=' ?
This code returns true for these strings
Thanks

function SimpleSymbols(str) {
    var temp=str.split("")
    if(temp.length==1 || temp.length==2 )
    return false;
    for(i=0;i<temp.length;i++){
        if(temp[i]>='a' && temp[i]<='z'){
            if(i===0 || i===(temp.length-1)||
            (temp[i-1]!=='+' && temp[i+1]!=='+')){
                return false;
            }
        }
    }
  return true;
}
   ```

答:
Hint: check out these strings too, they all return true even though they should return false.

"+a4"

"1a+"

"%a+"

Let's simplify your condition:

```<code>str[i-1] !== '+' && str[i+1] !== '+'
</code>```

is the same as

```<code>!(str[i-1] === '+' || str[i+1] === '+')
</code>```

This makes it easier to see what you were really checking.

We can see now that the condition str[i-1] !== '+' && str[i+1] !== '+' returns true only if neither of those two characters are a +.

You want it to return true if at least one is not a +. So you should use this instead:

```<code>str[i-1] !== '+' || str[i+1] !== '+'
</code>```

I re-wrote your code with this correct condition here:

```<code>function SimpleSymbols(str) {
    if (str.length == 1 || str.length == 2) return false;
    for (var i = 0; i < str.length; i++) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            if (i === 0 || i === (str.length-1) || (str[i-1] !== '+' || str[i+1] !== '+')) {
                return false;
            }
        }
    }
    return true;
}
</code>```

Note: regular expressions can help out a lot with pattern-matching in strings like this.

E.g. your whole function would have simply become the regex:

```<code>function SimpleSymbols(str) {
  return !str.match(/[^+][a-z][^+]/) && str.length > 2;
}
</code>```

Body:
Hint: check out these strings too, they all return true even though they should return false.

"+a4"

"1a+"

"%a+"

Let's simplify your condition:

str[i-1] !== '+' && str[i+1] !== '+'

is the same as

!(str[i-1] === '+' || str[i+1] === '+')

This makes it easier to see what you were really checking.

We can see now that the condition str[i-1] !== '+' && str[i+1] !== '+' returns true only if neither of those two characters are a +.

You want it to return true if at least one is not a +. So you should use this instead:

str[i-1] !== '+' || str[i+1] !== '+'

I re-wrote your code with this correct condition here:

function SimpleSymbols(str) {
    if (str.length == 1 || str.length == 2) return false;
    for (var i = 0; i < str.length; i++) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            if (i === 0 || i === (str.length-1) || (str[i-1] !== '+' || str[i+1] !== '+')) {
                return false;
            }
        }
    }
    return true;
}

Note: regular expressions can help out a lot with pattern-matching in strings like this.

E.g. your whole function would have simply become the regex:

function SimpleSymbols(str) {
  return !str.match(/[^+][a-z][^+]/) && str.length > 2;
}