问:
How to bind a custom value to the Text property of a TextBlock inside of a ListBox DataTemplate?
I would like my ListBox to number each ListItem using its index + 1.

How would I do that to the Text property of a TextBlock in a DataTemplate of the ListBox?

答:
If each ListBoxItem uses SelectedIndex + 1, they will all display the same value since SelectedIndex is a scalar. Moreover, this number will change as the user selects different ListBoxItems. I suspect you actually want to display each item's index within the ListBox + 1.

To achieve this, you're probably best off using the ListBox's ItemsContainerGenerator to get the index of the item within the container (see the IndexFromContainer method). You could look at exposing this from your data class, or perhaps look into an attached readonly property that retrieves this value for you.

OwnerDisplayName: Malcolm

LastEditorDisplayName: A. Rex

OwnerDisplayName: Kent Boogaart


来源: stackexchange

问:
getting my divs to flow horizontally
Regardless of what I've tried, I cannot get my inner divs to flow horizonatally within the outer div. Please help!!!</p>

```<code><style type="text/css">

#gallery {
width: 688px;
height: 360px;
border: solid;
}

#galleryelements {
width: 650px;
height: 320px;
display:inline;
background-color:#0FF;
}

.s-thumbnail {
width: 50px;
height: 75px;
border: solid;
}

.thumbnail {
width: 100px;
height: 150px;
border: solid;
}

#left {
float:left;
}

#right {
float:right;
}

#Mimage {
width: 200px;
height: 300px;
border: solid;
}
</style>

<body>
<div id="gallery">
<div id="galleryelements">
<div class="s-thumbnail" id="left"></div>
<div class="thumbnail" id="left"></div>
<div id="Mimage"></div>
<div class="thumbnail" id="right"></div>
<div class="s-thumbnail" id="right"></div>
</div>
</div>
</body>
</html>
</code>```

答:
You should never have more than one element on the page with the same ID.

Try ```<code><div class="s-thumbnail left"></div>
<div class="thumbnail left"></div>
<div id="Mimage"></div>
<div class="thumbnail right"></div>
<div class="s-thumbnail right"></div></code>```and then change your CSS from #left and #right to .left and .right.

div#Mimage needs to be floated, else it will span the entire width and push the other floats down.

ContentLicense: CC BY-SA 2.5

Title: getting my divs to flow horizontally

Body:
You should never have more than one element on the page with the same ID.

Try
<div class="s-thumbnail left"></div>
<div class="thumbnail left"></div>
<div id="Mimage"></div>
<div class="thumbnail right"></div>
<div class="s-thumbnail right"></div>
and then change your CSS from #left and #right to .left and .right.

div#Mimage needs to be floated, else it will span the entire width and push the other floats down.


问:
Additional parameters with MongoDB $sample
I've successfully used db.collection('example').aggregate({$sample: {size: 1}}) in Node.js to retrieve a random sample from my collection, however, I'd like to put in an additional parameter to only sample an item from a certain subset.  I've tried adding an additional parameter (e.g., db.collection('example').aggregate({sampleParam: {$gte: 1}}, {$sample: {size: 1}}), which did not work.

I also understand that .skip could achieve this but that it is inefficient.

答:
You query does not work aproply because sampleParam not is a pipeline stage you can try with so this:

```<code>{ "_id" : 11, "score" : 11, "name" : "ahn", "q1" : true, "q2" : true }
{ "_id" : 12, "score" : 12, "name" : "dane", "q1" : true, "q2" : true }
{ "_id" : 13, "score" : 13, "name" : "spec", "q1" : true, "q2" : true }
{ "_id" : 14, "score" : 14, "name" : "axe", "q1" : true, "q2" : true }
{ "_id" : 15, "score" : 15, "name" : "soplo", "q1" : true, "q2" : true }
{ "_id" : 16, "score" : 16, "name" : "tepe", "q1" : true, "q2" : true }
</code>```

I guess that I have an user collections, so:

```<code>> db.user.aggregate([{$match:{score: {$gt:10}}}, {$sample:{size:1}}])
</code>```

The query above return all score greater than 10 and show a simple document with size

ContentLicense: CC BY-SA 3.0

Body:
You query does not work aproply because sampleParam not is a pipeline stage you can try with so this:

{ "_id" : 11, "score" : 11, "name" : "ahn", "q1" : true, "q2" : true }
{ "_id" : 12, "score" : 12, "name" : "dane", "q1" : true, "q2" : true }
{ "_id" : 13, "score" : 13, "name" : "spec", "q1" : true, "q2" : true }
{ "_id" : 14, "score" : 14, "name" : "axe", "q1" : true, "q2" : true }
{ "_id" : 15, "score" : 15, "name" : "soplo", "q1" : true, "q2" : true }
{ "_id" : 16, "score" : 16, "name" : "tepe", "q1" : true, "q2" : true }

I guess that I have an user collections, so:

> db.user.aggregate([{$match:{score: {$gt:10}}}, {$sample:{size:1}}])

The query above return all score greater than 10 and show a simple document with size


问:
In Angular1.6 $anchorScroll, Offset
Can someone explain to me how to use $anchorScroll, Offset, scrollX, scrollY in Components which is in AngularJS 1.6?

答:
Try AngularJS documentation for it

https://docs.angularjs.org/api/ng/service/$anchorScroll

Title: In Angular1.6 $anchorScroll, Offset


问:
Your security settings have blocked an application from running with an out-of-date or expired version of Java
Greetings .

I've encountered a Java Error ,which is actually giving me a nightmare .

It says :

" Application Blocked by Security Settings "

" Your security settings have blocked an application from running with an out-of-date or expired version of Java "

Java Version : 1.7_25 ( Recommended for my work and not an old one i believe)

Workaround i have performed (which did not work) :

Lowered Security Level to Medium.

Cleared Browser Cache and Cookies.

Checked a few settings in the Advanced Tab of the Java Control Panel like :

General : Allow user to grant permissions to signed content.

Java Cache was also cleared.

  Even after performing the above workarounds, one after other, the issue doesn't go and there is no exceptions site list in the security tab either(just for information).

Majority of the issues related to the error would go after the security level is lowered to medium. But mine doesn't.

Hope some one could help me out.
Shall be ever grateful.

Thank you !

AK

答: I had same issue, I reduced security level from high to medium and allowed to run the application at risk, it worked for me.</p>


问:
Custom UDF written in Pyspark giving output as "java.lang.Object"
I have written a custom transformer class POSWordTagger. My _transform() method code is,

```<code>def _transform(self, dataset):

    def f(s):
        tokens = nltk.tokenize.wordpunct_tokenize(s)
        pos_tags = nltk.pos_tag(tokens)
        return pos_tags

t = ArrayType(StringType())
out_col = self.getOutputCol()
in_col = dataset[self.getInputCol()]
return dataset.withColumn(out_col, udf(f, t)(in_col))
</code>```

I am calling my transformer class as follows,

```<code>sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)

sentenceDataFrame = sqlContext.createDataFrame([
  (0, "Hi I heard about Spark"),
  (0, "I wish Java could use case classes"),
  (1, "Logistic regression models are neat")
  ], ["label", "sentence"])

pos_tagger = POSWordTagger(inputCol="sentence", outputCol="pos")

pos_output=pos_tagger.transform(sentenceDataFrame)
pos_output.select("pos").show()
</code>```

I am getting the output as,

```<code>+--------------------+
|                 pos|
+--------------------+
|[[Ljava.lang.Obje...|
|[[Ljava.lang.Obje...|
|[[Ljava.lang.Obje...|
+--------------------+
</code>```

Even though I am passing the schema as ArrayType(StringType()), I am getting the Object reference as the output. But if I return only the tokens as output instead of the pos_tags from my _transform() method, I am getting the output correctly, that is, a list of tokens. Can anyone please let me know what am I missing or doing wrong? Any help is appreciated. My environment is Spark 1.6 and Python 2.7.

答:
Look at below example, pos_tag returns list(tuple(string)):

```<code>>>> text = word_tokenize("And now for something completely different")
>>> nltk.pos_tag(text)

[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'),
('completely', 'RB'), ('different', 'JJ')]
</code>```

So problem in your code looks here ArrayType(StringType()), So it should be ArrayType(ArrayType(StringType()))

###### Answer For Comment

