问:
On Diffie-Hellman key exchange
The book I am reading, explains the algorithm as follows:

2 people think of 2 public "n and g" numbers both are aware of.

2 people think of 2 private "x and "y" numbers they keep secret.

Exchange happens as illustrated

I put together the following python code to see how this works and .... it does not. Please help me understand what am i missing:

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

 n=22 # publicly known
 g=42 # publicly known

 x=13 # only Alice knows this
 y=53 # only Bob knows this

 aliceSends = (g**x)%n
 bobComputes = aliceSends**y
 bobSends = (g**y)%n
 aliceComputes = bobSends**x

 print "Alice sends    ", aliceSends
 print "Bob computes   ", bobComputes
 print "Bob sends      ", bobSends
 print "Alice computes ", aliceComputes

 print "In theory both should have ", (g**(x*y))%n

 ---

 Alice sends     14
 Bob computes    5556302616191343498765890791686005349041729624255239232159744
 Bob sends       14
 Alice computes  793714773254144

 In theory both should have  16
</code>```

答:
For two people

```<code>#!/usr/bin/python
p=141301# publicly known
g=5728435 # publicly known
x=76435 # only Alice knows this
y=37846 # only Bob knows this
aliceSends = (g**x)%p
aliceComputes = (bobSends**x)%p
bobSends = (g**y)%p
bobComputes = (aliceSends**y) %p
bobSends = (g**y)%p
bobComputes = (aliceSends**y) %p
print ("Alice sends    ", aliceSends )
print ("Bob computes   ", bobComputes )
print ("Bob sends      ", bobSends)
print ("Alice computes ", aliceComputes)
</code>```

For three or more people

```<code>#!/usr/bin/python
p=141301# publicly known
g=5728435 # publicly known
x=76435 # only Alice knows this
y=37846 # only Bob knows this
z=23# only carol knows this
aliceSends = (g**x)%p
bobSends = (aliceSends**y)%p
carolComputes=(bobSends**z)%p
bobSends2=(g**y)%p
carolSends=(bobSends2**z)%p
aliceComputes=(carolSends**x)%p
carolSends2=(g**z)%p
aliceSends2=(carolSends2**x)%p
bobComputes=(aliceSends2**y)%p
print ("Alice computes ga and sends it to Bob.",aliceSends)
print ("Bob computes (ga)b = gab and sends it to Carol.",bobSends)
print ("Carol computes (gab)c = gabc and uses it as her secret.",carolComputes)
print ("Bob computes gb and sends it to Carol.",bobSends2)
print ("Carol computes (gb)c = gbc and sends it to Alice.",carolSends)
print ("Alice computes (gbc)a = gbca = gabc and uses it as her  secret.",aliceComputes)
print ("Carol computes gc and sends it to Alice.",carolSends2)
print ("Alice computes (gc)a = gca and sends it to Bob.",aliceSends2)
print ("Bob computes (gca)b = gcab = gabc and uses it as his
secret.",bobComputes)
</code>```

Title: On Diffie-Hellman key exchange

Body:
The book I am reading, explains the algorithm as follows:

2 people think of 2 public "n and g" numbers both are aware of.

2 people think of 2 private "x and "y" numbers they keep secret.

Exchange happens as illustrated

I put together the following python code to see how this works and .... it does not. Please help me understand what am i missing:

 #!/usr/bin/python

 n=22 # publicly known
 g=42 # publicly known

 x=13 # only Alice knows this
 y=53 # only Bob knows this

 aliceSends = (g**x)%n
 bobComputes = aliceSends**y
 bobSends = (g**y)%n
 aliceComputes = bobSends**x

 print "Alice sends    ", aliceSends
 print "Bob computes   ", bobComputes
 print "Bob sends      ", bobSends
 print "Alice computes ", aliceComputes

 print "In theory both should have ", (g**(x*y))%n

 ---

 Alice sends     14
 Bob computes    5556302616191343498765890791686005349041729624255239232159744
 Bob sends       14
 Alice computes  793714773254144

 In theory both should have  16

Body:
For two people

#!/usr/bin/python
p=141301# publicly known
g=5728435 # publicly known
x=76435 # only Alice knows this
y=37846 # only Bob knows this
aliceSends = (g**x)%p
aliceComputes = (bobSends**x)%p
bobSends = (g**y)%p
bobComputes = (aliceSends**y) %p
bobSends = (g**y)%p
bobComputes = (aliceSends**y) %p
print ("Alice sends    ", aliceSends )
print ("Bob computes   ", bobComputes )
print ("Bob sends      ", bobSends)
print ("Alice computes ", aliceComputes)

For three or more people

#!/usr/bin/python
p=141301# publicly known
g=5728435 # publicly known
x=76435 # only Alice knows this
y=37846 # only Bob knows this
z=23# only carol knows this
aliceSends = (g**x)%p
bobSends = (aliceSends**y)%p
carolComputes=(bobSends**z)%p
bobSends2=(g**y)%p
carolSends=(bobSends2**z)%p
aliceComputes=(carolSends**x)%p
carolSends2=(g**z)%p
aliceSends2=(carolSends2**x)%p
bobComputes=(aliceSends2**y)%p
print ("Alice computes ga and sends it to Bob.",aliceSends)
print ("Bob computes (ga)b = gab and sends it to Carol.",bobSends)
print ("Carol computes (gab)c = gabc and uses it as her secret.",carolComputes)
print ("Bob computes gb and sends it to Carol.",bobSends2)
print ("Carol computes (gb)c = gbc and sends it to Alice.",carolSends)
print ("Alice computes (gbc)a = gbca = gabc and uses it as her  secret.",aliceComputes)
print ("Carol computes gc and sends it to Alice.",carolSends2)
print ("Alice computes (gc)a = gca and sends it to Bob.",aliceSends2)
print ("Bob computes (gca)b = gcab = gabc and uses it as his
secret.",bobComputes)


来源: stackexchange

问:
Facebook C# sdk - Does the FacebookApp.Get("me") access to Facebook or just to cookie?
I'm using the Facebook c# sdk on a new project and i've a question.
In the follow code:

```<code>var app = new FacebookApp();
app.AppId = "myappid";
app.AppSecret = "theappsecretcode";
if (app.Session != null)
{
dynamic me = app.Get("me");
}
</code>```

When i'm calling the method Get of FacebookApp, i'm i just accessing to the Cookie saved when i've authenticated with Facebook or i'm connecting to the Facebook and getting the values?

I'm asking because i'm saving the values of the user in a session when i authenticate with the Facebook, but if the method Get doesn't access to Facebook and just to the cookie, then i'll stop using the session and start to access to the Facebook cookie instead (i haven't understand yet if the cookie save some information about the user, but i've searched in "Watch" window in VS and i haven't found anything)

Thanks

答: I've examined source code of FacebookApp and FacebookAppbase classes and have found out that method Get is always accessing the Facebook (there is no any cache).</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm using the Facebook c# sdk on a new project and i've a question.
In the follow code:

var app = new FacebookApp();
app.AppId = "myappid";
app.AppSecret = "theappsecretcode";
if (app.Session != null)
{
dynamic me = app.Get("me");
}

When i'm calling the method Get of FacebookApp, i'm i just accessing to the Cookie saved when i've authenticated with Facebook or i'm connecting to the Facebook and getting the values?

I'm asking because i'm saving the values of the user in a session when i authenticate with the Facebook, but if the method Get doesn't access to Facebook and just to the cookie, then i'll stop using the session and start to access to the Facebook cookie instead (i haven't understand yet if the cookie save some information about the user, but i've searched in "Watch" window in VS and i haven't found anything)

Thanks


问:
Block form submit if no one checkbox checked
I need help because confused how to block form submit if no one checkbox checked.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  $.each($checkbox, function(index, value) {
    if (!$(value).is(':checked')) {
      alert('Opps! You not select friends.');
      e.preventDefault();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />
  <button type="submit">Send</submit>
    </form></code>```

The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.

Please help.

答:
The first problem comes from this line :

```<code>if ( !$(value).is(':checked')) {
</code>```

Should be :

```<code>if ( !$(this).is(':checked')) {
</code>```

Since value contains the value of the selected checkbox not the object, so $(value) will not work.

Then if you want to submit with at least one checkbox you could check the length of checked input's like :

```<code>if( $('input.invitation-friends:checked').length == 0 )
{
    return false;
}
</code>```

Hope this helps.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  if( $('input.invitation-friends:checked').length == 0 )
  {
    return false;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />

  <button type="submit">Send</submit>
</form></code>```

ContentLicense: CC BY-SA 3.0

Body:
I need help because confused how to block form submit if no one checkbox checked.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  $.each($checkbox, function(index, value) {
    if (!$(value).is(':checked')) {
      alert('Opps! You not select friends.');
      e.preventDefault();
    }
  });
});

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />
  <button type="submit">Send</submit>
    </form>

The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.

Please help.

Body:
The first problem comes from this line :

if ( !$(value).is(':checked')) {

Should be :

if ( !$(this).is(':checked')) {

Since value contains the value of the selected checkbox not the object, so $(value) will not work.

Then if you want to submit with at least one checkbox you could check the length of checked input's like :

if( $('input.invitation-friends:checked').length == 0 )
{
    return false;
}

Hope this helps.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  if( $('input.invitation-friends:checked').length == 0 )
  {
    return false;
  }
});

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

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />

  <button type="submit">Send</submit>
</form>


问:
add a " once string matched using sed in multiple lines
while i am trying to replace a string using below command, all the strings are replaced which is having a 0.But, I need to replace only a string starting with 0 and combination of alpha numeric.Please help to exclude the others.Please find the sed command below what i used.

```<code>sed -r 's:((0\w+)):"&":g'  test >test.log
</code>```

input file:   test

```<code>0INTEL  GC  P   0servername     0.000       0I30019     12/02/15
0INTEL  GC  P   0servername     0.000       0I30019     12/02/15
</code>```

Expected output:  test.log

```<code>"0INTEL"    GC  P   "0servername"   0.000       I30019      12/02/15
"0INTEL"    GC  P   "0servername"   0.000       I30019      12/02/15
</code>```

Actual output:

```<code>"0INTEL"    GC  P   "0servername"   0."000"     I30019      12/"02"/15
"0INTEL"    GC  P   "0servername"   0."000"     I30019      12/"02"/15
</code>```

答:
Just another awk proposal.</p>

```<code>awk '{sub(/0INTEL/,"\0420INTEL\042")sub(/0servername/,"\0420servername\042")}1' file

"0INTEL"  GC  P   "0servername"     0.000       0I30019     12/02/15
"0INTEL"  GC  P   "0servername"     0.000       0I30019     12/02/15
</code>```

Body:
while i am trying to replace a string using below command, all the strings are replaced which is having a 0.But, I need to replace only a string starting with 0 and combination of alpha numeric.Please help to exclude the others.Please find the sed command below what i used.

sed -r 's:((0\w+)):"&":g'  test >test.log

input file:   test

0INTEL  GC  P   0servername     0.000       0I30019     12/02/15
0INTEL  GC  P   0servername     0.000       0I30019     12/02/15

Expected output:  test.log

"0INTEL"    GC  P   "0servername"   0.000       I30019      12/02/15
"0INTEL"    GC  P   "0servername"   0.000       I30019      12/02/15

Actual output:

"0INTEL"    GC  P   "0servername"   0."000"     I30019      12/"02"/15
"0INTEL"    GC  P   "0servername"   0."000"     I30019      12/"02"/15

Body:
Just another awk proposal.

awk '{sub(/0INTEL/,"\0420INTEL\042")sub(/0servername/,"\0420servername\042")}1' file

"0INTEL"  GC  P   "0servername"     0.000       0I30019     12/02/15
"0INTEL"  GC  P   "0servername"     0.000       0I30019     12/02/15


问:
Cut out Nothing with foldl
I have a list [Maybe a] where I want to cut out the Nothing elements with a function that uses foldl
For example cut [Just 2, Just 10, Nothing, Just 5] -> [2,10,5]

```<code>I wrote:
cut :: [Maybe a] -> [a]
cut a = foldl (help) [] a
               where help (x:xs) Nothing = (x:xs)
                     help (x:xs) Just a = a:(x:xs)
</code>```

Where is my mistake?

答:
By writing help (x:xs) Nothing = (x:xs) you have used a pattern (x:xs) this means that you expect the accumulator to be a list with at least one element. But that is not always the case, for instance the initial accumulator [] is the empty list.

We can simply use a variable l, instead of a pattern:

```<code>cut :: [Maybe a] -> [a]
cut a = foldl help [] a
               where help <b>l</b> Nothing = <b>l</b>
                     help <b>l</b> <b>(</b>Just a<b>)</b> = a:<b>l</b></code>```

Note that you also need to add brackets for a constructor with arguments.

But this will not solve the entire pattern, now you will have reversed the list. This is because foldl iterates through the list left-to-right, so you prepend values while you iterate through the list. We can use foldr instead. But now the type of the function does no longer works, since the help function in foldr takes the accumulator as second argument. So we can flip the arguments:

```<code>cut :: [Maybe a] -> [a]
cut a = fold<b>r</b> help [] a
               where help <b>Nothing l</b> = <b>l</b>
                     help <b>(Just a) l</b> = a:<b>l</b></code>```

And now it works. We can however clean up the code a bit. For instance use an eta-reduction on the cut function: we can remove a in the head and body of the function:

```<code>cut :: [Maybe a] -> [a]
cut = foldr help []
               where help Nothing l = l
                     help (Just a) l = a:l</code>```

and since the second argument in help can be removed and the body converted into functions:

```<code>cut :: [Maybe a] -> [a]
cut = foldr help []
               where help Nothing = <b>id</b>
                     help (Just a) = <b>(a:)</b></code>```

We can also use another catamorphism: foldr is the catamorphism of a list, and maybe is the catamorphism of Maybe, so we can write a:

```<code>maybe <value-in-case-of-nothing> <function-just-value> <Maybe value>
</code>```

So we can rewrite our help to:

```<code><b>import Data.Maybe(maybe)</b>

cut :: [Maybe a] -> [a]
cut = foldr help []
               where help = <b>maybe id (:)</b></code>```

or simply inject it as an argument of foldr:

```<code>import Data.Maybe(maybe)

cut :: [Maybe a] -> [a]
cut = foldr <b>(maybe id (:))</b> []</code>```

So now we used a catamporhism inside a catamorphism, so catamorphception.

Title: Cut out Nothing with foldl

Body:
I have a list [Maybe a] where I want to cut out the Nothing elements with a function that uses foldl
For example cut [Just 2, Just 10, Nothing, Just 5] -> [2,10,5]

I wrote:
cut :: [Maybe a] -> [a]
cut a = foldl (help) [] a
               where help (x:xs) Nothing = (x:xs)
                     help (x:xs) Just a = a:(x:xs)

Where is my mistake?

Body:
By writing help (x:xs) Nothing = (x:xs) you have used a pattern (x:xs) this means that you expect the accumulator to be a list with at least one element. But that is not always the case, for instance the initial accumulator [] is the empty list.

We can simply use a variable l, instead of a pattern:

cut :: [Maybe a] -> [a]
cut a = foldl help [] a
               where help l Nothing = l
                     help l (Just a) = a:l

Note that you also need to add brackets for a constructor with arguments.

But this will not solve the entire pattern, now you will have reversed the list. This is because foldl iterates through the list left-to-right, so you prepend values while you iterate through the list. We can use foldr instead. But now the type of the function does no longer works, since the help function in foldr takes the accumulator as second argument. So we can flip the arguments:

cut :: [Maybe a] -> [a]
cut a = foldr help [] a
               where help Nothing l = l
                     help (Just a) l = a:l

And now it works. We can however clean up the code a bit. For instance use an eta-reduction on the cut function: we can remove a in the head and body of the function:

cut :: [Maybe a] -> [a]
cut = foldr help []
               where help Nothing l = l
                     help (Just a) l = a:l

and since the second argument in help can be removed and the body converted into functions:

cut :: [Maybe a] -> [a]
cut = foldr help []
               where help Nothing = id
                     help (Just a) = (a:)

We can also use another catamorphism: foldr is the catamorphism of a list, and maybe is the catamorphism of Maybe, so we can write a:

maybe <value-in-case-of-nothing> <function-just-value> <Maybe value>

So we can rewrite our help to:

import Data.Maybe(maybe)

cut :: [Maybe a] -> [a]
cut = foldr help []
               where help = maybe id (:)

or simply inject it as an argument of foldr:

import Data.Maybe(maybe)

cut :: [Maybe a] -> [a]
cut = foldr (maybe id (:)) []

So now we used a catamporhism inside a catamorphism, so catamorphception.


问:
JPA Mapping Error -not provided sufficient metadata in your id class
I am trying to do mapping in JPA.

```<code>@Entity
public class Auction {

    @Id
    private Integer auctionId;

    @OneToMany(mappedBy="auctionId")
    @MapKey(name="auctionParamId")
    private Map<AuctionParam, AuctionParamValue> values;

}

@Entity
public class AuctionParam {

    @Id
    private Integer auctionParamId;

    private String description;

}

@Entity
public class AuctionParamValue {

    @EmbeddedId
    private AuctionParamValuePK pk;

    private String value;

}

@Embeddable
public class AuctionParamValuePK {

    @ManyToOne
    @JoinColumn(name="auctionId")
    private Auction auction;

    @ManyToOne
    @JoinColumn(name="auctionParamId")
    private AuctionParam auctionParam;

}
</code>```

Showing an error:-

.Error-Details:-Exception Description:
  Entity [class
  com.eaportal.domain.AuctionParamValue]

  uses [class
  com.eaportal.domain.AuctionParamValuePK]

  as embedded id class

  whose access-type
  has been determined as [FIELD].

  But
  [class
  com.eaportal.domain.AuctionParamValuePK]

  does not define any [FIELD]. It is
  likely that you have not provided

  sufficient metadata in your id class
  [class
  com.eaportal.domain.AuctionParamValuePK].

If you come up with a solution please let me know.

Thanks in Advance
Tushar

答:
I think there are some errors in your Auction class. This is how I think it should look

```<code>@Entity
public class Auction {

    @Id
    private Integer auctionId;

    @OneToMany(mappedBy="auction") // not auctionId
    @MapKey(name="auctionParam") // not auctionParamId
    private Map<AuctionParam, AuctionParamValue> values;

}
</code>```

(The annotation values have to correspond with fields (or properties), not with columns)

Body:
I am trying to do mapping in JPA.

@Entity
public class Auction {

    @Id
    private Integer auctionId;

    @OneToMany(mappedBy="auctionId")
    @MapKey(name="auctionParamId")
    private Map<AuctionParam, AuctionParamValue> values;

}

@Entity
public class AuctionParam {

    @Id
    private Integer auctionParamId;

    private String description;

}

@Entity
public class AuctionParamValue {

    @EmbeddedId
    private AuctionParamValuePK pk;

    private String value;

}

@Embeddable
public class AuctionParamValuePK {

    @ManyToOne
    @JoinColumn(name="auctionId")
    private Auction auction;

    @ManyToOne
    @JoinColumn(name="auctionParamId")
    private AuctionParam auctionParam;

}

Showing an error:-

.Error-Details:-Exception Description:
  Entity [class
  com.eaportal.domain.AuctionParamValue]

  uses [class
  com.eaportal.domain.AuctionParamValuePK]

  as embedded id class

  whose access-type
  has been determined as [FIELD].

  But
  [class
  com.eaportal.domain.AuctionParamValuePK]

  does not define any [FIELD]. It is
  likely that you have not provided

  sufficient metadata in your id class
  [class
  com.eaportal.domain.AuctionParamValuePK].

If you come up with a solution please let me know.

Thanks in Advance
Tushar

Body:
I think there are some errors in your Auction class. This is how I think it should look

@Entity
public class Auction {

    @Id
    private Integer auctionId;

    @OneToMany(mappedBy="auction") // not auctionId
    @MapKey(name="auctionParam") // not auctionParamId
    private Map<AuctionParam, AuctionParamValue> values;

}

(The annotation values have to correspond with fields (or properties), not with columns)


问:
change array with objects into new array with objects
Hi I have this array with objects,

```<code>[
    {
         "QuestionID":1350,
         "Answers":[
                {
                     "AnswerId":"1350_1",
                     "selected":true
                },
                {
                     "AnswerId":"1350_2",
                     "selected":false
                },
                {
                     "AnswerId":"1350_3",
                     "selected":false
                }
         ]
    },
    {
         "QuestionID":1349,
         "Answers":[
                {
                     "AnswerId":"1349_1",
                     "selected":false
                },
                {
                     "AnswerId":"1349_2",
                     "selected":true
                },
                {
                     "AnswerId":"1349_3",
                     "selected":false
                }
         ]
    }
]
</code>```

but it should be changed to this, where answerID is the selected answers ID

```<code>[
    {
        "QuestionID": 1350,
        "AnswerId": "1350_1"
    },
    {
        “QuestionID”: 1349,
        “AnswerId”: "1349_2"
    }
]
</code>```

答:
You can do that:</p>

```<code>data.map(item => ({
  QuestionID: item.QuestionID,
  AnswerId: item.Answers.find(answer => answer.selected).AnswerId,
}));
</code>```

Body:
Hi I have this array with objects,

[
    {
         "QuestionID":1350,
         "Answers":[
                {
                     "AnswerId":"1350_1",
                     "selected":true
                },
                {
                     "AnswerId":"1350_2",
                     "selected":false
                },
                {
                     "AnswerId":"1350_3",
                     "selected":false
                }
         ]
    },
    {
         "QuestionID":1349,
         "Answers":[
                {
                     "AnswerId":"1349_1",
                     "selected":false
                },
                {
                     "AnswerId":"1349_2",
                     "selected":true
                },
                {
                     "AnswerId":"1349_3",
                     "selected":false
                }
         ]
    }
]

but it should be changed to this, where answerID is the selected answers ID

[
    {
        "QuestionID": 1350,
        "AnswerId": "1350_1"
    },
    {
        “QuestionID”: 1349,
        “AnswerId”: "1349_2"
    }
]

Body:
You can do that:

data.map(item => ({
  QuestionID: item.QuestionID,
  AnswerId: item.Answers.find(answer => answer.selected).AnswerId,
}));


问:
How to Convert United States State Plane coordinates to Latitude and Longitude in Mathematica?
How to Convert United States State Plane coordinates to Latitude and Longitude in Mathematica?

I'm converting Washington DC Northing and Easting (in feet) of a location to latitude and longitude
Here is the address:
316 PENNSYLVANIA AVENUE SE  20003

And here are the  coordinate:

X= 399901.19    Y= 135465.63

I know that I should be ND83 and my SPC Zone is MD-1900

I checked GeodesyData[] and I tried all these:
"NAD27", "NAD831986", "NAD83CORS93", "NAD83CORS94", "NAD83CORS96", \
"NAD83HARN"
with GeoPosition[{399901, 135465, 0}, datum] but with no success.  I know in R I can use epsg:2804 or epsg:3559 but in Mathematica, I don't know which code to use, and none of these worked.

答:
I found out how to answer it:

Our coordinates are in datum NAD83 for Maryland 1800.  Therefore, our datum string for Mathematica should be "SPCS83MD00"
Knowing the State and the code connected to to the state are crucial to build the datum string.  After SPCS83, one adds the state, in this case MD, and the last 2 digits of the four-digit code.

Hence, one can convert to (WGS84) or latitude and longitude as follows:

```<code>    LatitudeLongitude[GeoGridPosition[{399901., 135466.}, "SPCS83MD00"]]
</code>```

One more thing:

If you want to find out the extension for SPCS83 or NAD 83 in Mathematica you just need to use, and start typing SPCS83 or NAD83 and it will give you the possible string containing the state and its codes (some states have more than 1 code)

```<code>  GeoProjectionData["SPCS83MD00"]
</code>```

Body:
I found out how to answer it:

Our coordinates are in datum NAD83 for Maryland 1800.  Therefore, our datum string for Mathematica should be "SPCS83MD00"
Knowing the State and the code connected to to the state are crucial to build the datum string.  After SPCS83, one adds the state, in this case MD, and the last 2 digits of the four-digit code.

Hence, one can convert to (WGS84) or latitude and longitude as follows:

    LatitudeLongitude[GeoGridPosition[{399901., 135466.}, "SPCS83MD00"]]

One more thing:

If you want to find out the extension for SPCS83 or NAD 83 in Mathematica you just need to use, and start typing SPCS83 or NAD83 and it will give you the possible string containing the state and its codes (some states have more than 1 code)

  GeoProjectionData["SPCS83MD00"]


问:
If condition to count column values based on index number
I have 14 column with 1st column (say A) containing the month value (1 for Jan, 2 for Feb and so on). Colum B contain a number representing 2017 year value. For the next 12 columns starting column C onwards, there are values for each month of 2018 starting from Jan 2018 till Dec 2018. In Col 15, i want to sum value of 2017 (Column B) with corresponding months in 2018 based on the month value in Column A. For example, if the month value is 3, then the result should give me the sum of values in column B(2017) + column C(Jan2018) + column D(Feb 2018) + column B (Mar 2018). Since month value 3 represents March 2018.
I tried to use the function Choose but seems too length. Is there a smaller and easy function?       </p>

答:
```<code>=SUM(B2:INDEX(C2:N2,1,A2))
</code>```

INDEX(C2:N2,1,A2) here gives the reference within C2:N2 at row 1 and column from cell A2. The range from SUM then becomes B2 to the reference obtained from INDEX.

Body:
=SUM(B2:INDEX(C2:N2,1,A2))

INDEX(C2:N2,1,A2) here gives the reference within C2:N2 at row 1 and column from cell A2. The range from SUM then becomes B2 to the reference obtained from INDEX.


问:
Find all mongo documents containing a field with a specific value using java
I am trying to use mongo's Java driver to read through a collection and only pull back documents with a field that is a range of values. An example of this would be if I had data like

```<code>{ "name" : "foo", "Color" : "white", "Date" : 20171116 }
{ "name" : "bar", "Color" : "black", "Date" : 20171115 }
{ "name" : "Jeff", "Color" : "purple", "Date" : 20171114 }
{ "name" : "John", "Color" : "blue", "Date" : 20171015 }
</code>```

I would want to begin on 20171114 and end on 20171116 so I would do something like

```<code>DateFormat df = new SimpleDateFormat("yyyyMMdd");
String begin = "20171114";
String end   = "20171116";
Date startDate;
Date endDate;
</code>```

Then I would need to convert the strings to a date and use a cursor like

```<code>try {
  startDate = df.parse(startDateString);
  endDate = df.parse(endDateString);
  BasicDBObject data = new BasicDBObject();
  data.put("Date", new BasicDBObject( new BasicDBOject( "$gte", startDate).append("$lte", endDate)));
} catch(ParseException e){
  e.printStackTrace
}
</code>```

However when I do this it returns nothing.

Answer:

I was trying to compare a number to a date which doesn't work so I converted my begin & end string to integers by doing

```<code>Integer beginDate = Integer.valueOf(begin)
Integer endDate = Integer.valueOf(end)
</code>```

and it worked.

答:
I think you have saved values of Date as numbers. Please check your code once how you are saving and please let us know.

Considering that please try below by passing long values as

```<code>try {
  Long startDate = 20171114L;
  Long endDate = 20171116L;
  BasicDBObject data = new BasicDBObject();
  data.put("Date", new BasicDBObject( new BasicDBObject( "$gte", startDate).append("$lte", endDate)));
} catch(ParseException e){
  e.printStackTrace
}
</code>```

Body:
I am trying to use mongo's Java driver to read through a collection and only pull back documents with a field that is a range of values. An example of this would be if I had data like

{ "name" : "foo", "Color" : "white", "Date" : 20171116 }
{ "name" : "bar", "Color" : "black", "Date" : 20171115 }
{ "name" : "Jeff", "Color" : "purple", "Date" : 20171114 }
{ "name" : "John", "Color" : "blue", "Date" : 20171015 }

I would want to begin on 20171114 and end on 20171116 so I would do something like

DateFormat df = new SimpleDateFormat("yyyyMMdd");
String begin = "20171114";
String end   = "20171116";
Date startDate;
Date endDate;

Then I would need to convert the strings to a date and use a cursor like

try {
  startDate = df.parse(startDateString);
  endDate = df.parse(endDateString);
  BasicDBObject data = new BasicDBObject();
  data.put("Date", new BasicDBObject( new BasicDBOject( "$gte", startDate).append("$lte", endDate)));
} catch(ParseException e){
  e.printStackTrace
}

However when I do this it returns nothing.

Answer:

I was trying to compare a number to a date which doesn't work so I converted my begin & end string to integers by doing

Integer beginDate = Integer.valueOf(begin)
Integer endDate = Integer.valueOf(end)

and it worked.

Body:
I think you have saved values of Date as numbers. Please check your code once how you are saving and please let us know.

Considering that please try below by passing long values as

try {
  Long startDate = 20171114L;
  Long endDate = 20171116L;
  BasicDBObject data = new BasicDBObject();
  data.put("Date", new BasicDBObject( new BasicDBObject( "$gte", startDate).append("$lte", endDate)));
} catch(ParseException e){
  e.printStackTrace
}


问:
JSON Feed Timestamp
I am using FullCalendar JS Plugin for a tool I am building and I am creating a JSON Feed.

```<code>        "id": "'.$row['AppointmentID'].'",
        "title": "'.$row['AppointmentName'].'",
        "url": "'.$row['URL'].'",
        "class": "event-important",
        "start": "1364407286400"
    },
</code>```

The time stamp for the start of this is 1364407286400 I for the life of me cannot work out how this timestamp is formated. I thought it was Unix but I generated a timestamp for today and replaced it and it is still not showing.

Can anyone point me in right direction?

答:
This is a timestamp in miliseconds. You can easily test this value using:

```<code>$test = (int)(1364407286400/1000);
var_dump((new DateTime())->setTimestamp($test));
</code>```

the output will be:

```<code>object(DateTime)#1 (3) {
  ["date"]=>
      string(26) "2013-03-27 11:01:26.000000"
  ["timezone_type"]=>
      int(3)
  ["timezone"]=>
      string(10) "US/Pacific"
}
</code>```

Title: JSON Feed Timestamp

Body:
I am using FullCalendar JS Plugin for a tool I am building and I am creating a JSON Feed.

        "id": "'.$row['AppointmentID'].'",
        "title": "'.$row['AppointmentName'].'",
        "url": "'.$row['URL'].'",
        "class": "event-important",
        "start": "1364407286400"
    },

The time stamp for the start of this is 1364407286400 I for the life of me cannot work out how this timestamp is formated. I thought it was Unix but I generated a timestamp for today and replaced it and it is still not showing.

Can anyone point me in right direction?

Body:
This is a timestamp in miliseconds. You can easily test this value using:

$test = (int)(1364407286400/1000);
var_dump((new DateTime())->setTimestamp($test));

the output will be:

object(DateTime)#1 (3) {
  ["date"]=>
      string(26) "2013-03-27 11:01:26.000000"
  ["timezone_type"]=>
      int(3)
  ["timezone"]=>
      string(10) "US/Pacific"
}


问:
how to mark row on gridview by any value?
i have gridview that contain:

```<code>Fname|Born
aa   |03/05
bb   |19/01
cc   |03/08
dd   |19/01
</code>```

if today is: 19/01/2011  how to mark in red color the 2 rows that Satisfies the condition ?

in C# asp.net

thanks for any help

答:
try using RowDataBound  event of the grid to test the date column
if (e.row.cell[1]=...)
, and from there you can access the e.Row.BackColor= ...</p>

Body:
i have gridview that contain:

Fname|Born
aa   |03/05
bb   |19/01
cc   |03/08
dd   |19/01

if today is: 19/01/2011  how to mark in red color the 2 rows that Satisfies the condition ?

in C# asp.net

thanks for any help


问:
Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"
I am using Android studio 1.0.1. I have a java module referred by other modules in my project. I have checked it out from SVN But now every

Unsupported Modules Detected: Compilation is not supported for following modules: . Unfortunately you can't have non-Gradle Java modules and Android-Gradle modules in one project.

After getting this error AS stop compilation of this module so that I am not able to compile/run my project any more.

答:
Close the Android Studio and Move ".idea" Folder and paste it outside Project root folder( For Back up if you need).

Open the Android studio.
On Opening the project it"ll ask add module (app) to your project. You can ignore the same.

It set set default build variant to be "debug".
You can see build variant tab on left corner or hover on "Monitor" Symbol on left bottom

Note: No need to change your .iml file of your project.tom to get build variant option and "Invalidate Cache and Restart" will also not work rather it will clear your history files too!.


问:
How create a Noninstantiable class java?
```<code>public class CarServices {
  private CarServices() { } // Prevents instantiation

 //some methods

}
</code>```

I prevent the constructor from been instantiated is this the correct way, or am I missing something?

答:
You can mark your class - abstract:

```<code>public abstract class CarService{
...
}
</code>```

We can't create instance for abstract class, only extends for this class.

Body:
public class CarServices {
  private CarServices() { } // Prevents instantiation

 //some methods

}

I prevent the constructor from been instantiated is this the correct way, or am I missing something?

Body:
You can mark your class - abstract:

public abstract class CarService{
...
}

We can't create instance for abstract class, only extends for this class.


问:
Java library for converting characters between different encodings
I'm facing the following situation:

We poll some csv data from an external source. The source's response headers doesn't specify that which is the charset, and the data contains some german characters which are showing as a question mark inside a rombus (I know that means the character is not defined in UTF-8).

We want to do some work with this data, and then forward it, but to fix this issue, we want to also encode the erroneous characters to a correct format to show them properly.

I have read already some answers here and most of them suggested using "string.getBytes("encoding")" method, and then create a new string from this with some other encoding.

But from what I understand I need a different thing, as this method just decodes the characters and process the same bytes in respect to another encoding, and some characters get represented with different byte lengths in utf-8 than for example ISO-8859-1 (which I believe the data we are polling is really encoded in) which causes strange characters appearing in the result string so its not really what we want to achieve.

I would need something which can

Get the character from a byte representation in a source encoding

Get the character from a byte representation in the target encoding

Iterate over the decoded byte array and replace all characters byte representation with the representation from the target encoding

After this it would be safe to create a new string from the byte array with the target encoding.
So if anyone knows a good library which can do that? I dont want to implement it myself if its already there.

答:
You have bytes, binary data, that represent text in some character set. For that you need a charset detection. Knowing the Charset you can load it in a java String (Unicode) and save it as bytes given any Charset you want.

If that target Charset cannot represent the Unicode symbol (code point), then one might even determine how that is handled. See CharsetDecoder/CharsetEncoder.

For Charset detection there exist some libraries. I wrote my own for a partial set of charsets & languages. It works best in combination with language detection. For instance for Czech.

See What is the most accurate encoding detector?


问:
Issue with testing Spring MVC slice in SpringBoot 1.4
I'm trying out the new Spring Boot 1.4 MVC testing features. I have the following controller.

```<code>@Controller
public class ProductController {