```<code>import pyspark.sql.types as T
import pyspark.sql.functions as F
def flattenArray(obj):
    return reduce(lambda x,y:x+y, obj)

pos_output.select(F.udf(flattenArray, T.ArrayType(T.StringType()))("pos").alias("pos")).show(truncate = False)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written a custom transformer class POSWordTagger. My _transform() method code is,

def _transform(self, dataset):

    def f(s):
        tokens = nltk.tokenize.wordpunct_tokenize(s)
        pos_tags = nltk.pos_tag(tokens)
        return pos_tags

t = ArrayType(StringType())
out_col = self.getOutputCol()
in_col = dataset[self.getInputCol()]
return dataset.withColumn(out_col, udf(f, t)(in_col))

I am calling my transformer class as follows,

sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)

sentenceDataFrame = sqlContext.createDataFrame([
  (0, "Hi I heard about Spark"),
  (0, "I wish Java could use case classes"),
  (1, "Logistic regression models are neat")
  ], ["label", "sentence"])

pos_tagger = POSWordTagger(inputCol="sentence", outputCol="pos")

pos_output=pos_tagger.transform(sentenceDataFrame)
pos_output.select("pos").show()

I am getting the output as,

+--------------------+
|                 pos|
+--------------------+
|[[Ljava.lang.Obje...|
|[[Ljava.lang.Obje...|
|[[Ljava.lang.Obje...|
+--------------------+

Even though I am passing the schema as ArrayType(StringType()), I am getting the Object reference as the output. But if I return only the tokens as output instead of the pos_tags from my _transform() method, I am getting the output correctly, that is, a list of tokens. Can anyone please let me know what am I missing or doing wrong? Any help is appreciated. My environment is Spark 1.6 and Python 2.7.

Body:
Look at below example, pos_tag returns list(tuple(string)):

>>> text = word_tokenize("And now for something completely different")
>>> nltk.pos_tag(text)

[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'),
('completely', 'RB'), ('different', 'JJ')]

So problem in your code looks here ArrayType(StringType()), So it should be ArrayType(ArrayType(StringType()))

###### Answer For Comment

import pyspark.sql.types as T
import pyspark.sql.functions as F
def flattenArray(obj):
    return reduce(lambda x,y:x+y, obj)

pos_output.select(F.udf(flattenArray, T.ArrayType(T.StringType()))("pos").alias("pos")).show(truncate = False)


问:
How to change the class of elements that have matching content
I have:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
</code>```

And I would like all the elements that contain the same content as the one with a class of "bar" to also have a class of "bar" like so:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
<div class="foo">qux</div>
</code>```

But I can't just search for "baz" because that content is subject to change. Instead I have to figure out what's in the lone "bar" div then find the others that match it and change their class to "bar" too.

I've managed to get the content of the first "bar" element into a variable:

```<code>var = body.css(".bar").first.inner_text
</code>```

But nothing I've tried from there as far as finding the matching content and replacing the class has worked.

答:
You can use body.css('div:contains("<text-to-match>")') to match the nodes containing the text content you want.

You can achieve what you want by doing something like:

```<code>require 'nokogiri'

input = '<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>'

body = Nokogiri::HTML.fragment(input)

text_to_match = body.at_css('.bar').text

matching_nodes = body.css("div:contains('#{text_to_match}')")
matching_nodes.each do |node|
  node['class'] = 'bar'
end

puts body.to_html
</code>```

Body:
I have:

baz

qux

qux

baz

qux

baz

qux

And I would like all the elements that contain the same content as the one with a class of "bar" to also have a class of "bar" like so:

baz

qux

qux

baz

qux

baz

qux

But I can't just search for "baz" because that content is subject to change. Instead I have to figure out what's in the lone "bar" div then find the others that match it and change their class to "bar" too.

I've managed to get the content of the first "bar" element into a variable:

var = body.css(".bar").first.inner_text

But nothing I've tried from there as far as finding the matching content and replacing the class has worked.

Body:
You can use body.css('div:contains("<text-to-match>")') to match the nodes containing the text content you want.

You can achieve what you want by doing something like:

require 'nokogiri'

input = '<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>'

body = Nokogiri::HTML.fragment(input)

text_to_match = body.at_css('.bar').text

matching_nodes = body.css("div:contains('#{text_to_match}')")
matching_nodes.each do |node|
  node['class'] = 'bar'
end

puts body.to_html


问:
sigmoidal regression with scipy, numpy, python, etc
I have two variables (x and y) that have a somewhat sigmoidal relationship with each other, and I need to find some sort of prediction equation that will enable me to predict the value of y, given any value of x.  My prediction equation needs to show the somewhat sigmoidal relationship between the two variables.  Therefore, I cannot settle for a linear regression equation that produces a line.  I need to see the gradual, curvilinear change in slope that occurs at both the right and left of the graph of the two variables.

I started using numpy.polyfit after googling curvilinear regression and python, but that gave me the awful results you can see if you run the code below.  Can anyone show me how to re-write the code below to get the type of sigmoidal regression equation that I want?

If you run the code below, you can see that it gives a downward facing parabola, which is not what the relationship between my variables should look like.  Instead, there should be more of a sigmoidal relationship between my two variables, but with a tight fit with the data that I am using in the code below.  The data in the code below are means from a large-sample research study, so they pack more statistical power than their five data points might suggest.  I do not have the actual data from the large-sample research study, but I do have the means below and their standard deviations(which I am not showing).  I would prefer to just plot a simple function with the mean data listed below, but the code could get more complex if complexity would offer substantial improvements.

How can I change my code to show a best fit of a sigmoidal function, preferably using scipy, numpy, and python?  Here is the current version of my code, which needs to be fixed:

```<code>import numpy as np
import matplotlib.pyplot as plt

# Create numpy data arrays
x = np.array([821,576,473,377,326])
y = np.array([255,235,208,166,157])

# Use polyfit and poly1d to create the regression equation
z = np.polyfit(x, y, 3)
p = np.poly1d(z)
xp = np.linspace(100, 1600, 1500)
pxp=p(xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(140,310)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()
</code>```

EDIT BELOW: (Re-framed the question)

Your response, and its speed, are very impressive.  Thank you, unutbu.
But, in order to produce more valid results, I need to re-frame my data values.  This means re-casting x values as a percentage of the max x value, while re-casting y values as a percentage of the x-values in the original data.  I tried to do this with your code, and came up with the following:

```<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

# Create numpy data arrays
'''
# Comment out original data
#x = np.array([821,576,473,377,326])
#y = np.array([255,235,208,166,157])
'''

# Re-calculate x values as a percentage of the first (maximum)
# original x value above
x = np.array([1.000,0.702,0.576,0.459,0.397])

# Recalculate y values as a percentage of their respective x values
# from original data above
y = np.array([0.311,0.408,0.440,0.440,0.482])

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

p_guess=(600,200,100,0.01)
(p,
 cov,
 infodict,
 mesg,
 ier)=scipy.optimize.leastsq(residuals,p_guess,args=(x,y),full_output=1,warning=True)

'''
# comment out original xp to allow for better scaling of
# new values
#xp = np.linspace(100, 1600, 1500)
'''

xp = np.linspace(0, 1.1, 1100)
pxp=sigmoid(p,xp)

x0,y0,c,k=p
print('''\
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k))

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(0,1)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()
</code>```

Can you show me how to fix this revised code?

NOTE: By re-casting the data, I have essentially rotated the 2d (x,y) sigmoid about the z-axis by 180 degrees.  Also, the 1.000 is not really a maximum of the x values.  Instead, 1.000 is a mean of the range of values from different test participants in a maximum test condition.

SECOND EDIT BELOW:

Thank you, ubuntu.  I carefully read through your code and looked aspects of it up in the scipy documentation.  Since your name seems to pop up as a writer of the scipy documentation, I am hoping you can answer the following questions:

1.) Does leastsq() call residuals(), which then returns the difference between the input y-vector and the y-vector returned by the sigmoid() function?  If so, how does it account for the difference in the lengths of the input y-vector and the y-vector returned by the sigmoid() function?

2.) It looks like I can call leastsq() for any math equation, as long as I access that math equation through a residuals function, which in turn calls the math function.  Is this true?

3.) Also, I notice that p_guess has the same number of elements as p.  Does this mean that the four elements of p_guess correspond in order, respectively, with the values returned by x0,y0,c, and k?

4.) Is the p that is sent as an argument to the residuals() and sigmoid() functions the same p that will be output by leastsq(), and the leastsq() function is using that p internally before returning it?

5.) Can p and p_guess have any number of elements, depending on the complexity of the equation being used as a model, as long as the number of elements in p is equal to the number of elements in p_guess?

答:
Using scipy.optimize.leastsq:

```<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

def resize(arr,lower=0.0,upper=1.0):
    arr=arr.copy()
    if lower>upper: lower,upper=upper,lower
    arr -= arr.min()
    arr *= (upper-lower)/arr.max()
    arr += lower
    return arr

# raw data
x = np.array([821,576,473,377,326],dtype='float')
y = np.array([255,235,208,166,157],dtype='float')

x=resize(-x,lower=0.3)
y=resize(y,lower=0.3)
print(x)
print(y)
p_guess=(np.median(x),np.median(y),1.0,1.0)
p, cov, infodict, mesg, ier = scipy.optimize.leastsq(
    residuals,p_guess,args=(x,y),full_output=1,warning=True)

x0,y0,c,k=p
print('''\
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k))