  private ProductService productService;

  @Autowired
  public void setProductService(ProductService productService) {
    this.productService = productService;
  }

  @RequestMapping(value = "/products", method = RequestMethod.GET)
  public String list(Model model){
    model.addAttribute("products", productService.listAllProducts());
     return "products";
  }
}
</code>```

My minimal ProductService implementation is:

```<code>@Service
public class ProductServiceImpl implements ProductService {
  private ProductRepository productRepository;

  @Autowired
  public void setProductRepository(ProductRepository productRepository) {
    this.productRepository = productRepository;
  }

  @Override
  public Iterable<Product> listAllProducts() {
    return productRepository.findAll();
  }

}
</code>```

The code of ProductRepository is:

```<code>public interface ProductRepository extends CrudRepository<Product,
 Integer>{
}
</code>```

I'm trying to use the new @WebMvcTest to test the conroller. My view is a thymeleaf teamplate. And my controller test is this:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(ProductController.class)

public class ProductControllerTest {
private MockMvc mockMvc;

@Before
public void setUp() {
    ProductController productController= new ProductController();
    mockMvc = MockMvcBuilders.standaloneSetup(productController).build();
}

@Test
public void testList() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/products"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("products"))
 .andExpect(MockMvcResultMatchers.model().attributeExists("products"));
 }
}
</code>```

But, on running the test I get this error.

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through method 'setProductService' parameter 0: No qualifying bean of type [guru.springframework.services.ProductService] found for dependency [guru.springframework.services.ProductService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [guru.springframework.services.ProductService] found for dependency [guru.springframework.services.ProductService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
</code>```

I need help to resolve the issue to properly test ProductController. Suggestions for additional andExpect() for more thorough testing of the controller will be highly appreciated.

Thanks in advance.

答:
Who is interested in loading the full application should try using @SpringBootTest combined with @AutoConfigureMockMvc rather than the @WebMvcTest.

I have been struggling with the problem for quite a while, but finally I got the complete picture.

The many tutorials on the internet,  <s>as well as the official Spring documentation I found so far </s>, state that you can test your controllers using @WebMvcTest; that's entirely correct, still omitting half of the story though.

As pointed out by the javadoc of such annotation, @WebMvcTest is only intended to test your controllers, and won't load all your app's beans at all, and this is by design.

It is even incompatible with explicit bean scanning annotations like @Componentscan.

I suggest anybody interested in the matter, to read the full javadoc of the annotation (which is just 30 lines long and stuffed of condensed useful info) but I'll extract a couple of gems relevant to my situation.

from Annotation Type WebMvcTest

Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans). [...]
  If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than this annotation.

And actually, only @SpringBootTest + @AutoConfigureMockMvc fixed my problem, all other approaches that made use of @WebMvcTest failed to load some of the required beans.

EDIT

I take back my comment I made about Spring documentation, because I wasn't aware that a slice was implied when one uses a @WebMvcTest; actually the MVC slice documentation put it clear that not all the app is loaded, which is by the very nature of a slice.

Custom test slice with Spring Boot 1.4

Test slicing is about segmenting the ApplicationContext that is created for your test. Typically, if you want to test a controller using MockMvc, surely you don’t want to bother with the data layer. Instead you’d probably want to mock the service that your controller uses and validate that all the web-related interaction works as expected.

Body:
I'm trying out the new Spring Boot 1.4 MVC testing features. I have the following controller.

@Controller
public class ProductController {

  private ProductService productService;

  @Autowired
  public void setProductService(ProductService productService) {
    this.productService = productService;
  }

  @RequestMapping(value = "/products", method = RequestMethod.GET)
  public String list(Model model){
    model.addAttribute("products", productService.listAllProducts());
     return "products";
  }
}

My minimal ProductService implementation is:

@Service
public class ProductServiceImpl implements ProductService {
  private ProductRepository productRepository;

  @Autowired
  public void setProductRepository(ProductRepository productRepository) {
    this.productRepository = productRepository;
  }

  @Override
  public Iterable<Product> listAllProducts() {
    return productRepository.findAll();
  }

}

The code of ProductRepository is:

public interface ProductRepository extends CrudRepository<Product,
 Integer>{
}

I'm trying to use the new @WebMvcTest to test the conroller. My view is a thymeleaf teamplate. And my controller test is this:

@RunWith(SpringRunner.class)
@WebMvcTest(ProductController.class)

public class ProductControllerTest {
private MockMvc mockMvc;

@Before
public void setUp() {
    ProductController productController= new ProductController();
    mockMvc = MockMvcBuilders.standaloneSetup(productController).build();
}

@Test
public void testList() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/products"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("products"))
 .andExpect(MockMvcResultMatchers.model().attributeExists("products"));
 }
}

But, on running the test I get this error.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through method 'setProductService' parameter 0: No qualifying bean of type [guru.springframework.services.ProductService] found for dependency [guru.springframework.services.ProductService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [guru.springframework.services.ProductService] found for dependency [guru.springframework.services.ProductService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

I need help to resolve the issue to properly test ProductController. Suggestions for additional andExpect() for more thorough testing of the controller will be highly appreciated.

Thanks in advance.


问:
Showing Many-To-Many in different model's form in Django?
Say I have three models, a Professor model, a Course model, and a Review model. The user is allowed to make a Review, which reviews a Professor that teaches a certain Course.

I'm thinking of how to model the many to many relationship of Professor and Course, and how to reference that relationship in Review. My idea so far is to use models.ManyToMany to link Professor and Course.

Models.py (Prof)

```<code>class Prof(models.Model):
first_name = models.CharField(max_length = 20, unique = False)
last_name = models.CharField(max_length = 20, unique = False)

    def __str__ (self):
        return self.first_name + " " + self.last_name

class Course(models.Model):
    name = models.CharField(max_length = 20, unique = True)
    prof = models.ManyToManyField(Prof)

    def __str__ (self):
        return self.name
</code>```

Models.py (Review)

```<code>class Review(models.Model):
    message = models.TextField(max_length = 4000)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(null = True)
    rating = models.IntegerField(
        default = 5,
        validators = [MaxValueValidator(5), MinValueValidator(0)]
    )
    prof = models.ForeignKey(Prof, related_name = 'reviews')
    course = models.ForeignKey(Course, related_name = 'reviews')
    user = models.ForeignKey(User, related_name = 'reviews')

    def __str__ (self):
        return self.message
</code>```

forms.py

```<code>class ReviewForm(ModelForm):
    rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5}))

    class Meta:
        model = Review
        fields = ['message', 'rating', 'prof', 'course', 'user']