xp = np.linspace(0, 1.1, 1500)
pxp=sigmoid(p,xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.xlabel('x')
plt.ylabel('y',rotation='horizontal')
plt.grid(True)
plt.show()
</code>```

yields

with sigmoid parameters

```<code>x0 = 0.826964424481
y0 = 0.151506745435
c = 0.848564826467
k = -9.54442292022
</code>```

Note that for newer versions of scipy (e.g. 0.9) there is also the scipy.optimize.curve_fit function which is easier to use than leastsq. A relevant discussion of fitting sigmoids using curve_fit can be found here.

Edit: A resize function was added so that the raw data could be rescaled and shifted to fit any desired bounding box.

"your name seems to pop up as a writer
  of the scipy documentation"

DISCLAIMER: I am not a writer of scipy documentation. I am just a user, and a novice at that. Much of what I know about leastsq comes from reading this tutorial, written by Travis Oliphant.

1.) Does leastsq() call residuals(), which then returns the difference
  between the input y-vector and the
  y-vector returned by the sigmoid()
  function?

Yes! exactly.

If so, how does it account for the
  difference in the lengths of the input
  y-vector and the y-vector returned by
  the sigmoid() function?

The lengths are the same:

```<code>In [138]: x
Out[138]: array([821, 576, 473, 377, 326])

In [139]: y
Out[139]: array([255, 235, 208, 166, 157])

In [140]: p=(600,200,100,0.01)

In [141]: sigmoid(p,x)
Out[141]:
array([ 290.11439268,  244.02863507,  221.92572521,  209.7088641 ,
        206.06539033])
</code>```

One of the wonderful things about Numpy is that it allows you to write "vector" equations that operate on entire arrays.

```<code>y = c / (1 + np.exp(-k*(x-x0))) + y0
</code>```

might look like it works on floats (indeed it would) but if you make x a numpy array, and c,k,x0,y0 floats, then the equation defines y to be a numpy array of the same shape as x. So sigmoid(p,x) returns a numpy array. There is a more complete explanation of how this works in the numpybook (required reading for serious users of numpy).

2.) It looks like I can call leastsq() for any math equation, as long as I
  access that math equation through a
  residuals function, which in turn
  calls the math function. Is this true?

True. leastsq attempts to minimize the sum of the squares of the residuals (differences). It searches the parameter-space (all possible values of p) looking for the p which minimizes that sum of squares. The x and y sent to residuals, are your raw data values. They are fixed. They don't change. It's the ps (the parameters in the sigmoid function) that leastsq tries to minimize.

3.) Also, I notice that p_guess has the same number of elements as p. Does
  this mean that the four elements of
  p_guess correspond in order,
  respectively, with the values returned
  by x0,y0,c, and k?

Exactly so! Like Newton's method, leastsq needs an initial guess for p. You supply it as p_guess. When you see

```<code>scipy.optimize.leastsq(residuals,p_guess,args=(x,y))
</code>```

you can think that as part of the leastsq algorithm (really the Levenburg-Marquardt algorithm) as a first pass, leastsq calls residuals(p_guess,x,y).
Notice the visual similarity between

```<code>(residuals,p_guess,args=(x,y))
</code>```

and

```<code>residuals(p_guess,x,y)
</code>```

It may help you remember the order and meaning of the arguments to leastsq.

residuals, like sigmoid returns a numpy array. The values in the array are squared, and then summed. This is the number to beat. p_guess is then varied as leastsq looks for a set of values which minimizes residuals(p_guess,x,y).

4.) Is the p that is sent as an argument to the residuals() and
  sigmoid() functions the same p that
  will be output by leastsq(), and the
  leastsq() function is using that p
  internally before returning it?

Well, not exactly. As you know by now, p_guess is varied as leastsq searches for the p value that minimizes residuals(p,x,y). The p (er, p_guess) that is sent to leastsq has the same shape as the p that is returned by leastsq. Obviously the values should be different unless you are a hell of a guesser :)

5.) Can p and p_guess have any number of elements, depending on the
  complexity of the equation being used
  as a model, as long as the number of
  elements in p is equal to the number
  of elements in p_guess?

Yes. I haven't stress-tested leastsq for very large numbers of parameters, but it is a thrillingly powerful tool.

Body:
I have two variables (x and y) that have a somewhat sigmoidal relationship with each other, and I need to find some sort of prediction equation that will enable me to predict the value of y, given any value of x.  My prediction equation needs to show the somewhat sigmoidal relationship between the two variables.  Therefore, I cannot settle for a linear regression equation that produces a line.  I need to see the gradual, curvilinear change in slope that occurs at both the right and left of the graph of the two variables.

I started using numpy.polyfit after googling curvilinear regression and python, but that gave me the awful results you can see if you run the code below.  Can anyone show me how to re-write the code below to get the type of sigmoidal regression equation that I want?

If you run the code below, you can see that it gives a downward facing parabola, which is not what the relationship between my variables should look like.  Instead, there should be more of a sigmoidal relationship between my two variables, but with a tight fit with the data that I am using in the code below.  The data in the code below are means from a large-sample research study, so they pack more statistical power than their five data points might suggest.  I do not have the actual data from the large-sample research study, but I do have the means below and their standard deviations(which I am not showing).  I would prefer to just plot a simple function with the mean data listed below, but the code could get more complex if complexity would offer substantial improvements.

How can I change my code to show a best fit of a sigmoidal function, preferably using scipy, numpy, and python?  Here is the current version of my code, which needs to be fixed:

import numpy as np
import matplotlib.pyplot as plt

# Create numpy data arrays
x = np.array([821,576,473,377,326])
y = np.array([255,235,208,166,157])

# Use polyfit and poly1d to create the regression equation
z = np.polyfit(x, y, 3)
p = np.poly1d(z)
xp = np.linspace(100, 1600, 1500)
pxp=p(xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(140,310)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

EDIT BELOW: (Re-framed the question)

Your response, and its speed, are very impressive.  Thank you, unutbu.
But, in order to produce more valid results, I need to re-frame my data values.  This means re-casting x values as a percentage of the max x value, while re-casting y values as a percentage of the x-values in the original data.  I tried to do this with your code, and came up with the following:

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

# Create numpy data arrays
'''
# Comment out original data
#x = np.array([821,576,473,377,326])
#y = np.array([255,235,208,166,157])
'''

# Re-calculate x values as a percentage of the first (maximum)
# original x value above
x = np.array([1.000,0.702,0.576,0.459,0.397])

# Recalculate y values as a percentage of their respective x values
# from original data above
y = np.array([0.311,0.408,0.440,0.440,0.482])

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

p_guess=(600,200,100,0.01)
(p,
 cov,
 infodict,
 mesg,
 ier)=scipy.optimize.leastsq(residuals,p_guess,args=(x,y),full_output=1,warning=True)

'''
# comment out original xp to allow for better scaling of
# new values
#xp = np.linspace(100, 1600, 1500)
'''

xp = np.linspace(0, 1.1, 1100)
pxp=sigmoid(p,xp)

x0,y0,c,k=p
print('''\
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k))

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(0,1)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

Can you show me how to fix this revised code?

NOTE: By re-casting the data, I have essentially rotated the 2d (x,y) sigmoid about the z-axis by 180 degrees.  Also, the 1.000 is not really a maximum of the x values.  Instead, 1.000 is a mean of the range of values from different test participants in a maximum test condition.

SECOND EDIT BELOW:

Thank you, ubuntu.  I carefully read through your code and looked aspects of it up in the scipy documentation.  Since your name seems to pop up as a writer of the scipy documentation, I am hoping you can answer the following questions:

1.) Does leastsq() call residuals(), which then returns the difference between the input y-vector and the y-vector returned by the sigmoid() function?  If so, how does it account for the difference in the lengths of the input y-vector and the y-vector returned by the sigmoid() function?

2.) It looks like I can call leastsq() for any math equation, as long as I access that math equation through a residuals function, which in turn calls the math function.  Is this true?

3.) Also, I notice that p_guess has the same number of elements as p.  Does this mean that the four elements of p_guess correspond in order, respectively, with the values returned by x0,y0,c, and k?

4.) Is the p that is sent as an argument to the residuals() and sigmoid() functions the same p that will be output by leastsq(), and the leastsq() function is using that p internally before returning it?

5.) Can p and p_guess have any number of elements, depending on the complexity of the equation being used as a model, as long as the number of elements in p is equal to the number of elements in p_guess?

Body:
Using scipy.optimize.leastsq:

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

def resize(arr,lower=0.0,upper=1.0):
    arr=arr.copy()
    if lower>upper: lower,upper=upper,lower
    arr -= arr.min()
    arr *= (upper-lower)/arr.max()
    arr += lower
    return arr

# raw data
x = np.array([821,576,473,377,326],dtype='float')
y = np.array([255,235,208,166,157],dtype='float')

x=resize(-x,lower=0.3)
y=resize(y,lower=0.3)
print(x)
print(y)
p_guess=(np.median(x),np.median(y),1.0,1.0)
p, cov, infodict, mesg, ier = scipy.optimize.leastsq(
    residuals,p_guess,args=(x,y),full_output=1,warning=True)

x0,y0,c,k=p
print('''\
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k))

xp = np.linspace(0, 1.1, 1500)
pxp=sigmoid(p,xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.xlabel('x')
plt.ylabel('y',rotation='horizontal')
plt.grid(True)
plt.show()

yields

with sigmoid parameters

x0 = 0.826964424481
y0 = 0.151506745435
c = 0.848564826467
k = -9.54442292022

Note that for newer versions of scipy (e.g. 0.9) there is also the scipy.optimize.curve_fit function which is easier to use than leastsq. A relevant discussion of fitting sigmoids using curve_fit can be found here.

Edit: A resize function was added so that the raw data could be rescaled and shifted to fit any desired bounding box.

"your name seems to pop up as a writer
  of the scipy documentation"

DISCLAIMER: I am not a writer of scipy documentation. I am just a user, and a novice at that. Much of what I know about leastsq comes from reading this tutorial, written by Travis Oliphant.

1.) Does leastsq() call residuals(), which then returns the difference
  between the input y-vector and the
  y-vector returned by the sigmoid()
  function?

Yes! exactly.

If so, how does it account for the
  difference in the lengths of the input
  y-vector and the y-vector returned by
  the sigmoid() function?

The lengths are the same:

In [138]: x
Out[138]: array([821, 576, 473, 377, 326])

In [139]: y
Out[139]: array([255, 235, 208, 166, 157])

In [140]: p=(600,200,100,0.01)

In [141]: sigmoid(p,x)
Out[141]:
array([ 290.11439268,  244.02863507,  221.92572521,  209.7088641 ,
        206.06539033])

One of the wonderful things about Numpy is that it allows you to write "vector" equations that operate on entire arrays.

y = c / (1 + np.exp(-k*(x-x0))) + y0

might look like it works on floats (indeed it would) but if you make x a numpy array, and c,k,x0,y0 floats, then the equation defines y to be a numpy array of the same shape as x. So sigmoid(p,x) returns a numpy array. There is a more complete explanation of how this works in the numpybook (required reading for serious users of numpy).

2.) It looks like I can call leastsq() for any math equation, as long as I
  access that math equation through a
  residuals function, which in turn
  calls the math function. Is this true?

True. leastsq attempts to minimize the sum of the squares of the residuals (differences). It searches the parameter-space (all possible values of p) looking for the p which minimizes that sum of squares. The x and y sent to residuals, are your raw data values. They are fixed. They don't change. It's the ps (the parameters in the sigmoid function) that leastsq tries to minimize.

3.) Also, I notice that p_guess has the same number of elements as p. Does
  this mean that the four elements of
  p_guess correspond in order,
  respectively, with the values returned
  by x0,y0,c, and k?

Exactly so! Like Newton's method, leastsq needs an initial guess for p. You supply it as p_guess. When you see

scipy.optimize.leastsq(residuals,p_guess,args=(x,y))

you can think that as part of the leastsq algorithm (really the Levenburg-Marquardt algorithm) as a first pass, leastsq calls residuals(p_guess,x,y).
Notice the visual similarity between

(residuals,p_guess,args=(x,y))

and

residuals(p_guess,x,y)

It may help you remember the order and meaning of the arguments to leastsq.

residuals, like sigmoid returns a numpy array. The values in the array are squared, and then summed. This is the number to beat. p_guess is then varied as leastsq looks for a set of values which minimizes residuals(p_guess,x,y).

4.) Is the p that is sent as an argument to the residuals() and
  sigmoid() functions the same p that
  will be output by leastsq(), and the
  leastsq() function is using that p
  internally before returning it?

Well, not exactly. As you know by now, p_guess is varied as leastsq searches for the p value that minimizes residuals(p,x,y). The p (er, p_guess) that is sent to leastsq has the same shape as the p that is returned by leastsq. Obviously the values should be different unless you are a hell of a guesser :)

5.) Can p and p_guess have any number of elements, depending on the
  complexity of the equation being used
  as a model, as long as the number of
  elements in p is equal to the number
  of elements in p_guess?

Yes. I haven't stress-tested leastsq for very large numbers of parameters, but it is a thrillingly powerful tool.


问:
MySql database doesn't submit the values of my form
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

```<code>   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

error_reporting(0);
ini_set('display_errors', 0)

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

    <div class="registaration-logo">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
        <img src="images/translogo.png" alt=" ">
            </div>
        </div>
    </div>

    <form class="form-registration" action="reg_db.php" method="post">
              <h2> Registration </h2>
        <div class="form-group-row">
            <label for="Name" class="col-2 col-form-label">Name</label>
            <div class="col-10">
                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name"> </div>
        </div>
        <div class="form-group-row">
            <label for="Surname" class="col-2 col-form-label">Surname</label>
            <div class="col-10">
                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname"> </div>
        </div>
        <div class="form-group-row">
            <label for="Email" class="col-2 col-form-label">Email</label>
            <div class="col-10">
                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Confirm Email" class="col-2 col-form-label"> Confirm Email</label>
            <div class="col-10">
                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Telephone" class="col-2 col-form-label">Telephone Number</label>
            <div class="col-10">
                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number"> </div>
        </div>
        <div class="form-group-row">
            <label for="ID_Number" class="col-2 col-form-label">ID Number</label>
            <div class="col-10">
                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number"> </div>
        </div>
        <div class="form-group-row">
            <div class="col-sm-10">
                    <a href="verify.html" class="btn btn-default1" role="button" type="submit">Submit</a>
            </div>
        </div>

        <div class="panel panel-default">
  <div class="panel-body">
    <h3> Disclaimer</h3>
      <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
  </div>
        </div>
 </form>

</body>

</html>

 VERIFY.HTML PAGE
    <!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

   <div class="verify">
  <div class="jumbotron">
    <h2>Thank You</h2>
    <p>We will send you your login information when you are verified.</p>
  </div>
       </div>
</body>

</html>
</code>```

答:
Could you check to see if the type of data stored in columns telephone and id_number is INT if so u should change the statement

```<code>$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";
</code>```

To

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)VALUES ('$Name','$Surname','$Email',$Telephone,$ID_Number)";

Also change the action attribute of form element to point to your page itself as the php code in the current page only

```<code><form class="form-registration" action="" method="post">
</code>```

Please include the details of the table so that we could get a better idea of the problem.

Body:
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

error_reporting(0);
ini_set('display_errors', 0)

?>

<!DOCTYPE html>

    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <link rel="stylesheet" href="css/font-awesome.min.css">

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

    <form class="form-registration" action="reg_db.php" method="post">

 Registration

            Name

                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name">

            Surname

                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname">

            Email

                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email">

             Confirm Email

                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email">

            Telephone Number

                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number">

            ID Number

                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number">

                    Submit

 Disclaimer

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

 </form>

 VERIFY.HTML PAGE
    <!DOCTYPE html>

    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <link rel="stylesheet" href="css/font-awesome.min.css">

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

Thank You

We will send you your login information when you are verified.

Body:
Could you check to see if the type of data stored in columns telephone and id_number is INT if so u should change the statement

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

To

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)VALUES ('$Name','$Surname','$Email',$Telephone,$ID_Number)";

Also change the action attribute of form element to point to your page itself as the php code in the current page only

<form class="form-registration" action="" method="post">

Please include the details of the table so that we could get a better idea of the problem.


问:
Code inside get not running after using express.static
This is my nodejs express setting:

```<code>var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('*', function (req, res) {
  res.sendfile('public/index.html')
});

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!');
});