</code>```

This is my code so far for displaying the form

```<code><h1>New Review</h1>
<form method="POST">
    {% csrf_token %}
    <p>{{ review_form.message }}</p>
    <p>{{ review_form.rating }}</p>
    <p>{{ review_form.prof }}</p>
    <!-- The prof chosen's courses should be shown here -->
    <button type="submit">Save</button>
</form>
</code>```

Right now, forms.py shows all the objects under Course, and i'm not sure how to instead show the courses of a professor. Is it possible to filter the form after a prof is chosen from the drop down, to display the courses he/she teacher?

答:
It sounds like you're going about this the right way.  You haven't mentioned your urls.py structure yet, or views.py but the most straightforward way to do this is to display the courses by professor, taking the professor's id (or slug-field) in as a parameter  - either in the URL (v straightforward) or as the output from a form on a previous page (and reload the template with a professor parameter) or in Ajax, depending on your appetite for shiny-new-things.

In your view, when you call the form, you can then do, along the lines from this answer -

form.courses.queryset = Course.objects.filter(professor__in=[professor.id,])

Note that I've put filtered on a list here, which only has one item - it does give you scope to expand, or to use a queryset for more complicated functions later.

Tweak as appropriate if you're using class-based views. :)

Body:
Say I have three models, a Professor model, a Course model, and a Review model. The user is allowed to make a Review, which reviews a Professor that teaches a certain Course.

I'm thinking of how to model the many to many relationship of Professor and Course, and how to reference that relationship in Review. My idea so far is to use models.ManyToMany to link Professor and Course.

Models.py (Prof)

class Prof(models.Model):
first_name = models.CharField(max_length = 20, unique = False)
last_name = models.CharField(max_length = 20, unique = False)

    def __str__ (self):
        return self.first_name + " " + self.last_name

class Course(models.Model):
    name = models.CharField(max_length = 20, unique = True)
    prof = models.ManyToManyField(Prof)

    def __str__ (self):
        return self.name

Models.py (Review)

class Review(models.Model):
    message = models.TextField(max_length = 4000)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(null = True)
    rating = models.IntegerField(
        default = 5,
        validators = [MaxValueValidator(5), MinValueValidator(0)]
    )
    prof = models.ForeignKey(Prof, related_name = 'reviews')
    course = models.ForeignKey(Course, related_name = 'reviews')
    user = models.ForeignKey(User, related_name = 'reviews')

    def __str__ (self):
        return self.message

forms.py

class ReviewForm(ModelForm):
    rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5}))

    class Meta:
        model = Review
        fields = ['message', 'rating', 'prof', 'course', 'user']

This is my code so far for displaying the form

New Review

<form method="POST">
    {% csrf_token %}

{{ review_form.message }}

{{ review_form.rating }}

{{ review_form.prof }}

    <button type="submit">Save</button>
</form>

Right now, forms.py shows all the objects under Course, and i'm not sure how to instead show the courses of a professor. Is it possible to filter the form after a prof is chosen from the drop down, to display the courses he/she teacher?


问:
Store additional data in task comments
I'm looking for a way to log some structured data nearby task comments.

It would be preferable to handle it like other actions from Add Action actions menu. Here is how I see it interface mock

Have you got any idea how to do it? If it is of course possible that way, otherwise how to achieve similar effect?

答: Adding the data, as an action would be a little bit hard. You need to have the whole thing as an extension as it is declared in Phabricator documentation. But simple value field can be added as JSON configuration values in Phabricator without changing anything.Configuring Custom Fields will help.</p>

Title: Store additional data in task comments


问:
Translate JSON request to Java Google sheet API V4
In google Sheet API guide,

I read that a find request (find the cell with value 'X') can be formatted as follows in JSON:

```<code>{
  "find": string,
  "replacement": string,
  "matchCase": boolean,
  "matchEntireCell": boolean,
  "searchByRegex": boolean,
  "includeFormulas": boolean,

  // Union field scope can be only one of the following:
  "range": {
    object(GridRange)
  },
  "sheetId": number,
  "allSheets": boolean,
  // End of list of possible types for union field scope.
}
</code>```

requests can be made in the form of this URL
https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId .......

But I'm not able to translate that to JAVA code

The closest I've found was this code in one of the forums:

```<code>    requests.add(new Request().setFindReplace(new FindReplaceRequest().setFind(entry.getKey())
            .setMatchEntireCell(true)
            .setMatchCase(true)
            .setReplacement(entry.getValue())
            .setRange(new GridRange()
                    .setSheetId(0)
                    .setStartRowIndex(row)
                    .setEndRowIndex(row + 1))));
}

String cellReq = (new FindReplaceRequest().setFind("samuel")).getFind();
</code>```

which lack a response that I expect from the API, letting me know which cell in the sheet has the value I'm trying to find.

thanks

答:
It looks like you only partially copied the example from the Guide on this page: https://developers.google.com/sheets/api/guides/batchupdate#example

You need to place the FindReplaceRequest inside a BatchUpdateSpreadsheetRequest (in the requests field) and send it in a Spreadsheets.BatchUpdate call.

The full example is:

```<code>List<Request> requests = new ArrayList<>();
// Change the spreadsheet's title.
requests.add(new Request()
        .setUpdateSpreadsheetProperties(new UpdateSpreadsheetPropertiesRequest()
                .setProperties(new SpreadsheetProperties()
                        .setTitle(title))
                .setFields("title")));
// Find and replace text.
requests.add(new Request()
        .setFindReplace(new FindReplaceRequest()
                .setFind(find)
                .setReplacement(replacement)
                .setAllSheets(true)));
// Add additional requests (operations) ...

BatchUpdateSpreadsheetRequest body =
        new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse response =
        service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
FindReplaceResponse findReplaceResponse = response.getReplies().get(1).getFindReplace();
System.out.printf("%d replacements made.", findReplaceResponse.getOccurrencesChanged());
</code>```

Body:
In google Sheet API guide,

I read that a find request (find the cell with value 'X') can be formatted as follows in JSON:

{
  "find": string,
  "replacement": string,
  "matchCase": boolean,
  "matchEntireCell": boolean,
  "searchByRegex": boolean,
  "includeFormulas": boolean,

  // Union field scope can be only one of the following:
  "range": {
    object(GridRange)
  },
  "sheetId": number,
  "allSheets": boolean,
  // End of list of possible types for union field scope.
}

requests can be made in the form of this URL
https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId .......

But I'm not able to translate that to JAVA code

The closest I've found was this code in one of the forums:

    requests.add(new Request().setFindReplace(new FindReplaceRequest().setFind(entry.getKey())
            .setMatchEntireCell(true)
            .setMatchCase(true)
            .setReplacement(entry.getValue())
            .setRange(new GridRange()
                    .setSheetId(0)
                    .setStartRowIndex(row)
                    .setEndRowIndex(row + 1))));
}

String cellReq = (new FindReplaceRequest().setFind("samuel")).getFind();

which lack a response that I expect from the API, letting me know which cell in the sheet has the value I'm trying to find.

thanks

Body:
It looks like you only partially copied the example from the Guide on this page: https://developers.google.com/sheets/api/guides/batchupdate#example

You need to place the FindReplaceRequest inside a BatchUpdateSpreadsheetRequest (in the requests field) and send it in a Spreadsheets.BatchUpdate call.

The full example is:

List<Request> requests = new ArrayList<>();
// Change the spreadsheet's title.
requests.add(new Request()
        .setUpdateSpreadsheetProperties(new UpdateSpreadsheetPropertiesRequest()
                .setProperties(new SpreadsheetProperties()
                        .setTitle(title))
                .setFields("title")));
// Find and replace text.
requests.add(new Request()
        .setFindReplace(new FindReplaceRequest()
                .setFind(find)
                .setReplacement(replacement)
                .setAllSheets(true)));
// Add additional requests (operations) ...

BatchUpdateSpreadsheetRequest body =
        new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse response =
        service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
FindReplaceResponse findReplaceResponse = response.getReplies().get(1).getFindReplace();
System.out.printf("%d replacements made.", findReplaceResponse.getOccurrencesChanged());


问:
Issue when ap-angular2-fullcalendar AOT issue
I am facing an issue when i do AOT for my angular 4 app , where i am referencing ap-angular2-fullcalendar.

Here are my configurations in rollup-config.js

**

```<code>import rollup      from 'rollup';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs    from 'rollup-plugin-commonjs';
import uglify      from 'rollup-plugin-uglify';
import includePaths from 'rollup-plugin-includepaths';