module.exports = app;
</code>```

I found out that when it use:

app.use(express.static('public'));

Nothing runs inside this get:

app.get('*', function (req, res) {
          // nothing runs here
        res.sendfile('public/index.html')
      });

ps: I want to redirect (http -> https) inside that get.

答:
If you want to redirect all http requests to https, then insert an app.use() middleware as the first request handler with the redirect logic to https.  Express processes request handlers in the order you define them and you will want this middleware to be processed first before your express.static() middleware.

You will, of course, need to put all your other request handlers on an https server (not on the http server) so the https server can process your URLs after the redirect (something your code does not show).

Body:
This is my nodejs express setting:

var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('*', function (req, res) {
  res.sendfile('public/index.html')
});

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!');
});

module.exports = app;

I found out that when it use:

app.use(express.static('public'));

Nothing runs inside this get:

app.get('*', function (req, res) {
          // nothing runs here
        res.sendfile('public/index.html')
      });

ps: I want to redirect (http -> https) inside that get.


问:
Retrofit returns null response body when issuing a GET request
I am using retrofit to receive JSON data from my API. I am able to receive the JSON data when the data contains a single object. But when I try to a get list of all the employees I get an error.

JSON data for /api/Employee/1 is (working fine):

```<code>{
  "id": 10,
  "name": "Arpit",
  "number": "7777777777",
  "city": "noida",
  "depid": 4,
}
</code>```

Code to get this JSON object is working. PFB the code.

Retrofit Code:

```<code>public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Employee e = new Employee();
        e.setId(response.body().id);
        e.setName(response.body().name);
        e.setCity(response.body().city);
        e.setNumber(response.body().number);
        Log.d("employee details", e.toString());
        list.add(e);
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());}
</code>```

EmployeeAPI.java

```<code>public interface EmployeeAPI {
@GET("/assignment1/api/Employee/1")
Call<EmployeeResponse> load_employee();}
</code>```

EmployeeResponse.java

```<code>public class EmployeeResponse {
@SerializedName("id")
public String id;
@SerializedName("name")
public String name;
@SerializedName("city")
public String city;
@SerializedName("number")
public String number;}
</code>```

But when I am trying to get the list of all Employees from /api/Employee I get the following error:

```<code>java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
</code>```

JSON data for api/Employee is ():

```<code>[
   {
  "id":10,
  "name":"Arpit Jain",
  "number":"7777777777",
  "city":"noida",
  "depid":4,
   },
   {
  "id":32,
  "name":"Ish Chawla",
  "number":"9999999999",
  "city":"Noida",
  "depid":1,
   },
   {
  "id":39,
  "name":"Laxman",
  "number":"6666666666",
  "city":"GZB",
  "depid":1,
   },
   {
  "id":44,
  "name":"Ishan",
  "number":"9839060055",
  "city":"Kanpur",
  "depid":3,
   }
]
</code>```

Code to get the list of employees is:

Retrofit Code

```<code>public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Log.d("employee details", response.body().toString());
        list = response.body().list;
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());
}
</code>```

EmployeeAPI.java

```<code> public interface EmployeeAPI {
    @GET("/assignment1/api/Employee")
    Call<EmployeeResponse> load_employee();
}
</code>```

EmployeeResponse.java

```<code>   public class EmployeeResponse {
    public ArrayList<Employee> list;
}
</code>```

Kindly tell me the changes required to get the data correctly.

答:
You need to change little in code:

1)EmployeeResponse.java

```<code>public class EmployeeResponse {
    public List<Employee> list;

      public List<Employee> getDatas() {
        return datas;
    }
  }