let includePathOptions = {
    include: { 'core-module/core.module' : 'core-module/core.module.js' },
    extensions: ['.js', '.json', '.html']
};
//paths are relative to the execution path
export default {
input: 'app/main-aot.js',
output : {
    file: 'aot/dist/build.js', // output a single application bundle
    format: 'iife'
},
sourcemap: true,
sourcemapFile: 'aot/dist/build.js.map',
plugins: [
    includePaths(includePathOptions),
    nodeResolve({jsnext: true, module: true}),
commonjs({
    include: [
        'core-module/**',
        'app/**',
        'node_modules/rxjs/**',
        'node_modules/angular2-logger/**',
        'node_modules/ng2-bs3-modal/**',
        'node_modules/ng2-cookies/**',
        'node_modules/ng2-toastr/**',
        'node_modules/ng2-translate/**',
        'node_modules/ng2-select/**',
        'node_modules/jquery/**',
        'node_modules/moment/**',
        'node_modules/fullcalendar/**',
        'node_modules/ap-angular2-fullcalendar/**'
    ],
    namedExports: {
        'node_modules/angular2-logger/core.js': [ 'Logger', 'Options', 'Level' ],
        'node_modules/ng2-bs3-modal/ng2-bs3-modal.js' : [ 'ModalComponent' ],
        'node_modules/ng2-cookies/ng2-cookies.js': [ 'Cookie' ],
        'node_modules/ng2-select/index.js': ['SelectModule', 'SelectComponent']
    }
}),
uglify()
]
}
</code>```

**

Then in index.html I have included

```<code><link rel="stylesheet" href="node_modules/fullcalendar/dist/fullcalendar.min.css"/>

<script src="/assets/References/jquery-3.2.1.min.js"></script>
<script src="/assets/References/jquery-2.2.0.min.js"></script>
<script src="node_modules/moment/min/moment.min.js"></script>
<script src="node_modules/fullcalendar/dist/fullcalendar.min.js"></script>
<script src="/aot/shim.min.js?v=2.1.4"></script>
<script src="/aot/zone.min.js?v=0.7.4"></script>
<script>window.module = 'aot';</script>
<script src="/aot/dist/build.js?v=2017.11.14"></script>
</code>```

However , when i browse my website i am getting below error in fullcaledar.js.

uncaught typeerror: : "Cannot add property fullCalendar, object is not extensible"

During Development , it works , as I am using systemjs.config.js and it is configured like

```<code>(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            "app": 'app',

            'jquery': 'node_modules/jquery/dist/jquery.min.js',
            'bootstrap': 'node_modules/bootstrap/dist/js/bootstrap.min.js',
            'moment': 'node_modules/moment',
            'fullcalendar': 'node_modules/fullcalendar/dist/fullcalendar.js',
            'ap-angular2-fullcalendar': 'node_modules/ap-angular2-fullcalendar'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            "app": {
                main: './main.js',
                defaultExtension: 'js'
            },
            'fullcalendar': {
                defaultExtension: 'js'
            },
            'ap-angular2-fullcalendar': {
                main: 'index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);
</code>```

Any idea how to get around this ? I am planning to buy license for Full Calendar but this is a sort of a blocker at the moment.

答: i can see fullcalendar.js is a jquery library. What i got from my search on google, it is peer dependency issue. avoid multiple versions of jquery on the same page.(index.html)</p>

Body:
I am facing an issue when i do AOT for my angular 4 app , where i am referencing ap-angular2-fullcalendar.

Here are my configurations in rollup-config.js

**

import rollup      from 'rollup';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs    from 'rollup-plugin-commonjs';
import uglify      from 'rollup-plugin-uglify';
import includePaths from 'rollup-plugin-includepaths';

let includePathOptions = {
    include: { 'core-module/core.module' : 'core-module/core.module.js' },
    extensions: ['.js', '.json', '.html']
};
//paths are relative to the execution path
export default {
input: 'app/main-aot.js',
output : {
    file: 'aot/dist/build.js', // output a single application bundle
    format: 'iife'
},
sourcemap: true,
sourcemapFile: 'aot/dist/build.js.map',
plugins: [
    includePaths(includePathOptions),
    nodeResolve({jsnext: true, module: true}),
commonjs({
    include: [
        'core-module/**',
        'app/**',
        'node_modules/rxjs/**',
        'node_modules/angular2-logger/**',
        'node_modules/ng2-bs3-modal/**',
        'node_modules/ng2-cookies/**',
        'node_modules/ng2-toastr/**',
        'node_modules/ng2-translate/**',
        'node_modules/ng2-select/**',
        'node_modules/jquery/**',
        'node_modules/moment/**',
        'node_modules/fullcalendar/**',
        'node_modules/ap-angular2-fullcalendar/**'
    ],
    namedExports: {
        'node_modules/angular2-logger/core.js': [ 'Logger', 'Options', 'Level' ],
        'node_modules/ng2-bs3-modal/ng2-bs3-modal.js' : [ 'ModalComponent' ],
        'node_modules/ng2-cookies/ng2-cookies.js': [ 'Cookie' ],
        'node_modules/ng2-select/index.js': ['SelectModule', 'SelectComponent']
    }
}),
uglify()
]
}

**

Then in index.html I have included

<link rel="stylesheet" href="node_modules/fullcalendar/dist/fullcalendar.min.css"/>

However , when i browse my website i am getting below error in fullcaledar.js.

uncaught typeerror: : "Cannot add property fullCalendar, object is not extensible"

During Development , it works , as I am using systemjs.config.js and it is configured like

(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            "app": 'app',

            'jquery': 'node_modules/jquery/dist/jquery.min.js',
            'bootstrap': 'node_modules/bootstrap/dist/js/bootstrap.min.js',
            'moment': 'node_modules/moment',
            'fullcalendar': 'node_modules/fullcalendar/dist/fullcalendar.js',
            'ap-angular2-fullcalendar': 'node_modules/ap-angular2-fullcalendar'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            "app": {
                main: './main.js',
                defaultExtension: 'js'
            },
            'fullcalendar': {
                defaultExtension: 'js'
            },
            'ap-angular2-fullcalendar': {
                main: 'index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);

Any idea how to get around this ? I am planning to buy license for Full Calendar but this is a sort of a blocker at the moment.


问:
Add missing xmlns attributes to SOAP-ENV:Envelope tag using SoapClient in PHP
How can I edit the xmlns attributes of the <SOAP-ENV:Envelope /> tag?

I have a situation where xmlns:xsi and xmlns:xsd are missing.  I'd like to know how to add them back in?

Example:

```<code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ns1="http://fedex.com/ws/track/v12">
    <SOAP-ENV:Body>
        <ns1:TrackRequest>
            ...
</code>```

But I need it be this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:ns1="http://fedex.com/ws/track/v12"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SOAP-ENV:Body>
        <ns1:TrackRequest>
          ...
</code>```

答:
I know this is kinda old, but in case someone stumbles upon it...

After fiddling around with SoapVar, this is how it worked for me:

```<code>$params[] = new SoapVar('',XSD_ANYXML, '', null, 'Envelope', 'http://www.w3.org/2001/XMLSchema');
$params[] = new SoapVar('',XSD_ANYXML, '', null, 'Envelope', 'http://www.w3.org/2001/XMLSchema-instance');
//you can add more vars here.
//E.g. in my case I also needed $params[] = new SoapVar('<notifications xmlns="http://soap.sforce.com/2005/09/outbound"><Ack>true</Ack></notifications>',XSD_ANYXML); as I was working with salesforces soap.
return new SoapVar($params, XSD_ANYXML);
</code>```

Body:
How can I edit the xmlns attributes of the <SOAP-ENV:Envelope /> tag?

I have a situation where xmlns:xsi and xmlns:xsd are missing.  I'd like to know how to add them back in?

Example:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ns1="http://fedex.com/ws/track/v12">
    <SOAP-ENV:Body>
        <ns1:TrackRequest>
            ...

But I need it be this:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:ns1="http://fedex.com/ws/track/v12"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SOAP-ENV:Body>
        <ns1:TrackRequest>
          ...

Body:
I know this is kinda old, but in case someone stumbles upon it...

After fiddling around with SoapVar, this is how it worked for me:

$params[] = new SoapVar('',XSD_ANYXML, '', null, 'Envelope', 'http://www.w3.org/2001/XMLSchema');
$params[] = new SoapVar('',XSD_ANYXML, '', null, 'Envelope', 'http://www.w3.org/2001/XMLSchema-instance');
//you can add more vars here.
//E.g. in my case I also needed $params[] = new SoapVar('<notifications xmlns="http://soap.sforce.com/2005/09/outbound"><Ack>true</Ack></notifications>',XSD_ANYXML); as I was working with salesforces soap.
return new SoapVar($params, XSD_ANYXML);


问:
Instantiating view frame so that it fits with navigation bar / tab bar?
I have an app where sometimes views are in navigation controllers, sometimes not, and sometimes in a tab bar and navigation controller.

I create my views programatically using code such as this:

```<code>let contact = ContactFormViewController(contactFormView: ContactFormView.init(frame: UIScreen.main.bounds))
</code>```

however this is causing frames to always be as large as the screen, meaning when there is a navigation bar or tab bar the view is pushed off the visible screen and doesnt fit.

Is there a method to adapt the view height to always show it all on screen regardless of parent elements like the nav bar or tab bar? or would it be a case of always creating views with manual subtractions like this, which seems poor as it needs to assume hardcoded elements:

```<code>let attendees = AttendeesViewController(attendeesView: AttendeesView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-55)))
</code>```

thanks for any guidance as its a major issue in my app

答: I think it's wrong to take UIScreen as the reference to lay out your views. I think you should use the content view (the view at the top of your hierarchy) as the reference.</p>

Body:
I have an app where sometimes views are in navigation controllers, sometimes not, and sometimes in a tab bar and navigation controller.

I create my views programatically using code such as this:

let contact = ContactFormViewController(contactFormView: ContactFormView.init(frame: UIScreen.main.bounds))

however this is causing frames to always be as large as the screen, meaning when there is a navigation bar or tab bar the view is pushed off the visible screen and doesnt fit.

Is there a method to adapt the view height to always show it all on screen regardless of parent elements like the nav bar or tab bar? or would it be a case of always creating views with manual subtractions like this, which seems poor as it needs to assume hardcoded elements:

let attendees = AttendeesViewController(attendeesView: AttendeesView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-55)))