</code>```

2) Employee.java

```<code>  public class Employee{
       @SerializedName("id")
       public String id;
       @SerializedName("name")
       public String name;
       @SerializedName("city")
       public String city;
       @SerializedName("number")
       public String number;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    }
</code>```

3) In Interface:

```<code>public interface EmployeeAPI {
  @GET("/assignment1/api/Employee")
  Call<EmployeeResponse> load_employee();
}
</code>```

4) Retrofit Code

```<code> private void getEmployee() {
List<Employee> employee;
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        EmployeeAPI apiInterface = retrofit.create(EmployeeAPI.class);
        Call<EmployeeResponse> call = apiInterface.load_employee();
        call.enqueue(new Callback<EmployeeResponse>() {
            @Override
            public void onResponse(Call<EmployeeResponse> call, Response<EmployeeResponse> response) {
       employee = response.body().getDatas();
            }
            @Override
            public void onFailure(Call<EmployeeResponse> call, Throwable t) {
                Log.e(TAG, "onFailure:" + t.getMessage());
            }
        });
    }
</code>```

Body:
I am using retrofit to receive JSON data from my API. I am able to receive the JSON data when the data contains a single object. But when I try to a get list of all the employees I get an error.

JSON data for /api/Employee/1 is (working fine):

{
  "id": 10,
  "name": "Arpit",
  "number": "7777777777",
  "city": "noida",
  "depid": 4,
}

Code to get this JSON object is working. PFB the code.

Retrofit Code:

public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Employee e = new Employee();
        e.setId(response.body().id);
        e.setName(response.body().name);
        e.setCity(response.body().city);
        e.setNumber(response.body().number);
        Log.d("employee details", e.toString());
        list.add(e);
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());}

EmployeeAPI.java

public interface EmployeeAPI {
@GET("/assignment1/api/Employee/1")
Call<EmployeeResponse> load_employee();}

EmployeeResponse.java

public class EmployeeResponse {
@SerializedName("id")
public String id;
@SerializedName("name")
public String name;
@SerializedName("city")
public String city;
@SerializedName("number")
public String number;}

But when I am trying to get the list of all Employees from /api/Employee I get the following error:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

JSON data for api/Employee is ():

[
   {
  "id":10,
  "name":"Arpit Jain",
  "number":"7777777777",
  "city":"noida",
  "depid":4,
   },
   {
  "id":32,
  "name":"Ish Chawla",
  "number":"9999999999",
  "city":"Noida",
  "depid":1,
   },
   {
  "id":39,
  "name":"Laxman",
  "number":"6666666666",
  "city":"GZB",
  "depid":1,
   },
   {
  "id":44,
  "name":"Ishan",
  "number":"9839060055",
  "city":"Kanpur",
  "depid":3,
   }
]

Code to get the list of employees is:

Retrofit Code

public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Log.d("employee details", response.body().toString());
        list = response.body().list;
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());
}

EmployeeAPI.java

 public interface EmployeeAPI {
    @GET("/assignment1/api/Employee")
    Call<EmployeeResponse> load_employee();
}

EmployeeResponse.java

   public class EmployeeResponse {
    public ArrayList<Employee> list;
}

Kindly tell me the changes required to get the data correctly.

Body:
You need to change little in code:

1)EmployeeResponse.java

public class EmployeeResponse {
    public List<Employee> list;

      public List<Employee> getDatas() {
        return datas;
    }
  }

2) Employee.java

  public class Employee{
       @SerializedName("id")
       public String id;
       @SerializedName("name")
       public String name;
       @SerializedName("city")
       public String city;
       @SerializedName("number")
       public String number;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    }

3) In Interface:

public interface EmployeeAPI {
  @GET("/assignment1/api/Employee")
  Call<EmployeeResponse> load_employee();
}

4) Retrofit Code

 private void getEmployee() {
List<Employee> employee;
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        EmployeeAPI apiInterface = retrofit.create(EmployeeAPI.class);
        Call<EmployeeResponse> call = apiInterface.load_employee();
        call.enqueue(new Callback<EmployeeResponse>() {
            @Override
            public void onResponse(Call<EmployeeResponse> call, Response<EmployeeResponse> response) {
       employee = response.body().getDatas();
            }
            @Override
            public void onFailure(Call<EmployeeResponse> call, Throwable t) {
                Log.e(TAG, "onFailure:" + t.getMessage());
            }
        });
    }


问:
IdentityServer4 and using multiple scopes
I'd like to define 2 different scopes for my API resource with IdentityServer4, similar to this: https://identityserver4.readthedocs.io/en/release/configuration/resources.html#defining-api-resources. There is 1 endpoint I want my client application to hit without requiring the user to login, and the rest of the endpoints would be fully protected with user interaction (hybrid flow fwiw).

I think I could get it working so either flow provides access to the API. What I'm confused about is with the configuration demonstrated above how do I limit the client credentials flow to only a limited scope? I don't want that flow to be able to hit the full extent of the API. Only once a user logs in would they get access to the rest...a different "scope" of the API...

This is for a native/mobile application, so the client secret for the client credentials will be embedded in the application. That is why the rest of the API needs to have better protection. But with the IdentityServer4 configured to allow both grant types for the resource wouldn't someone be able to discover that client secret and use it outside of the native application to gain access to the rest of the API anyway? How to limit that grant type to the more constrained scope...?

答: You will need two different clients each with their own configuration to your resources (using scopes). The sub claim can be seen as user identifier claim, and thus has no place in the client credentials flow since it is a flow that is user-less.</p>


问:
BufferedOutputStream not throwing I/O exception
While working on BufferedOutputStream found it does not throw an IOException when we wrote on it after closing the stream.

To verify my result, i checked FileOutputStream found it is throwing IOException once we try to write on it after closing it.

```<code>public class Test {
    public static void main(String[] args) {
        try {
            // Created a byte[] barry1 barry2
            byte[] barry1 = { '1', '3' };
            byte[] barray2 = { '2', '4' };
            OutputStream os = new BufferedOutputStream(
                  new FileOutputStream("abc.txt", false));
            // Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // this suceeds - bug

            os = new FileOutputStream("abc.txt", true);
             //Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // crashes here, correct.
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Could some one help me on this, Why this behavior is different ?

答:
While working on BufferedOutputStream found it does not throw an IOException when we wrote on it after closing the stream.

The BufferedOutputStream code just doesn't have that sort of checking – but then neither does the FileOutputStream.  In both cases, only when the IO is actually written to disk does the OS "throw" the IOException.  It is not the Java code which is detecting that the stream has been closed.  As an aside, this probably means that some native implementations don't throw at all.

The reason why the FileOutputStream is throwing the exception on os.write(...), versus the BufferedOutputStream, is that it is writing the IO to the underlying native layer immediately.  If you add a os.flush() call to the BufferedOutputStream after the os.write() then you will see the same exception because that forces its internal buffer to be written out.

```<code>OutputStream os = new BufferedOutputStream(new FileOutputStream("abc.txt", false));
os.write(barry1);
os.close();
os.write(barray2); // this suceeds – unfortunate behavior
os.flush();  // adding this line throws an IOException
</code>```

In looking at the BufferedOutputStream's close() method (actually in the FilterOutputStream base class), you can see that the output stream is not set to null or anything:

```<code>public void close() throws IOException {
    try {
      flush();
    } catch (IOException ignored) {
    }
    out.close();
}
</code>```

I also don't like the fact that it is ignoring IOExceptions on close here.  Wow.  This tells me that we should always call flush() by hand before close() which is a pattern I specifically don't do.

Now compare that code to the BufferedWriter.close():

```<code>public void close() throws IOException {
    synchronized (lock) {
        if (out == null) {
            return;
        }
        try {
            flushBuffer();
        } finally {
            out.close();
            out = null;   // good doggie
            cb = null;
        }
    }
}
</code>```

BufferedWriter.close() doesn't eat the exception and sets the delegated Writer to be null.  Much better IMO.

Body:
While working on BufferedOutputStream found it does not throw an IOException when we wrote on it after closing the stream.

To verify my result, i checked FileOutputStream found it is throwing IOException once we try to write on it after closing it.

public class Test {
    public static void main(String[] args) {
        try {
            // Created a byte[] barry1 barry2
            byte[] barry1 = { '1', '3' };
            byte[] barray2 = { '2', '4' };
            OutputStream os = new BufferedOutputStream(
                  new FileOutputStream("abc.txt", false));
            // Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // this suceeds - bug

            os = new FileOutputStream("abc.txt", true);
             //Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // crashes here, correct.
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Could some one help me on this, Why this behavior is different ?

Body:
While working on BufferedOutputStream found it does not throw an IOException when we wrote on it after closing the stream.

The BufferedOutputStream code just doesn't have that sort of checking – but then neither does the FileOutputStream.  In both cases, only when the IO is actually written to disk does the OS "throw" the IOException.  It is not the Java code which is detecting that the stream has been closed.  As an aside, this probably means that some native implementations don't throw at all.

The reason why the FileOutputStream is throwing the exception on os.write(...), versus the BufferedOutputStream, is that it is writing the IO to the underlying native layer immediately.  If you add a os.flush() call to the BufferedOutputStream after the os.write() then you will see the same exception because that forces its internal buffer to be written out.

OutputStream os = new BufferedOutputStream(new FileOutputStream("abc.txt", false));
os.write(barry1);
os.close();
os.write(barray2); // this suceeds – unfortunate behavior
os.flush();  // adding this line throws an IOException

In looking at the BufferedOutputStream's close() method (actually in the FilterOutputStream base class), you can see that the output stream is not set to null or anything:

public void close() throws IOException {
    try {
      flush();
    } catch (IOException ignored) {
    }
    out.close();
}

I also don't like the fact that it is ignoring IOExceptions on close here.  Wow.  This tells me that we should always call flush() by hand before close() which is a pattern I specifically don't do.

Now compare that code to the BufferedWriter.close():

public void close() throws IOException {
    synchronized (lock) {
        if (out == null) {
            return;
        }
        try {
            flushBuffer();
        } finally {
            out.close();
            out = null;   // good doggie
            cb = null;
        }
    }
}

BufferedWriter.close() doesn't eat the exception and sets the delegated Writer to be null.  Much better IMO.


问:
Windows Phone private application deployment
I'm developing a Windows Phone application for Windows 8.1 and Windows 10 phones. The application is for internal usage only and is communicating with our system. It needs to be private so I don't want to upload it to the Store. I tried uploading it as a hidden app so that only people with link would be able to download it, but Microsoft rejected my submission since I did not provide a test account to our production server or app screenshots. I can provide them with screenshots, but I cannot give them credentials to the system.

I'm having a hard time understanding a thought process behind deploying such an application. We have around 30 employees so I think creating Company Hub for one app is a total overkill, so is using Intune.

This is super small application, but fortunately my employers are willing to spend $99 on company dev account and $299 on the certificate but what next? I tried just uploading a .appx file on http server as a test and trying to install it by navigating the phone to the URL but it saw it as a zip file and wants to extract it instead of installing.

Microsoft documentation is split among many pages, and more often than not they are 404 - not found.

My question is: when I'll finally obtain a company dev account and a certificate how can I deploy my signed application? Any help or point to good tutorial would be much appreciated.

答:
when I'll finally obtain a company dev account and a certificate how can I deploy my signed application?

Since you have obtained the Symantec Certificate,

you need to import the certificates

verify the certificates imported correctly

export the .pfx file to sign the company portal

finally, you can upload the app package and your code-signing certificate to Intune.

For detailed steps, see Sign line-of-business apps so they can be deployed to Windows devices with Intune.

Then, you can refer to this Example: Download, sign, and deploy the Company Portal app for Windows devices to complete your deploying job.


问:
Pushing Python introspection to limits
Simple question – can I print the source code of this if?

```<code>if __name__ == '__main__':
  # ...
  # this is the `if` I want to print
  #  V
  if args and args[0][0] == '-':
    if args[0] in ('--help','-h','-?'):
      print_source_of_block(level=2)
    icase = 'i' in args[0]
    desc = 'd' in args[0]
    args = args[1:]
</code>```

Please don't ask me why I need it, nor give me advice on how to write user help. I want to know it because I'm curious.

答:
Yeah, that's doable. Here's a quick sketch of how you could do it and what tools would be involved:

Retrieve the stack frame of print_source_of_block's caller with inspect.currentframe().f_back.

Determine the caller's source file and line number within that source file with inspect.getframeinfo.

Open the source file.

Either

Use ast.parse to parse the file, or

Use tokenize.tokenize to tokenize it.

Using either the abstract syntax tree or the token stream, determine where the requested source block begins and ends.

Print the block.

Title: Pushing Python introspection to limits

Body:
Simple question – can I print the source code of this if?

if __name__ == '__main__':
  # ...
  # this is the `if` I want to print
  #  V
  if args and args[0][0] == '-':
    if args[0] in ('--help','-h','-?'):
      print_source_of_block(level=2)
    icase = 'i' in args[0]
    desc = 'd' in args[0]
    args = args[1:]

Please don't ask me why I need it, nor give me advice on how to write user help. I want to know it because I'm curious.


答:
If you want all the contents between "====" to be stored in the given file, this will work. I have tested it on my system as well. Good luck!

```<code>awk '/dell/{flag=1;next}/=/{flag=0}flag' <filename> > dell1-node4.lvs.local
</code>```

/dell/ matches lines having this text, as well as /=/ does.

/dell/{flag=1;next} sets the flag when the text dell is found.
Then, it skips the line.

/=/{flag=0} unsets the flag when the text = is found.

The final flag is a pattern with the default action, which is to
print $0: if flag is equal 1 the line is printed.

Title: Split data between empty row

Body:
===================================
dell1-node1.lvs.local

Device: t10.ATA_____DENCSTE251M252D0115______________________A09AY011202000268000000
VSANUUID: 5229819d-8308-e6a3-fea1-0716a6432ecd
SSD: True
Capacity: 79830188032
CapacityUsed: 0
DiskHealh: OK

Device: t10.ATA_____ST1000VX0012D1HH162__________________________________S513WZVV
VSANUUID: 526b1573-6e2e-111e-9748-a67d18a0093f
SSD: False
Capacity: 990191288320
CapacityUsed: 526032830464
DiskHealh: OK

===================================
dell1-node4.lvs.local

Device: t10.ATA_____ST2000VX0032D1HH164__________________________________W7208JYX
VSANUUID: 52219120-9951-3037-a871-11571eccf50e
SSD: False
Capacity: 1980382576640
CapacityUsed: 1337030868992
DiskHealh: OK

Device: t10.ATA_____DENCSTE251M252D0115______________________A09AY011210000027000000
VSANUUID: 52252706-4dcb-c73c-19f5-67719c29d0f6
SSD: True
Capacity: 79830188032
CapacityUsed: 0
DiskHealh: OK

===================================
dell1-node3.lvs.local

Device: naa.5000c5008c23ab53
VSANUUID: 5213b511-11b8-5f64-cb03-5a2d6ad258fa
SSD: False
Capacity: 990191288320
CapacityUsed: 682308403200
DiskHealh: OK

Device: naa.5000c5008c23ac7a
VSANUUID: 5236dc9a-b087-c2d8-2d24-2433218f3352
SSD: False
Capacity: 990191288320
CapacityUsed: 652595953664
DiskHealh: OK

Device: naa.5e83a97010008946
VSANUUID: 52f99ae4-970c-7369-de9d-7b93f0d9b5df
SSD: True
Capacity: 79830188032
CapacityUsed: 0
DiskHealh: OK

Hi all, I need to copy this string to a file:
dell1-node4.lvs.local

Device: t10.ATA_____ST2000VX0032D1HH164__________________________________W7208JYX
VSANUUID: 52219120-9951-3037-a871-11571eccf50e
SSD: False
Capacity: 1980382576640
CapacityUsed: 1337030868992
DiskHealh: OK

Device: t10.ATA_____DENCSTE251M252D0115______________________A09AY011210000027000000
VSANUUID: 52252706-4dcb-c73c-19f5-67719c29d0f6
SSD: True
Capacity: 79830188032
CapacityUsed: 0
DiskHealh: OK

And then continue copy this string to another file:

t10.ATA_____DENCSTE251M252D0115______________________A09AY011210000027000000
VSANUUID: 52252706-4dcb-c73c-19f5-67719c29d0f6
SSD: True
Capacity: 79830188032
CapacityUsed: 0
DiskHealh: OK

Body:
If you want all the contents between "====" to be stored in the given file, this will work. I have tested it on my system as well. Good luck!

awk '/dell/{flag=1;next}/=/{flag=0}flag' <filename> > dell1-node4.lvs.local

/dell/ matches lines having this text, as well as /=/ does.

/dell/{flag=1;next} sets the flag when the text dell is found.
Then, it skips the line.

/=/{flag=0} unsets the flag when the text = is found.

The final flag is a pattern with the default action, which is to
print $0: if flag is equal 1 the line is printed.


问:
Is there a way to specify in Java docs that a method should be called from a non-UI thread
I was writing a set of functions for accessing/writing data to the SQLite database in my android application. Since I need to use getWritableDatabase() to get the database instance and this needs to be called in a non-UI thread, I was wondering if there a clean way to specify the same warning in the java docs of these functions?

Also, I needed one more clarification about getting handle over the database instance using getWritableDatabase(). I should call this wherever I need to write things into database right? Or can I call this once at the application level and use the same handle to access db at different places in the app?

答:
There are no fixed rules for such things. You can only rely on conventions/style.

In other words: try to come up with explicit, unambiguous wording and make sure that this part is easy to read and quick to spot in your javadoc (check the generated HTML as well for these properties).

And then be prepared for bug reports from people ignoring your javadoc.


问:
How can I use progress bar while fetching data from server database located in web in c# winforms?
After login process I want to load form1 with mdi.

In the Pageload event of the Form1 load database table data from web using JSon and saved to the local database.

Form1 pageload take lots of time.

When I execute my application the mdi form load first and after some time form1 is loaded.

I want to resolve this issue. This is my pageload event code.
Here get data from web and saved to the local database.
Then set the data to the controls in form1.

```<code>private void Form1_Load(object sender, EventArgs e)
{
  string strUrlService = "http://.............................";
  string strUrlBranch = "http://......................";
  string strUrlOrigin = "http://.....";
  string strUrlEmployee = "http://.......";

  .............................
  GetServiceType(strUrlService);
  GetBranch(strUrlBranch);
  GetOrigin(strUrlOrigin);
  GetEmployee(strUrlEmployee);
  .............................

  SetServiceType();
  SetBranch();
  SetOrigin();
  SetEmployee();
  ......................

}
</code>```

GetServiceType method definition. Using Json object get value from web. And saved this data to the local database.
//---------Get ServiceType from web database-------------

```<code>private void GetServiceType(string strUrl)
{
  ServiceType obj = new ServiceType();
  HttpClient client = new HttpClient();
  client.BaseAddress = new Uri(strUrl);
  client.DefaultRequestHeaders.Accept.Clear();
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  HttpResponseMessage response = client.GetAsync(strUrl).Result;
  if (response.IsSuccessStatusCode)
  {
    var JsonResult = response.Content.ReadAsStringAsync().Result;
    System.Web.Script.Serialization.JavaScriptSerializer tmp = new System.Web.Script.Serialization.JavaScriptSerializer();
    obj = (ServiceType)tmp.Deserialize(JsonResult, typeof(ServiceType));
  }
  if (obj != null)
  {
    int count = obj.products.Count;
    int[] TxtID = new int[count];
    ..............................
    for (int i = 0; i < count; i++)
    {
      TxtID[i] = Convert.ToInt32(obj.products[i].id.ToString());
      ...............................
    }
    FunSaveServiceType(TxtID, txtService, txtCode, intDays);
  }
}
</code>```

In SetServiceType() method retrieve data(which is fetched from web and saved to local database) from local database. And this data is set to the combo box in the form1.

```<code>//--------------set service type to Form1 combobox control-----------------
private void SetServiceType()
{
  DataTable dtService = new DataTable();
  dtService = GetServiceTypeFromDB();
  DataRow dr = dtService.NewRow();
  dr["ServiceType"] = "";
  dtService.Rows.InsertAt(dr, 0);
  cbServiceType.DataSource = dtService;
}
</code>```

These are the process done before the form1 pageload event. These codes are working properly.

I am tried to set a progressbar and background worker in my mdi form. But it is not working properly.

答:
If you are using .Net 4.5 you won't longer need a background-worker. You can use the new TPL (Task Parallel Library). What you need at first is a progressbar which you can show in a different form. You could also use your mainform for showing progress, but you should use the Form1.Shown Event than. This is fired if your form is up and running and your gui-components are loaded properly.

You can implement the progress logic in the Shown-Event as following:

```<code>private async void Form1_Shown(object sender, EventArgs e)
{
   var progressHandler = new Progress<string>(value =>
   {
      //What to do if a Progress is reported?
      //For example set progressbar and labeltext
      progressBar.Step();
      label1.Text = value; //Value stores the string you send via Report (see at bottom method)
   });

   await InitializeServicesAsync(progressHandler as IProgress<string>);
}

private async Task InitializeServicesAsync(IProgress<string> progress)
{
  await Task.Run(() =>
  {
    string strUrlService = "http://.............................";
    string strUrlBranch = "http://......................";
    string strUrlOrigin = "http://.....";
    string strUrlEmployee = "http://.......";

    GetServiceType(strUrlService);
    progress.Report("Getting Servicetypes done");

    GetBranch(strUrlBranch);
    progress.Report("Getting Branch done");

    GetOrigin(strUrlOrigin);
    progress.Report("Getting Origin done");

    GetEmployee(strUrlEmployee);
    progress.Report("Getting Employee done");

    SetServiceType();
    progress.Report("Setting ServiceType done");

    SetBranch();
    //Report further progress as often as you need

    SetOrigin();
    SetEmployee();
  });
}
</code>```

Check out this blogpost to learn more.

Body:
After login process I want to load form1 with mdi.

In the Pageload event of the Form1 load database table data from web using JSon and saved to the local database.

Form1 pageload take lots of time.

When I execute my application the mdi form load first and after some time form1 is loaded.

I want to resolve this issue. This is my pageload event code.
Here get data from web and saved to the local database.
Then set the data to the controls in form1.

private void Form1_Load(object sender, EventArgs e)
{
  string strUrlService = "http://.............................";
  string strUrlBranch = "http://......................";
  string strUrlOrigin = "http://.....";
  string strUrlEmployee = "http://.......";

  .............................
  GetServiceType(strUrlService);
  GetBranch(strUrlBranch);
  GetOrigin(strUrlOrigin);
  GetEmployee(strUrlEmployee);
  .............................

  SetServiceType();
  SetBranch();
  SetOrigin();
  SetEmployee();
  ......................

}

GetServiceType method definition. Using Json object get value from web. And saved this data to the local database.
//---------Get ServiceType from web database-------------

private void GetServiceType(string strUrl)
{
  ServiceType obj = new ServiceType();
  HttpClient client = new HttpClient();
  client.BaseAddress = new Uri(strUrl);
  client.DefaultRequestHeaders.Accept.Clear();
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  HttpResponseMessage response = client.GetAsync(strUrl).Result;
  if (response.IsSuccessStatusCode)
  {
    var JsonResult = response.Content.ReadAsStringAsync().Result;
    System.Web.Script.Serialization.JavaScriptSerializer tmp = new System.Web.Script.Serialization.JavaScriptSerializer();
    obj = (ServiceType)tmp.Deserialize(JsonResult, typeof(ServiceType));
  }
  if (obj != null)
  {
    int count = obj.products.Count;
    int[] TxtID = new int[count];
    ..............................
    for (int i = 0; i < count; i++)
    {
      TxtID[i] = Convert.ToInt32(obj.products[i].id.ToString());
      ...............................
    }
    FunSaveServiceType(TxtID, txtService, txtCode, intDays);
  }
}

In SetServiceType() method retrieve data(which is fetched from web and saved to local database) from local database. And this data is set to the combo box in the form1.

//--------------set service type to Form1 combobox control-----------------
private void SetServiceType()
{
  DataTable dtService = new DataTable();
  dtService = GetServiceTypeFromDB();
  DataRow dr = dtService.NewRow();
  dr["ServiceType"] = "";
  dtService.Rows.InsertAt(dr, 0);
  cbServiceType.DataSource = dtService;
}

These are the process done before the form1 pageload event. These codes are working properly.

I am tried to set a progressbar and background worker in my mdi form. But it is not working properly.

Body:
If you are using .Net 4.5 you won't longer need a background-worker. You can use the new TPL (Task Parallel Library). What you need at first is a progressbar which you can show in a different form. You could also use your mainform for showing progress, but you should use the Form1.Shown Event than. This is fired if your form is up and running and your gui-components are loaded properly.

You can implement the progress logic in the Shown-Event as following:

private async void Form1_Shown(object sender, EventArgs e)
{
   var progressHandler = new Progress<string>(value =>
   {
      //What to do if a Progress is reported?
      //For example set progressbar and labeltext
      progressBar.Step();
      label1.Text = value; //Value stores the string you send via Report (see at bottom method)
   });

   await InitializeServicesAsync(progressHandler as IProgress<string>);
}

private async Task InitializeServicesAsync(IProgress<string> progress)
{
  await Task.Run(() =>
  {
    string strUrlService = "http://.............................";
    string strUrlBranch = "http://......................";
    string strUrlOrigin = "http://.....";
    string strUrlEmployee = "http://.......";

    GetServiceType(strUrlService);
    progress.Report("Getting Servicetypes done");

    GetBranch(strUrlBranch);
    progress.Report("Getting Branch done");

    GetOrigin(strUrlOrigin);
    progress.Report("Getting Origin done");

    GetEmployee(strUrlEmployee);
    progress.Report("Getting Employee done");

    SetServiceType();
    progress.Report("Setting ServiceType done");

    SetBranch();
    //Report further progress as often as you need

    SetOrigin();
    SetEmployee();
  });
}

Check out this blogpost to learn more.


问:
converting a string into a double
I am looking for a way to get floating point input from a user.

My way of going about this is to use a self-made getstrn function and plug that into another function which would convert the string into a double.

My safe get string:

```<code>void safeGetString(char arr[], int limit){
    int c, i;
    i = 0;
    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}
</code>```

What would be the best way to write this get_double function?

答:
Try the strtod function:

```<code>char *end;
double num = strtod(arr, &end);
</code>```

The end will point after the last char that was processed. You can set the second to NULL if you don't care about that. Or you can use atof: atof(str) is equivalent to strtod(str, (char **)NULL).

But you should care, since you can check if the input is malformed:

```<code>if (*end != '\0')
  // Handle malformed input
</code>```

Title: converting a string into a double

Body:
I am looking for a way to get floating point input from a user.

My way of going about this is to use a self-made getstrn function and plug that into another function which would convert the string into a double.

My safe get string:

void safeGetString(char arr[], int limit){
    int c, i;
    i = 0;
    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}

What would be the best way to write this get_double function?

Body:
Try the strtod function:

char *end;
double num = strtod(arr, &end);

The end will point after the last char that was processed. You can set the second to NULL if you don't care about that. Or you can use atof: atof(str) is equivalent to strtod(str, (char **)NULL).

But you should care, since you can check if the input is malformed:

if (*end != '\0')
  // Handle malformed input


问:
Retrieve file from database using python
I have a column FileContent (datatype image) in the database which store pdf, zip and docx file.

The FileContent column has the following value in database: 0x2550444...

I read the SQL table into DF using python and the values in column FileContent contains weird text instead of the 0x2550444... :

%PDF-1.7\n\n4 0 obj\n(Identity)\nendobj\n5 0 obj(Adobe)endobj8 0 obj> stream xœì½x\ÅÕ7>sïÝÞ«¶hµ»ZíJòªKV³,Õb[’eK²eKVqaÝmlÜ0ÍÑƒ˜NB Á$ÙÆ¢›¼¦…’˜4JpH€ " éæÎcxóþŸïý¾G#Ÿ=¿™;3wæÌ™3gæÞ]#Œ²Ã‡€:Ê›fWÕþ°ã ’ý~+Bž£¥åó_{óÒÕ¿™€õ®ŠÒº²‹U3Â¯ý!E¤ª¼¢rÁ«|ˆ{w!..................................

Is there a way to retrieve the file or convert the text above into a file (e.g. PDF) using python?

Will appreciate your input. Thank you.

My ultimate goal is to:
- retrieve the file from the column FileContent and extract the text within the files later on.

Code:

```<code>import pymssql
conn = pymssql.connect(server="",user="",password="",database="")
stmt = "SELECT FileContent FROM [tablename]"
df = pd.read_sql(stmt,conn)
df.head()
print(df)
</code>```

答:
Everything is fine. What you see is different representations of the same content.

0x255044... is the hexadecimal representation of the first bytes. If you look up in an ASCII table,

0x25 = '%'

0x50 = 'P'

0x44 = 'D'

and so on. The other text is what the .pdf looks like in a text editor. The garbled mess after "stream" is zip-compressed content within the pdf.

Just write out the whole stream into a .pdf file (use binary mode!) and try to open in Acrobat Reader.

```<code>with open('temp.pdf', 'wb') as outfile:
    outfile.write(pdf_content_from_database)
</code>```

should do.

Body:
I have a column FileContent (datatype image) in the database which store pdf, zip and docx file.

The FileContent column has the following value in database: 0x2550444...

I read the SQL table into DF using python and the values in column FileContent contains weird text instead of the 0x2550444... :

%PDF-1.7\n\n4 0 obj\n(Identity)\nendobj\n5 0 obj(Adobe)endobj8 0 obj> stream xœì½x\ÅÕ7>sïÝÞ«¶hµ»ZíJòªKV³,Õb[’eK²eKVqaÝmlÜ0ÍÑƒ˜NB Á$ÙÆ¢›¼¦…’˜4JpH€ " éæÎcxóþŸïý¾G#Ÿ=¿™;3wæÌ™3gæÞ]#Œ²Ã‡€:Ê›fWÕþ°ã ’ý~+Bž£¥åó_{óÒÕ¿™€õ®ŠÒº²‹U3Â¯ý!E¤ª¼¢rÁ«|ˆ{w!..................................

Is there a way to retrieve the file or convert the text above into a file (e.g. PDF) using python?

Will appreciate your input. Thank you.

My ultimate goal is to:
- retrieve the file from the column FileContent and extract the text within the files later on.

Code:

import pymssql
conn = pymssql.connect(server="",user="",password="",database="")
stmt = "SELECT FileContent FROM [tablename]"
df = pd.read_sql(stmt,conn)
df.head()
print(df)

Body:
Everything is fine. What you see is different representations of the same content.

0x255044... is the hexadecimal representation of the first bytes. If you look up in an ASCII table,

0x25 = '%'

0x50 = 'P'

0x44 = 'D'

and so on. The other text is what the .pdf looks like in a text editor. The garbled mess after "stream" is zip-compressed content within the pdf.

Just write out the whole stream into a .pdf file (use binary mode!) and try to open in Acrobat Reader.

with open('temp.pdf', 'wb') as outfile:
    outfile.write(pdf_content_from_database)

should do.


问:
Remove left padding

I added search view to toolbar.but there is small gap in Left side between LinearLayout and toolbar.I need to remove that padding.But I did not added any padding intentionally.How can I remove that?Thanks in advance.

```<code> <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/orange"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="Drawer With Swipe Tabs"
        android:weightSum="1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >

        <EditText
                android:id="@+id/editMobileNo"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_marginTop="5dp"
                android:paddingLeft="5dp"

                android:background="@drawable/login_edittext"
                android:textColor="@color/orange"
                android:textColorHint="@color/orange"
                android:hint="@string/search"
                android:drawableLeft="@drawable/search2"
                android:drawablePadding="10dp"
                android:gravity="left"
                android:layout_weight="0.96">
            </EditText>
            <ImageButton
                android:layout_width="0dp"
                android:layout_height="30dp"
                android:layout_weight="0.1"
                android:layout_margin="5dp"
                android:ems="10"
                android:background="@drawable/alarm3"
                android:gravity="center"
                >
            </ImageButton>
        </LinearLayout>

</android.support.v7.widget.Toolbar>
</code>```

答:
```<code><android.support.v7.widget.Toolbar
.
.
.
.

android:contentInsetLeft="0dp"
android:contentInsetStart="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:contentInsetRight="0dp"
android:contentInsetEnd="0dp"
app:contentInsetRight="0dp"
app:contentInsetEnd="0dp" />
</code>```

Add these to remove content Inset

Title: Remove left padding

Body:
I added search view to toolbar.but there is small gap in Left side between LinearLayout and toolbar.I need to remove that padding.But I did not added any padding intentionally.How can I remove that?Thanks in advance.

 <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/orange"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="Drawer With Swipe Tabs"
        android:weightSum="1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >

        <EditText
                android:id="@+id/editMobileNo"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_marginTop="5dp"
                android:paddingLeft="5dp"

                android:background="@drawable/login_edittext"
                android:textColor="@color/orange"
                android:textColorHint="@color/orange"
                android:hint="@string/search"
                android:drawableLeft="@drawable/search2"
                android:drawablePadding="10dp"
                android:gravity="left"
                android:layout_weight="0.96">
            </EditText>
            <ImageButton
                android:layout_width="0dp"
                android:layout_height="30dp"
                android:layout_weight="0.1"
                android:layout_margin="5dp"
                android:ems="10"
                android:background="@drawable/alarm3"
                android:gravity="center"
                >
            </ImageButton>
        </LinearLayout>

</android.support.v7.widget.Toolbar>

Body:
<android.support.v7.widget.Toolbar
.
.
.
.

android:contentInsetLeft="0dp"
android:contentInsetStart="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:contentInsetRight="0dp"
android:contentInsetEnd="0dp"
app:contentInsetRight="0dp"
app:contentInsetEnd="0dp" />

Add these to remove content Inset


问:
A downgrade path is not supported convert version 782 to 706 and earlier
I am creating one application where I have used ASP.NET MVC with Entity Framework 4.5.2 and trying to access the SQL Server but it gives me an error that I can't access any database so I just convert it to the single user mode.

Now after converting it to Single User mode the new error comes when I am trying to access in Server Explorer, Data Connections (Default Connection), it shows me the below dialog. I am not understand what is going wrong.

I have SQL Server version 11.0.2100.60.

Please some one help me to solve this issue!

答:
This worked for me (using Visual Studio 2015 community)...

In Server Explorer right-click the desired connection and select Modify Connection

Select Advanced Options

Change the Data Source to a different version (In my case it needed to be SQL express) press OK.

Hope it helps