thanks for any guidance as its a major issue in my app


问:
ViewHelper is not found
I fiddled around with it for more than 8 hours without getting it resolved.
All I want is to call a ViewHelper in a Fluid template. I did that before and I never had a similar problem.

My ViewHelper file is located in

```<code>EXTDIR/VendorName/Classes/ViewHelpers/SomeViewHelper.php.
</code>```

In my Fluid Template I use the namespace

```<code>{namespace k=VendorName\Extname\ViewHelpers}.
</code>```

Somewhere in the template I call the ViewHelper with

```<code>{k:some()}.
</code>```

The ViewHelper script "SomeViewHelper.php" contains the following code:

```<code>class SomeViewHelper extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper {
    public function initializeArguments() { }

    public function render() {
        return 7;
    }
}
</code>```

As you can see, the whole thing is quite simple and the expected output on the page should be "7". But calling a page in the frontend produces this error message:

```<code>Oops, an error occurred!

Could not analyse class:VendorName\Extname\ViewHelpers\SomeViewHelper maybe not loaded
or no autoloader?"
</code>```

Any hints on what might be wrong here?

Cheers
Michael

答:
If TYPO3 is installed in composer mode and your extension is not installed via composer (e.g. a ProviderExtension of FluidTYPO3), you must provide autoload information for your extension in the main composer.json file, as described within TYPO3-composer-documentation:

In Composer Mode all class loading information must be provided by each of the installed extensions or the root package. If TYPO3 extensions are not installed by composer, e.g. because they are directly committed to the root package or a new package is kickstarted, class loading information needs to be provided, otherwise no classes can be loaded for these extensions/ packages.

E.g. if you have a site extension directly committed to your root package, you must include the class loading information in the root package like that:

Drove me crazy to get my ViewHelpers autoloaded. Providing the autoload-information within a composer.json or the ext_emconf.php of the extension and reinstalling it didn't do the trick.

Title: ViewHelper is not found

Body:
I fiddled around with it for more than 8 hours without getting it resolved.
All I want is to call a ViewHelper in a Fluid template. I did that before and I never had a similar problem.

My ViewHelper file is located in

EXTDIR/VendorName/Classes/ViewHelpers/SomeViewHelper.php.

In my Fluid Template I use the namespace

{namespace k=VendorName\Extname\ViewHelpers}.

Somewhere in the template I call the ViewHelper with

{k:some()}.

The ViewHelper script "SomeViewHelper.php" contains the following code:

class SomeViewHelper extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper {
    public function initializeArguments() { }

    public function render() {
        return 7;
    }
}

As you can see, the whole thing is quite simple and the expected output on the page should be "7". But calling a page in the frontend produces this error message:

Oops, an error occurred!

Could not analyse class:VendorName\Extname\ViewHelpers\SomeViewHelper maybe not loaded
or no autoloader?"

Any hints on what might be wrong here?

Cheers
Michael


问:
Build time error swift 4 xCode 9 with Alamofire added in pod
I was working on a project which I required to updated to support Swift 4. After making related changes, When I have run the application I got the similar error mentioned below. After which I have created a new and empty project to check which also encountered the same error.

What did I do?

Initially, I have created a project in xCode 9 with Swift 4 and add Alamofire in pod file and run the code without making any change in code.

What happened instead?

Instead of building successful, It shows an error:

```<code>PhaseScriptExecution \[CP\]\ Embed\ Pods\ Frameworks /Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Intermediates.noindex/xCode9Demo.build/Debug-iphonesimulator/xCode9Demo.build/Script-2DACA56F3034C685ED1342BD.sh
    cd /Users/rigel/Vihar/Development/Demo/Created/xCode9Demo
    /bin/sh -c /Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Intermediates.noindex/xCode9Demo.build/Debug-iphonesimulator/xCode9Demo.build/Script-2DACA56F3034C685ED1342BD.sh

mkdir -p /Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Products/Debug-iphonesimulator/xCode9Demo.app/Frameworks
rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework" "/Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Products/Debug-iphonesimulator/xCode9Demo.app/Frameworks"
building file list ... done
Alamofire.framework/
Alamofire.framework/Alamofire
Alamofire.framework/Info.plist
Alamofire.framework/_CodeSignature/
Alamofire.framework/_CodeSignature/CodeResources

sent 1730891 bytes  received 98 bytes  3461978.00 bytes/sec
total size is 1730337  speedup is 1.00
basename: invalid option -- 's'
Try `basename --help' for more information.
Command /bin/sh failed with exit code 1
</code>```

Alamofire Environment

Alamofire version: 4.5.0

Xcode version: 9_GM(Beta)

Swift version: 4.0

Platform(s) running Alamofire: iOS 10.3.3

macOS version running Xcode: 10.12.6

Anyone can please help me?

答:
After spending good amount of time on the surfing, I come to know that the issue is related to the configurations, mostly hardware configurations of a MAC I was using.

Once I have tried running the same code on another mac it works perfectly.

This could not be the solution for all which I know but I have shared my scenario because if someone stuck in such an issue and even after spending a good amount of time like me, don't get any solution I suggest please check running the code in another MAC.

I have to spend a really good amount of time on the issue, which I wish other must not.

I hope you don't have the issue but might got help from this So please don't lead the answer in any negative direction if this will not be your answer.

Body:
I was working on a project which I required to updated to support Swift 4. After making related changes, When I have run the application I got the similar error mentioned below. After which I have created a new and empty project to check which also encountered the same error.

What did I do?

Initially, I have created a project in xCode 9 with Swift 4 and add Alamofire in pod file and run the code without making any change in code.

What happened instead?

Instead of building successful, It shows an error:

PhaseScriptExecution \[CP\]\ Embed\ Pods\ Frameworks /Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Intermediates.noindex/xCode9Demo.build/Debug-iphonesimulator/xCode9Demo.build/Script-2DACA56F3034C685ED1342BD.sh
    cd /Users/rigel/Vihar/Development/Demo/Created/xCode9Demo
    /bin/sh -c /Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Intermediates.noindex/xCode9Demo.build/Debug-iphonesimulator/xCode9Demo.build/Script-2DACA56F3034C685ED1342BD.sh

mkdir -p /Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Products/Debug-iphonesimulator/xCode9Demo.app/Frameworks
rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework" "/Users/rigel/Library/Developer/Xcode/DerivedData/xCode9Demo-fhmuhhcblhavqddwdzduqcfflaqu/Build/Products/Debug-iphonesimulator/xCode9Demo.app/Frameworks"
building file list ... done
Alamofire.framework/
Alamofire.framework/Alamofire
Alamofire.framework/Info.plist
Alamofire.framework/_CodeSignature/
Alamofire.framework/_CodeSignature/CodeResources

sent 1730891 bytes  received 98 bytes  3461978.00 bytes/sec
total size is 1730337  speedup is 1.00
basename: invalid option -- 's'
Try `basename --help' for more information.
Command /bin/sh failed with exit code 1

Alamofire Environment

Alamofire version: 4.5.0

Xcode version: 9_GM(Beta)

Swift version: 4.0

Platform(s) running Alamofire: iOS 10.3.3

macOS version running Xcode: 10.12.6

Anyone can please help me?


问:
Refactoring static classes and methods (Json serialisation/deserialisation)
I've used https://quicktype.io to create a class for my Json data. However I'm not really understanding why with the helper methods created to convert to json, from json, and supply default parameters they are each created differently as a static method of the class, a static class and a class with a static method.

The reason really is because as soon as I create a second class from another set of json data the code fails because of the static classes and I want to make sure I refactor them correctly. As well as understand the reasons of course.

I figure 'Converter' will never change across all my json objects so I can move this as is to a separate file and Serialize to a static method with FromJson. But I'd just like to understand more about the reasoning of how it was done in the first place and the better approach.

Here is the code:

```<code>public partial class StationDO
{
    public string Active { get; set; }
    //more fields here
}

public partial class StationDO
    {
        public static List<StationDO> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<StationDO>>(json, Converter.Settings);
        }
    }

    public static class Serialize
    {
        public static string ToJson(this List<StationDO> self)
        {
            return JsonConvert.SerializeObject(self, Converter.Settings);
        }
    }

    public class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };
    }
</code>```

If I look at the Java code the same site produces, it simply puts everything bar the bean into a single class 'Converter'

答:
You can have all the static members in StationDO class. In that case I recommend mark that class as sealed (public sealed class StationDO) to prevent someone to inheriting from that class and use the static methods from inherited class.

```<code>public class InheritedStationDO : StationDO { }
// ... somewhere else ...
InheritedStationDO.FromJson(jsonValue); // still returns List<StationDO> not List<InheritedStationDO> !!!
</code>```

EDIT:

After close look I think, the whole design of members is not good.

1) There is no need to accept just List<StationDO>.

2) There is no need the defined special methods for (de)serialization of every class, you will have. You can have just one method for serialization and one for deserialization for all your classes.

Example:

```<code>public class StationDO {
    public string Active { get; set; }
}

public class AnotherDO {
    public string Name { get; set; }
}

// and more *DO classes

// class need to be "static" because contains "extension methods"
public static class MySerializationHelper {
    private static readonly JsonSerializerSettings serializationSettings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };

    // universal method for deserialization from json
    // the generic type "T" represents the result type of deserialization
    public static T FromJson<T>(string json) {
        return JsonConvert.DeserializeObject<T>(json, serializationSettings);
    }

    // universal method for serialization to json
    // this "this" keyword means, its "extension method"
    public static string ToJson<T>(this T self) {
        return JsonConvert.SerializeObject(self, serializationSettings);
    }
}
</code>```

Usage:

```<code>StationDO obj01 = GetSomeStation();

// returns json of one object
string json01A = obj01.ToJson(); // these two lines are equivalent
string json01B = MySerializationHelper.ToJson(obj01); // these two lines are equivalent

// returns new object deserialized from json in "json01" variable
StationDO clone01 = MySerializationHelper.FromJson<StationDO>(json01A);

StationDO obj02 = GetAnotherStation();
StationDO[] arr01 = new StationDO[] { obj01, obj02 };

// returns json of array with two objects
string json02A = arr01.ToJson(); // these two lines are equivalent
string json02B = MySerializationHelper.ToJson(arr01); // these two lines are equivalent

// returns new array with deserialized object from json in "json02" variable
StationdDO[] clone02 = MySerializationHelper.FromJson<StationdDO[]>(json02A);

AnotherDO obj03 = GetAnotherDO();
string json03A = obj03.ToJson(); // these two lines are equivalent
string json03B = MySerializationHelper.ToJson(obj03); // these two lines are equivalent
</code>```

As you see, the generics is the way, how to avoid code duplication for every class.
And you can (de)serialize all kind of arrays and collections or single objects. Not just List<T>.

Body:
I've used https://quicktype.io to create a class for my Json data. However I'm not really understanding why with the helper methods created to convert to json, from json, and supply default parameters they are each created differently as a static method of the class, a static class and a class with a static method.

The reason really is because as soon as I create a second class from another set of json data the code fails because of the static classes and I want to make sure I refactor them correctly. As well as understand the reasons of course.

I figure 'Converter' will never change across all my json objects so I can move this as is to a separate file and Serialize to a static method with FromJson. But I'd just like to understand more about the reasoning of how it was done in the first place and the better approach.

Here is the code:

public partial class StationDO
{
    public string Active { get; set; }
    //more fields here
}

public partial class StationDO
    {
        public static List<StationDO> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<StationDO>>(json, Converter.Settings);
        }
    }

    public static class Serialize
    {
        public static string ToJson(this List<StationDO> self)
        {
            return JsonConvert.SerializeObject(self, Converter.Settings);
        }
    }

    public class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };
    }

If I look at the Java code the same site produces, it simply puts everything bar the bean into a single class 'Converter'

Body:
You can have all the static members in StationDO class. In that case I recommend mark that class as sealed (public sealed class StationDO) to prevent someone to inheriting from that class and use the static methods from inherited class.

public class InheritedStationDO : StationDO { }
// ... somewhere else ...
InheritedStationDO.FromJson(jsonValue); // still returns List<StationDO> not List<InheritedStationDO> !!!

EDIT:

After close look I think, the whole design of members is not good.

1) There is no need to accept just List<StationDO>.

2) There is no need the defined special methods for (de)serialization of every class, you will have. You can have just one method for serialization and one for deserialization for all your classes.

Example:

public class StationDO {
    public string Active { get; set; }
}

public class AnotherDO {
    public string Name { get; set; }
}

// and more *DO classes

// class need to be "static" because contains "extension methods"
public static class MySerializationHelper {
    private static readonly JsonSerializerSettings serializationSettings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };

    // universal method for deserialization from json
    // the generic type "T" represents the result type of deserialization
    public static T FromJson<T>(string json) {
        return JsonConvert.DeserializeObject<T>(json, serializationSettings);
    }

    // universal method for serialization to json
    // this "this" keyword means, its "extension method"
    public static string ToJson<T>(this T self) {
        return JsonConvert.SerializeObject(self, serializationSettings);
    }
}

Usage:

StationDO obj01 = GetSomeStation();

// returns json of one object
string json01A = obj01.ToJson(); // these two lines are equivalent
string json01B = MySerializationHelper.ToJson(obj01); // these two lines are equivalent

// returns new object deserialized from json in "json01" variable
StationDO clone01 = MySerializationHelper.FromJson<StationDO>(json01A);

StationDO obj02 = GetAnotherStation();
StationDO[] arr01 = new StationDO[] { obj01, obj02 };

// returns json of array with two objects
string json02A = arr01.ToJson(); // these two lines are equivalent
string json02B = MySerializationHelper.ToJson(arr01); // these two lines are equivalent

// returns new array with deserialized object from json in "json02" variable
StationdDO[] clone02 = MySerializationHelper.FromJson<StationdDO[]>(json02A);

AnotherDO obj03 = GetAnotherDO();
string json03A = obj03.ToJson(); // these two lines are equivalent
string json03B = MySerializationHelper.ToJson(obj03); // these two lines are equivalent

As you see, the generics is the way, how to avoid code duplication for every class.
And you can (de)serialize all kind of arrays and collections or single objects. Not just List<T>.


问:
Block form submit if no one checkbox checked
I need help because confused how to block form submit if no one checkbox checked.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  $.each($checkbox, function(index, value) {
    if (!$(value).is(':checked')) {
      alert('Opps! You not select friends.');
      e.preventDefault();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />
  <button type="submit">Send</submit>
    </form></code>```

The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.

Please help.

答:
There is a way to do this that is much simpler than what you are doing. There's no need to loop. Just used the :checked pseudo-class selector to get a set of nodes that are checked and check the .length of the resulting set of nodes. If the .length is 0, no checkboxes have been checked.

$( '#send-invite-form' ).on('submit', function(e) {
   if($( 'input[class^="invitation-friends"]:checked' ).length === 0) {
      alert( 'Oops! You not select friends.' );
      e.preventDefault();
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send-invite-form">
     <input type="checkbox" class="invitation-friends" value="875" />
     <input type="checkbox" class="invitation-friends" value="394" />

     <button type="submit">Send</submit>
</form></code>```

Body:
I need help because confused how to block form submit if no one checkbox checked.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  $.each($checkbox, function(index, value) {
    if (!$(value).is(':checked')) {
      alert('Opps! You not select friends.');
      e.preventDefault();
    }
  });
});

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />
  <button type="submit">Send</submit>
    </form>

The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.

Please help.

Body:
There is a way to do this that is much simpler than what you are doing. There's no need to loop. Just used the :checked pseudo-class selector to get a set of nodes that are checked and check the .length of the resulting set of nodes. If the .length is 0, no checkboxes have been checked.

$( '#send-invite-form' ).on('submit', function(e) {
   if($( 'input[class^="invitation-friends"]:checked' ).length === 0) {
      alert( 'Oops! You not select friends.' );
      e.preventDefault();
   }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send-invite-form">
     <input type="checkbox" class="invitation-friends" value="875" />
     <input type="checkbox" class="invitation-friends" value="394" />

     <button type="submit">Send</submit>
</form>


问:
Reading from Csv, adding headers starting at column 2, 4, and 6
I am wanting to add headers to my data being 2, 4, 6 as it just makes it much easier to manage datasets when you have consistent headers.

```<code>Col A   Col B    Col C  Col D   Col E  Col F
         data           data           data
         etc,,          etc,,          etc,,
</code>```

Here is what I have tried:

```<code>df = pd.read_csv(filename, header=None, usecols=[2, 4, 6])
df.columns = ["Sequence", "Start", "End"]
</code>```

I have also tried:

```<code>df = pd.read_csv(“filename, sep='\t',
                  names = ["Sequence", "Start", "End", "Coverage"])
</code>```

I have tried a number of different methods, but I cannot get adding headers to work.  There is no error message in this case but no output with a header.

答:
You can use index_col=False for not convert first column to index and then usecols[1,3,5] for select 2.,4,6. columns, because python counts from 0. Last add parameter names for new columns names and add header=None for read first row to data:

```<code>df = pd.read_excel('HA.xlsx',
                   index_col=False,
                   usecols=[1,3,5],
                   names=["Sequence", "Start", "End"],
                   header=None)
print (df)

  Sequence      Start        End
0      awd   awdwdawd    wadwdwd
1    dawdw  wdadawdwd      wdadd
2    awawd  wadawdawd  waddwaawd
3    wadaw        NaN    dwadawd
</code>```

Body:
I am wanting to add headers to my data being 2, 4, 6 as it just makes it much easier to manage datasets when you have consistent headers.

Col A   Col B    Col C  Col D   Col E  Col F
         data           data           data
         etc,,          etc,,          etc,,

Here is what I have tried:

df = pd.read_csv(filename, header=None, usecols=[2, 4, 6])
df.columns = ["Sequence", "Start", "End"]

I have also tried:

df = pd.read_csv(“filename, sep='\t',
                  names = ["Sequence", "Start", "End", "Coverage"])

I have tried a number of different methods, but I cannot get adding headers to work.  There is no error message in this case but no output with a header.

Body:
You can use index_col=False for not convert first column to index and then usecols[1,3,5] for select 2.,4,6. columns, because python counts from 0. Last add parameter names for new columns names and add header=None for read first row to data:

df = pd.read_excel('HA.xlsx',
                   index_col=False,
                   usecols=[1,3,5],
                   names=["Sequence", "Start", "End"],
                   header=None)
print (df)

  Sequence      Start        End
0      awd   awdwdawd    wadwdwd
1    dawdw  wdadawdwd      wdadd
2    awawd  wadawdawd  waddwaawd
3    wadaw        NaN    dwadawd


答:
try this, no need to explain i think:</p>

```<code>var found = false;
$.each( $checkbox, function(index, value) {
    if( $(this).is(':checked') ) {
        found = true;
    }
});
if(!found){
    alert( 'Opps! You not select friends.' );
    e.preventDefault();
}
</code>```

Title: Block form submit if no one checkbox checked

Body:
try this, no need to explain i think:

var found = false;
$.each( $checkbox, function(index, value) {
    if( $(this).is(':checked') ) {
        found = true;
    }
});
if(!found){
    alert( 'Opps! You not select friends.' );
    e.preventDefault();
}