问:
Sort dynamic dropdown list alphabetically
I have a dropdown with three strings horizontally for each item. How can I alphabetically sort first by string 1 from each item, then by string 2 from each item?

Here's my snippet:

```<code>foreach (var item in list)
{
    if(typeof(T).Equals(typeof(Machine)))
    {
        Machine machine = (item as Machine);
        string title = machine.MachineName + " - " + machine.Serial + " - " + machine.MachineOwnership;
        alert.AddAction(UIAlertAction.Create(title, UIAlertActionStyle.Default, action => {
            button.SetTitle(title, UIControlState.Normal);
        }));
    }
    else if(typeof(T).Equals(typeof(Person)))
    {
        alert.AddAction(UIAlertAction.Create((item as Person).Name, UIAlertActionStyle.Default, action => {
            button.SetTitle((item as Person).Name, UIControlState.Normal);
        }));
    }
}
</code>```

Where list contains objects of type Machine which has the following properties:

MachineName, Serial and MachineOwnshership (all strings).

So I want to do something like OrderBy(MachineName).ThenBy(Serial) but not sure how to do so correctly when I'm first checking to see what the list type is and then populating the dropdown list per item.

My dropdown list looks something like this if anyone needs clarification:

```<code>-------------------------------------------------
MachineNameStartsWithA - 01234 - OwnerStartsWithA
--------------------------------------------------
MachineNameStartsWithB - 012345 - OwnerStartsWithB
---------------------------------------------------
</code>```

etc.... where it's a long list of items where the strings are separated by "-" like it's shown in the code.

Also, for what it's worth, this is currently inside a Xamarin app.

答:
I think something like this should work. Sorting by a Tuple should be lexicographic:

```<code>list.OfType<Machine>().OrderBy(x => new Tuple<string,string>(x.MachineName,x.Serial))
</code>```

The OfType call should also remove the need for the typeof check and cast - the result should be an iterable of Machines.

Per the comment regarding multiple object types:

Grouping like types together

This would be my default preference from a UI/UX perspective unless it really makes sense to mix Machines and Persons together. Depending on the length of the list it may be preferable to split on the element type first as list.OfType will enumerate the entire list each time.

```<code>foreach(var item in list.OfType<Machine>().OrderBy(x => new Tuple<string,string>(x.MachineName,x.Serial)))
{
  // append item
}
foreach(var item in list.OfType<Person>().OrderBy(x => x.Name))
{
  // append item
}
</code>```

Interleaving various types

```<code>private Tuple<string,string> Projection(BaseClass x)
{
    Machine item = x as Machine;
    if(item != null)
    {
      return new Tuple<string,string>(item.MachineName,item.Serial);
    }

    Person item = x as Person;
    if(item != null)
    {
      return new Tuple<string,string>(item.Name,"");
    }
}

foreach(var item in list.OrderBy(Projection))
{
  // check type of item and append as appropriate
}
</code>```

Body:
I have a dropdown with three strings horizontally for each item. How can I alphabetically sort first by string 1 from each item, then by string 2 from each item?

Here's my snippet:

foreach (var item in list)
{
    if(typeof(T).Equals(typeof(Machine)))
    {
        Machine machine = (item as Machine);
        string title = machine.MachineName + " - " + machine.Serial + " - " + machine.MachineOwnership;
        alert.AddAction(UIAlertAction.Create(title, UIAlertActionStyle.Default, action => {
            button.SetTitle(title, UIControlState.Normal);
        }));
    }
    else if(typeof(T).Equals(typeof(Person)))
    {
        alert.AddAction(UIAlertAction.Create((item as Person).Name, UIAlertActionStyle.Default, action => {
            button.SetTitle((item as Person).Name, UIControlState.Normal);
        }));
    }
}

Where list contains objects of type Machine which has the following properties:

MachineName, Serial and MachineOwnshership (all strings).

So I want to do something like OrderBy(MachineName).ThenBy(Serial) but not sure how to do so correctly when I'm first checking to see what the list type is and then populating the dropdown list per item.

My dropdown list looks something like this if anyone needs clarification:

-------------------------------------------------
MachineNameStartsWithA - 01234 - OwnerStartsWithA
--------------------------------------------------
MachineNameStartsWithB - 012345 - OwnerStartsWithB
---------------------------------------------------

etc.... where it's a long list of items where the strings are separated by "-" like it's shown in the code.

Also, for what it's worth, this is currently inside a Xamarin app.

Body:
I think something like this should work. Sorting by a Tuple should be lexicographic:

list.OfType<Machine>().OrderBy(x => new Tuple<string,string>(x.MachineName,x.Serial))

The OfType call should also remove the need for the typeof check and cast - the result should be an iterable of Machines.

Per the comment regarding multiple object types:

Grouping like types together

This would be my default preference from a UI/UX perspective unless it really makes sense to mix Machines and Persons together. Depending on the length of the list it may be preferable to split on the element type first as list.OfType will enumerate the entire list each time.

foreach(var item in list.OfType<Machine>().OrderBy(x => new Tuple<string,string>(x.MachineName,x.Serial)))
{
  // append item
}
foreach(var item in list.OfType<Person>().OrderBy(x => x.Name))
{
  // append item
}

Interleaving various types

private Tuple<string,string> Projection(BaseClass x)
{
    Machine item = x as Machine;
    if(item != null)
    {
      return new Tuple<string,string>(item.MachineName,item.Serial);
    }

    Person item = x as Person;
    if(item != null)
    {
      return new Tuple<string,string>(item.Name,"");
    }
}

foreach(var item in list.OrderBy(Projection))
{
  // check type of item and append as appropriate
}


来源: stackexchange

问:
How to handle Image carousel in protractor which are moving with time interval of 3 seconds
```<code><div class="carousel ng-isolate-scope" ng-mouseleave="play()" ng-mouseenter="pause()" no-wrap="false" interval="3000">
<ol class="carousel-indicators" ng-show="slides().length > 1"/>
<div class="carousel-inner" ng-transclude="">
    <div class="item text-center ng-isolate-scope next left" ng-transclude="" ng-class="{ 'active': leaving || (active && !entering), 'prev': (next || active) && direction=='prev', 'next': (next || active) && direction=='next', 'right': direction=='prev', 'left': direction=='next' }">
        <div class="col-md-10 text-center center-img ng-scope">
            <img width="800px" height="480px" alt="neustar" src="app/images/Landing.png">
        </div>
    </div>
        <div class="item text-center ng-isolate-scope active left" ng-transclude="" ng-class="{ 'active': leaving || (active && !entering), 'prev': (next || active) && direction=='prev', 'next': (next || active) && direction=='next', 'right': direction=='prev', 'left': direction=='next' }">
            <div class="col-md-10 text-center center ng-scope" style="height: 500px;">
            </div>
        </div>
        <a class="left carousel-control" ng-show="slides().length > 1" ng-click="prev()"/>
        <a class="right carousel-control" ng-show="slides().length > 1" ng-click="next()"/>
    </div>
</div>
</code>```

答:
I would suggest using "browser.wait" with "protractor.expectedCondition.visibiltyOf" and then performing the action you want.

Without more context of the problem and expectations, I can't be more specific.

ContentLicense: CC BY-SA 3.0

Body:
 1"/>

         1" ng-click="prev()"/>
         1" ng-click="next()"/>


问:
R: NA/NaN/Inf in foreign function call (arg 1) for vegdist
I am trying to make a dissimilarity matrix by using the following code:

```<code>BC26bBrayCurtisMatrix<-vegdist(BC2_6b_OTU, method="bray", binary=FALSE, diag=FALSE, upper=FALSE,na.rm = FALSE)
</code>```

I am getting this error:

```<code>Error in vegdist(BC2_6b_OTU, method = "bray", binary = FALSE, diag = FALSE, NA/NaN/Inf in foreign function call (arg 1)
</code>```

I have tried:

```<code>is.na(BC2_6b_OTU)
</code>```

The output returns all FALSE except for 2 columns at the end of the table. These are actually blank on my BC2_6b_OTU.csv file but say 'TRUE' after this is.na output.  Could this be the problem? If so, how do I delete this row?

Any other suggestions? I am new to R and I appreciate the help!

答:
If you want to remove certain columns, you can do

```<code>x <- x[, c(ncol(x), ncol(x)-1)]
</code>```

or

```<code>x <- x[ , !sapply(x, FUN = function(n) any(is.na(n))))
</code>```

My guess would be that this .csv was created in a spreadsheet program? If so, consider removing "empty" columns at the end of the dataset and work on a clean set.

Here's a demonstration that NAs can cause your problem.

```<code>library(vegan)

data(varespec)
vare.dist <- vegdist(varespec)

varespec$sneakycol1 <- NA
varespec$sneakycol2 <- NA

sneaky.dist <- vegdist(varespec, method = "bray")
</code>```

Body:
I am trying to make a dissimilarity matrix by using the following code:

BC26bBrayCurtisMatrix<-vegdist(BC2_6b_OTU, method="bray", binary=FALSE, diag=FALSE, upper=FALSE,na.rm = FALSE)

I am getting this error:

Error in vegdist(BC2_6b_OTU, method = "bray", binary = FALSE, diag = FALSE, NA/NaN/Inf in foreign function call (arg 1)

I have tried:

is.na(BC2_6b_OTU)

The output returns all FALSE except for 2 columns at the end of the table. These are actually blank on my BC2_6b_OTU.csv file but say 'TRUE' after this is.na output.  Could this be the problem? If so, how do I delete this row?

Any other suggestions? I am new to R and I appreciate the help!

Body:
If you want to remove certain columns, you can do

x <- x[, c(ncol(x), ncol(x)-1)]

or

x <- x[ , !sapply(x, FUN = function(n) any(is.na(n))))

My guess would be that this .csv was created in a spreadsheet program? If so, consider removing "empty" columns at the end of the dataset and work on a clean set.

Here's a demonstration that NAs can cause your problem.

library(vegan)

data(varespec)
vare.dist <- vegdist(varespec)

varespec$sneakycol1 <- NA
varespec$sneakycol2 <- NA

sneaky.dist <- vegdist(varespec, method = "bray")


问:
Adding CommandLogger to MongoClient - monitoring
I have MongoClient from PyMongo.I do not know how to add a event_listener to an existing MongoClient. This is what I have:

from pymongo import MongoClient, monitoring

class CommandLogger(monitoring.CommandListener):
    def started(self, event):
        logging.info("Command {0.command_name} with request id "
                     "{0.request_id} started on server "
                     "{0.connection_id}".format(event))

```<code>def succeeded(self, event):
    logging.info("Command {0.command_name} with request id "
                 "{0.request_id} on server {0.connection_id} "
                 "succeeded in {0.duration_micros} "
                 "microseconds".format(event))

def failed(self, event):
    logging.error("Command {0.command_name} with request id "
                 "{0.request_id} on server {0.connection_id} "
                 "failed in {0.duration_micros} "
                 "microseconds".format(event))

monitoring.register(CommandLogger())

def get_mongo_client():
    ...
    ...
    my_mongo_client = MongoClient(connString)

   # Here, I want to add a event_listener - something like this:
   # my_mongo_client = MongoClient(connString, event_listeners=[CommandLogger()])
    return my_mongo_client
</code>```

How do I create a mongo_client with a listener and with a connection string (uri)?

答:
Yes, the code you commented-out is correct:

```<code>my_mongo_client = MongoClient(connString, event_listeners=[CommandLogger()])
</code>```

Is something not working as expected when you try that?

Body:
I have MongoClient from PyMongo.I do not know how to add a event_listener to an existing MongoClient. This is what I have:

from pymongo import MongoClient, monitoring

class CommandLogger(monitoring.CommandListener):
    def started(self, event):
        logging.info("Command {0.command_name} with request id "
                     "{0.request_id} started on server "
                     "{0.connection_id}".format(event))

def succeeded(self, event):
    logging.info("Command {0.command_name} with request id "
                 "{0.request_id} on server {0.connection_id} "
                 "succeeded in {0.duration_micros} "
                 "microseconds".format(event))

def failed(self, event):
    logging.error("Command {0.command_name} with request id "
                 "{0.request_id} on server {0.connection_id} "
                 "failed in {0.duration_micros} "
                 "microseconds".format(event))

monitoring.register(CommandLogger())

def get_mongo_client():
    ...
    ...
    my_mongo_client = MongoClient(connString)

   # Here, I want to add a event_listener - something like this:
   # my_mongo_client = MongoClient(connString, event_listeners=[CommandLogger()])
    return my_mongo_client

How do I create a mongo_client with a listener and with a connection string (uri)?

Body:
Yes, the code you commented-out is correct:

my_mongo_client = MongoClient(connString, event_listeners=[CommandLogger()])

Is something not working as expected when you try that?


问:
Lifetime of http request
In learning node and working through a few examples, I have a prototype which is working perfectly in test but I am worried that it is working 'by accident'.

The code, (heavily stripped down) boils down to the following

```<code>function CheckValue(){
  var req=http.request({/*some options*/},
                       function (resp){
                       resp.on('data',
                               function (s){
                         /* process the response */
                       })});
  /* Tweak a few headers here. */
  req.end();
}
</code>```

now if I understand the documents correctly - the request is actually sent to the server at the point of req.end() and the callback is not processed until data is received.

So; if there is significant delay between the request being issued and the response being received could the req object be garbage collected? If so would the callback presumably not be called? Or, looking at it from another angle: does node internally maintain any references to http requests until they are complete?

(The code is deliberately written in a fire and forget manner, with req being internally scoped within the function and not saved in any global scope. It would be feasible to store the request in an array and delete the request during resp.on('end',...) but I would rather avoid the complication and overhead.)

答:
Yes. See the documentation:

Class: http.Agent -
  An Agent is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on the keepAlive option.

There is a global Agent instance which is used as the default for all HTTP client requests. So the bottom line is, this Agent instance will handle and store the reference of the request objects, and hence the req object will not be garbage collected.

Title: Lifetime of http request

Body:
In learning node and working through a few examples, I have a prototype which is working perfectly in test but I am worried that it is working 'by accident'.

The code, (heavily stripped down) boils down to the following

function CheckValue(){
  var req=http.request({/*some options*/},
                       function (resp){
                       resp.on('data',
                               function (s){
                         /* process the response */
                       })});
  /* Tweak a few headers here. */
  req.end();
}

now if I understand the documents correctly - the request is actually sent to the server at the point of req.end() and the callback is not processed until data is received.

So; if there is significant delay between the request being issued and the response being received could the req object be garbage collected? If so would the callback presumably not be called? Or, looking at it from another angle: does node internally maintain any references to http requests until they are complete?

(The code is deliberately written in a fire and forget manner, with req being internally scoped within the function and not saved in any global scope. It would be feasible to store the request in an array and delete the request during resp.on('end',...) but I would rather avoid the complication and overhead.)


问:
Many to many relationship in ddd
Is Many to many relationship should always avoided in ddd.

Suppose, I have two entities Publisher and SocialAccount.

1 publisher can register itself to 1 or many socialaccount.

For eg - : Joh is registering himself to twitter, FB.

1 SocialAccount can be associated with many publishers.

But according to business rule, Publisher should register itself to SocialAccount(s), but SocialAccount cannot register publisher, I mean there is no method.

How do  i convert this many to many into one to many

Do in Publisher class.

List<SocialAccount> SocialAccounts.

and same in SocialAccount class. or do i use query to get how many publisher are register to one account.

答:
You should do something like

```<code> List<int> SocialAccountIds { get { ... } }
</code>```

... in your Publisher.

PS. I prefer to use

```<code>List<IdRef<SocialAccount>> SocialAccounts { get { ... } }
</code>```

Where IdRef is basically a type-safe wrapper around int.

ContentLicense: CC BY-SA 2.5

Title: Many to many relationship in ddd

Body:
You should do something like

 List<int> SocialAccountIds { get { ... } }

... in your Publisher.

PS. I prefer to use

List<IdRef<SocialAccount>> SocialAccounts { get { ... } }

Where IdRef is basically a type-safe wrapper around int.


问:
I have inserted an image into pdf digital signature layer n2 using mupdf, but it not showed up
I am using mupdf(git clone at commit 2014/3/5 4:05) to sign a pdf.

And I've already succeeded to sign a digital signature in pdf with function 'pdf_sign_signature'.

Now I'm trying to insert an image into layer n2 of that signature when I'm signing it.

There's a function called 'pdf_set_signature_appearance' in '/source/pdf/pdf-appearance.c'.

I try to add codes below to insert the image:

```<code>image_doc = (image_document *)fz_open_document(ctx, jpgFilePathAndName);
fz_fill_image(dev, image_doc->image, page_ctm, 1.0f);
</code>```

these codes are inserted between:

```<code>rect = annot->rect;
rect.x0 = (rect.x0 + rect.x1)/2.0f;
text = fit_text(ctx, &font_rec, (char *)bufstr, &rect);
fz_fill_text(dev, text, page_ctm, cs, font_rec.da_rec.col, 1.0f);
</code>```

and

```<code>rect = annot->rect;
fz_transform_rect(&rect, page_ctm);
pdf_set_annot_appearance(doc, annot, &rect, dlist);
</code>```

After executing, I got a pdf file like this:

```<code>%PDF-1.4
%Œº·ø¶

1 0 obj
<<
  /Type /Font
  /BaseFont /Helvetica
  /Subtype /Type1
  /Encoding /WinAnsiEncoding
>>
endobj

2 0 obj
<<
  /Length 63
>>
stream
q
BT
36 806 Td
0 -18 Td
/F1 12 Tf
(Hello World!)Tj
0 0 Td
ET
Q
endstream
endobj

3 0 obj
<<
  /Count 1
  /Type /Pages
  /ITXT (5.3.0)
  /Kids [ 4 0 R ]
>>
endobj

4 0 obj
<<
  /Annots 10 0 R
  /Contents 2 0 R
  /MediaBox [ 0 0 595 842 ]
  /Parent 3 0 R
  /Resources <<
    /Font <<
      /F1 1 0 R
    >>
    /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
  >>
  /Type /Page
>>
endobj

5 0 obj
<<
  /AcroForm 8 0 R
  /Metadata 9 0 R
  /Pages 3 0 R
  /Type /Catalog
>>
endobj

6 0 obj
<<
  /CreationDate (D:20120620091727+02'00')
  /ModDate (D:20120804153425+02'00')
  /Producer (iText\256 5.3.0 \2512000-2012 1T3XT BVBA)
>>
endobj

7 0 obj
<<
  /AP <<
    /N 17 0 R
  >>
  /DA (/Helv 0 Tf 0 g)
  /F 4
  /FT /Sig
  /MK <<
  >>
  /P 4 0 R
  /Rect [ 41.3670998 713.710022 237.352997 781.257996 ]
  /Subtype /Widget
  /T (Signature1)
  /Type /Annot
  /V 15 0 R
>>
endobj

8 0 obj
<<
  /DA (/Helv 0 Tf 0 g )
  /DR <<
    /Encoding <<
      /PDFDocEncoding 14 0 R
    >>
    /Font <<
      /Helv 12 0 R
      /ZaDb 13 0 R
    >>
    /XObject <<
      /DSz 11 0 R
    >>
  >>
  /Fields [ 7 0 R ]
  /SigFlags 1
>>
endobj

9 0 obj
<<
  /Length 3304
  /Subtype /XML
  /Type /Metadata
>>
stream
<?xpacket begin="Ôªø" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:08:04        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:xmp="http://ns.adobe.com/xap/1.0/">
         <xmp:CreateDate>2012-06-20T09:17:27+02:00</xmp:CreateDate>
         <xmp:ModifyDate>2012-08-04T15:34:25+02:00</xmp:ModifyDate>
         <xmp:MetadataDate>2012-08-04T15:34:25+02:00</xmp:MetadataDate>
      </rdf:Description>
      <rdf:Description rdf:about=""
            xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
         <pdf:Producer>iText¬Æ 5.3.0 ¬©2000-2012 1T3XT BVBA</pdf:Producer>
      </rdf:Description>
      <rdf:Description rdf:about=""
            xmlns:dc="http://purl.org/dc/elements/1.1/">
         <dc:format>application/pdf</dc:format>
      </rdf:Description>
      <rdf:Description rdf:about=""
            xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">
         <xmpMM:DocumentID>uuid:547fb234-f327-4f3d-8dd1-7b7ea87df336</xmpMM:DocumentID>
         <xmpMM:InstanceID>uuid:72437fbf-7b45-4062-98f1-2b53d3ad86d0</xmpMM:InstanceID>
      </rdf:Description>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?>endstream
endobj

10 0 obj
[ 7 0 R ]
endobj

11 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /Length 67
  /Resources <<
    /XObject <<
      /Img0 16 0 R
    >>
  >>
  /Subtype /Form
  /Type /XObject
  /Matrix [ 1 0 0 1 0 0 ]
>>
stream
1.000000 0.000000 0.000000 -1.000000 0.000000 1.000000 cm
/Img0 Do
endstream
endobj

12 0 obj
<<
  /BaseFont /Helvetica
  /Encoding 14 0 R
  /Name /Helv
  /Subtype /Type1
  /Type /Font
>>
endobj

13 0 obj
<<
  /BaseFont /ZapfDingbats
  /Name /ZaDb
  /Subtype /Type1
  /Type /Font
>>
endobj

14 0 obj
<<
  /Differences [ 24 /breve /caron /circumflex /dotaccent /hungarumlaut
    /ogonek /ring /tilde 39 /quotesingle 96 /grave 128 /bullet
    /dagger /daggerdbl /ellipsis /emdash /endash /florin /fraction
    /guilsinglleft /guilsinglright /minus /perthousand /quotedblbase
    /quotedblleft /quotedblright /quoteleft /quoteright /quotesinglbase
    /trademark /fi /fl /Lslash /OE /Scaron /Ydieresis /Zcaron
    /dotlessi /lslash /oe /scaron /zcaron 160 /Euro 164 /currency
    166 /brokenbar 168 /dieresis /copyright /ordfeminine 172
    /logicalnot /.notdef /registered /macron /degree /plusminus
    /twosuperior /threesuperior /acute /mu 183 /periodcentered
    /cedilla /onesuperior /ordmasculine 188 /onequarter /onehalf
    /threequarters 192 /Agrave /Aacute /Acircumflex /Atilde /Adieresis
    /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis
    /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve
    /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash
    /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls
    /agrave /aacute /acircumflex /atilde /adieresis /aring /ae
    /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave
    /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute
    /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute
    /ucircumflex /udieresis /yacute /thorn /ydieresis ]
  /Type /Encoding
>>
endobj

15 0 obj
<<
  /ByteRange[0 6712 10814 12756]                               /Contents
...
  /Filter /Adobe.PPKLite
  /SubFilter /adbe.pkcs7.detached
>>
endobj

16 0 obj
<<
  /Type /XObject
  /Subtype /Image
  /Width 400
  /Height 332
  /ColorSpace /DeviceRGB
  /BitsPerComponent 8
  /Length 11097
>>
stream
...
endstream
endobj

17 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /FormType 1
  /Length 7
  /Matrix [ 1 0 0 1 0 0 ]
  /Resources <<
    /ProcSet [ /PDF /Text ]
    /XObject <<
      /FRM 18 0 R
    >>
  >>
  /Subtype /Form
  /Type /XObject
>>
stream
/FRM Doendstream
endobj

18 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /FormType 1
  /Length 51
  /Matrix [ 1 0 0 1 0 0 ]
  /Resources <<
    /ProcSet [ /PDF /Text ]
    /XObject <<
      /n0 19 0 R
      /n2 11 0 R
    >>
  >>
  /Subtype /Form
  /Type /XObject
>>
stream
q 1 0 0 1 0 0 cm /n0 Do Q q 1 0 0 1 0 0 cm /n2 Do Qendstream
endobj

19 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /FormType 1
  /Length 9
  /Matrix [ 1 0 0 1 0 0 ]
  /Resources <<
    /ProcSet [ /PDF /Text ]
  >>
  /Subtype /Form
  /Type /XObject
>>
stream
% DSBlankendstream
endobj

xref
0 20
0000000000 65536 f
0000000017 00000 n
0000000123 00000 n
0000000238 00000 n
0000000320 00000 n
0000000544 00000 n
0000000634 00000 n
0000000790 00000 n
0000001026 00000 n
0000001272 00000 n
0000004664 00000 n
0000004691 00000 n
0000004990 00000 n
0000005101 00000 n
0000005196 00000 n
0000006628 00000 n
0000010882 00000 n
0000022144 00000 n
0000022423 00000 n
0000022763 00000 n

trailer
<<
  /Size 20
  /Info 6 0 R
  /Root 5 0 R
  /ID [ <D0151A7ADF2410CF3E72A04B9CB83452> <FA2030FCC5A66742887F23E51DEC5875> ]
>>

startxref
23003
%%EOF
</code>```

It seems to be correct, since there's /n2 11 0 R in 18 0 obj and /Img0 16 0 R in 11 0 obj and 16 0 obj looks like a well-formed Image XObject.

But the image doesn't show up when I using pdf reader to open this pdf.

Could someone please give me a clue about what's wrong with this pdf file, and how to insert the image correctly.

Thanks a lot.

ps.

signed_with_image_only.pdf

signed_with_text_and_image.pdf

signed_with_image_only.pdf is the pdf I've added '\n' before 'endstream'. You can see image doesn't show up in the form which is below 'Hello World!'.

signed_with_text_and_image.pdf is pretty much the same as signed_with_image_only.pdf, but I put some text in layer n2 to show you text insertion is ok. The same image is also inserted, and it also not showed up.

答:
I don't know if it's the text formatting but you have a number of streams (objects 17, 18 and 19) where the "endstream" that denotes the end of the stream data is not being written correctly. The "endstream" should be on a line of its own, and a PDF file requires whitespace between tokens and operators. Therefore, things like

```<code>/FRM Doendstream
</code>```

are invalid syntax, they should be written like

```<code>/FRM Do
endstream
</code>```

For images, the current transform matrix must transform from the 1 unit square that images are specified in, to the desired size in PDF units. You're using a transformation matrix of [1 0 0 -1 0 1] to position and scale the image XObject, which will not give your desired result. Typically, for an unrotated image you'll want to use something like [width 0 0 height Xpos Ypos]. Also, I always recommend enclosing image XObject invocation in a graphic state save/restore so that the CTM required can be popped off the graphic state stack.

Finally, looking at the file in Dropbox your image is damaged. It specifies a width of 400 rasters and a height of 332 rasters - in RGB format, the image should have a length of 398,400 but only has a length of 11097. This is way too short for this image data stream. It looks like this is compressed data, in DCT compressed format. For this to render properly you need to specify that it is compressed and in the format, e.g. add

```<code>/Filter /DCTDecode
</code>```

to the image dictionary.

Body:
I am using mupdf(git clone at commit 2014/3/5 4:05) to sign a pdf.

And I've already succeeded to sign a digital signature in pdf with function 'pdf_sign_signature'.

Now I'm trying to insert an image into layer n2 of that signature when I'm signing it.

There's a function called 'pdf_set_signature_appearance' in '/source/pdf/pdf-appearance.c'.

I try to add codes below to insert the image:

image_doc = (image_document *)fz_open_document(ctx, jpgFilePathAndName);
fz_fill_image(dev, image_doc->image, page_ctm, 1.0f);

these codes are inserted between:

rect = annot->rect;
rect.x0 = (rect.x0 + rect.x1)/2.0f;
text = fit_text(ctx, &font_rec, (char *)bufstr, &rect);
fz_fill_text(dev, text, page_ctm, cs, font_rec.da_rec.col, 1.0f);

and

rect = annot->rect;
fz_transform_rect(&rect, page_ctm);
pdf_set_annot_appearance(doc, annot, &rect, dlist);

After executing, I got a pdf file like this:

%PDF-1.4
%Œº·ø¶

1 0 obj
<<
  /Type /Font
  /BaseFont /Helvetica
  /Subtype /Type1
  /Encoding /WinAnsiEncoding
>>
endobj

2 0 obj
<<
  /Length 63
>>
stream
q
BT
36 806 Td
0 -18 Td
/F1 12 Tf
(Hello World!)Tj
0 0 Td
ET
Q
endstream
endobj

3 0 obj
<<
  /Count 1
  /Type /Pages
  /ITXT (5.3.0)
  /Kids [ 4 0 R ]
>>
endobj

4 0 obj
<<
  /Annots 10 0 R
  /Contents 2 0 R
  /MediaBox [ 0 0 595 842 ]
  /Parent 3 0 R
  /Resources <<
    /Font <<
      /F1 1 0 R
    >>
    /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
  >>
  /Type /Page
>>
endobj

5 0 obj
<<
  /AcroForm 8 0 R
  /Metadata 9 0 R
  /Pages 3 0 R
  /Type /Catalog
>>
endobj

6 0 obj
<<
  /CreationDate (D:20120620091727+02'00')
  /ModDate (D:20120804153425+02'00')
  /Producer (iText\256 5.3.0 \2512000-2012 1T3XT BVBA)
>>
endobj

7 0 obj
<<
  /AP <<
    /N 17 0 R
  >>
  /DA (/Helv 0 Tf 0 g)
  /F 4
  /FT /Sig
  /MK <<
  >>
  /P 4 0 R
  /Rect [ 41.3670998 713.710022 237.352997 781.257996 ]
  /Subtype /Widget
  /T (Signature1)
  /Type /Annot
  /V 15 0 R
>>
endobj

8 0 obj
<<
  /DA (/Helv 0 Tf 0 g )
  /DR <<
    /Encoding <<
      /PDFDocEncoding 14 0 R
    >>
    /Font <<
      /Helv 12 0 R
      /ZaDb 13 0 R
    >>
    /XObject <<
      /DSz 11 0 R
    >>
  >>
  /Fields [ 7 0 R ]
  /SigFlags 1
>>
endobj

9 0 obj
<<
  /Length 3304
  /Subtype /XML
  /Type /Metadata
>>
stream
<?xpacket begin="Ôªø" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:08:04        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:xmp="http://ns.adobe.com/xap/1.0/">
         <xmp:CreateDate>2012-06-20T09:17:27+02:00</xmp:CreateDate>
         <xmp:ModifyDate>2012-08-04T15:34:25+02:00</xmp:ModifyDate>
         <xmp:MetadataDate>2012-08-04T15:34:25+02:00</xmp:MetadataDate>
      </rdf:Description>
      <rdf:Description rdf:about=""
            xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
         <pdf:Producer>iText¬Æ 5.3.0 ¬©2000-2012 1T3XT BVBA</pdf:Producer>
      </rdf:Description>
      <rdf:Description rdf:about=""
            xmlns:dc="http://purl.org/dc/elements/1.1/">
         <dc:format>application/pdf</dc:format>
      </rdf:Description>
      <rdf:Description rdf:about=""
            xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">
         <xmpMM:DocumentID>uuid:547fb234-f327-4f3d-8dd1-7b7ea87df336</xmpMM:DocumentID>
         <xmpMM:InstanceID>uuid:72437fbf-7b45-4062-98f1-2b53d3ad86d0</xmpMM:InstanceID>
      </rdf:Description>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?>endstream
endobj

10 0 obj
[ 7 0 R ]
endobj

11 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /Length 67
  /Resources <<
    /XObject <<
      /Img0 16 0 R
    >>
  >>
  /Subtype /Form
  /Type /XObject
  /Matrix [ 1 0 0 1 0 0 ]
>>
stream
1.000000 0.000000 0.000000 -1.000000 0.000000 1.000000 cm
/Img0 Do
endstream
endobj

12 0 obj
<<
  /BaseFont /Helvetica
  /Encoding 14 0 R
  /Name /Helv
  /Subtype /Type1
  /Type /Font
>>
endobj

13 0 obj
<<
  /BaseFont /ZapfDingbats
  /Name /ZaDb
  /Subtype /Type1
  /Type /Font
>>
endobj

14 0 obj
<<
  /Differences [ 24 /breve /caron /circumflex /dotaccent /hungarumlaut
    /ogonek /ring /tilde 39 /quotesingle 96 /grave 128 /bullet
    /dagger /daggerdbl /ellipsis /emdash /endash /florin /fraction
    /guilsinglleft /guilsinglright /minus /perthousand /quotedblbase
    /quotedblleft /quotedblright /quoteleft /quoteright /quotesinglbase
    /trademark /fi /fl /Lslash /OE /Scaron /Ydieresis /Zcaron
    /dotlessi /lslash /oe /scaron /zcaron 160 /Euro 164 /currency
    166 /brokenbar 168 /dieresis /copyright /ordfeminine 172
    /logicalnot /.notdef /registered /macron /degree /plusminus
    /twosuperior /threesuperior /acute /mu 183 /periodcentered
    /cedilla /onesuperior /ordmasculine 188 /onequarter /onehalf
    /threequarters 192 /Agrave /Aacute /Acircumflex /Atilde /Adieresis
    /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis
    /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve
    /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash
    /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls
    /agrave /aacute /acircumflex /atilde /adieresis /aring /ae
    /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave
    /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute
    /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute
    /ucircumflex /udieresis /yacute /thorn /ydieresis ]
  /Type /Encoding
>>
endobj

15 0 obj
<<
  /ByteRange[0 6712 10814 12756]                               /Contents
...
  /Filter /Adobe.PPKLite
  /SubFilter /adbe.pkcs7.detached
>>
endobj

16 0 obj
<<
  /Type /XObject
  /Subtype /Image
  /Width 400
  /Height 332
  /ColorSpace /DeviceRGB
  /BitsPerComponent 8
  /Length 11097
>>
stream
...
endstream
endobj

17 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /FormType 1
  /Length 7
  /Matrix [ 1 0 0 1 0 0 ]
  /Resources <<
    /ProcSet [ /PDF /Text ]
    /XObject <<
      /FRM 18 0 R
    >>
  >>
  /Subtype /Form
  /Type /XObject
>>
stream
/FRM Doendstream
endobj

18 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /FormType 1
  /Length 51
  /Matrix [ 1 0 0 1 0 0 ]
  /Resources <<
    /ProcSet [ /PDF /Text ]
    /XObject <<
      /n0 19 0 R
      /n2 11 0 R
    >>
  >>
  /Subtype /Form
  /Type /XObject
>>
stream
q 1 0 0 1 0 0 cm /n0 Do Q q 1 0 0 1 0 0 cm /n2 Do Qendstream
endobj

19 0 obj
<<
  /BBox [ 41.3670998 713.710022 237.352997 781.257996 ]
  /FormType 1
  /Length 9
  /Matrix [ 1 0 0 1 0 0 ]
  /Resources <<
    /ProcSet [ /PDF /Text ]
  >>
  /Subtype /Form
  /Type /XObject
>>
stream
% DSBlankendstream
endobj

xref
0 20
0000000000 65536 f
0000000017 00000 n
0000000123 00000 n
0000000238 00000 n
0000000320 00000 n
0000000544 00000 n
0000000634 00000 n
0000000790 00000 n
0000001026 00000 n
0000001272 00000 n
0000004664 00000 n
0000004691 00000 n
0000004990 00000 n
0000005101 00000 n
0000005196 00000 n
0000006628 00000 n
0000010882 00000 n
0000022144 00000 n
0000022423 00000 n
0000022763 00000 n

trailer
<<
  /Size 20
  /Info 6 0 R
  /Root 5 0 R
  /ID [ <D0151A7ADF2410CF3E72A04B9CB83452> <FA2030FCC5A66742887F23E51DEC5875> ]
>>

startxref
23003
%%EOF

It seems to be correct, since there's /n2 11 0 R in 18 0 obj and /Img0 16 0 R in 11 0 obj and 16 0 obj looks like a well-formed Image XObject.

But the image doesn't show up when I using pdf reader to open this pdf.

Could someone please give me a clue about what's wrong with this pdf file, and how to insert the image correctly.

Thanks a lot.

ps.

signed_with_image_only.pdf

signed_with_text_and_image.pdf

signed_with_image_only.pdf is the pdf I've added '\n' before 'endstream'. You can see image doesn't show up in the form which is below 'Hello World!'.

signed_with_text_and_image.pdf is pretty much the same as signed_with_image_only.pdf, but I put some text in layer n2 to show you text insertion is ok. The same image is also inserted, and it also not showed up.

Body:
I don't know if it's the text formatting but you have a number of streams (objects 17, 18 and 19) where the "endstream" that denotes the end of the stream data is not being written correctly. The "endstream" should be on a line of its own, and a PDF file requires whitespace between tokens and operators. Therefore, things like

/FRM Doendstream

are invalid syntax, they should be written like

/FRM Do
endstream

For images, the current transform matrix must transform from the 1 unit square that images are specified in, to the desired size in PDF units. You're using a transformation matrix of [1 0 0 -1 0 1] to position and scale the image XObject, which will not give your desired result. Typically, for an unrotated image you'll want to use something like [width 0 0 height Xpos Ypos]. Also, I always recommend enclosing image XObject invocation in a graphic state save/restore so that the CTM required can be popped off the graphic state stack.

Finally, looking at the file in Dropbox your image is damaged. It specifies a width of 400 rasters and a height of 332 rasters - in RGB format, the image should have a length of 398,400 but only has a length of 11097. This is way too short for this image data stream. It looks like this is compressed data, in DCT compressed format. For this to render properly you need to specify that it is compressed and in the format, e.g. add

/Filter /DCTDecode

to the image dictionary.


问:
Try-Catch with fluent expressions
This LINQ query expression fails with Win32Exception "Access is denied":

```<code>Process.GetProcesses().Select(p => p.MainModule.FileName)
</code>```

And this fails with IOException "The device is not ready":

```<code>DriveInfo.GetDrives().Select(d => d.VolumeLabel)
</code>```

What is the best way to filter out inaccessible objects and avoid exceptions?

答:
Your answer is the correct one. You can of course try to hide the checking logic inside an extension method.

```<code>public static IEnumerable<TElement> WhereSafe<TElement, TInner>(this IEnumerable<TElement> sequence, Func<TElement, TInner> selector)
{
    foreach (var element in sequence)
    {
        try { selector(element); }
        catch { continue; }
        yield return element;
    }
}

Process
    .GetProcesses()
    .WhereSafe(p => p.MainModule)
    .Select(p => p.MainModule.FileName)
</code>```

Or better so:

```<code>public static IEnumerable<TInner> TrySelect<TElement, TInner>(this IEnumerable<TElement> sequence, Func<TElement, TInner> selector)
{
    TInner current = default(TInner);
    foreach (var element in sequence)
    {
        try { current = selector(element); }
        catch { continue; }
        yield return current;
    }
}

Process
   .GetProcesses()
   .TrySelect(p => p.MainModule.FileName)
</code>```

Title: Try-Catch with fluent expressions

Body:
This LINQ query expression fails with Win32Exception "Access is denied":

Process.GetProcesses().Select(p => p.MainModule.FileName)

And this fails with IOException "The device is not ready":

DriveInfo.GetDrives().Select(d => d.VolumeLabel)

What is the best way to filter out inaccessible objects and avoid exceptions?

Body:
Your answer is the correct one. You can of course try to hide the checking logic inside an extension method.

public static IEnumerable<TElement> WhereSafe<TElement, TInner>(this IEnumerable<TElement> sequence, Func<TElement, TInner> selector)
{
    foreach (var element in sequence)
    {
        try { selector(element); }
        catch { continue; }
        yield return element;
    }
}

Process
    .GetProcesses()
    .WhereSafe(p => p.MainModule)
    .Select(p => p.MainModule.FileName)

Or better so:

public static IEnumerable<TInner> TrySelect<TElement, TInner>(this IEnumerable<TElement> sequence, Func<TElement, TInner> selector)
{
    TInner current = default(TInner);
    foreach (var element in sequence)
    {
        try { current = selector(element); }
        catch { continue; }
        yield return current;
    }
}

Process
   .GetProcesses()
   .TrySelect(p => p.MainModule.FileName)


问:
What is blocking the checking of the checkbox?
If you click the second orange "Заказ в 1 клик" button at this page you'll see the form with the checkbox at the bottom. How to figure out what script is blocking the checking of this chackbox?
May be it's due to this script:

```<code>$("#contactForm_oneclick").click( function(e){
        if(e.target.getAttribute('class') != 'addtocart_button' || e.target.getAttribute('id') == 'agree') {
            return false;
        }
    })
</code>```

but how to change it correct?

答:
Instead of returning false try to stop event propagation after it was handled.

```<code>$("#contactForm_oneclick").click( function(e){
    if(e.target.getAttribute('class') != 'addtocart_button' || e.target.getAttribute('id') == 'agree') {
        e.stopPropagation();
    }
})
</code>```

That tells the browser not to call click event handlers for the parents of "contactForm_oneclick" div tag. For more information about how event bubbling works, check out this https://en.wikipedia.org/wiki/Event_bubbling

Body:
If you click the second orange "Заказ в 1 клик" button at this page you'll see the form with the checkbox at the bottom. How to figure out what script is blocking the checking of this chackbox?
May be it's due to this script:

$("#contactForm_oneclick").click( function(e){
        if(e.target.getAttribute('class') != 'addtocart_button' || e.target.getAttribute('id') == 'agree') {
            return false;
        }
    })

but how to change it correct?

Body:
Instead of returning false try to stop event propagation after it was handled.

$("#contactForm_oneclick").click( function(e){
    if(e.target.getAttribute('class') != 'addtocart_button' || e.target.getAttribute('id') == 'agree') {
        e.stopPropagation();
    }
})

That tells the browser not to call click event handlers for the parents of "contactForm_oneclick" div tag. For more information about how event bubbling works, check out this https://en.wikipedia.org/wiki/Event_bubbling


问:
Event Timeout At Kaa-Client
How long does kaa-client stores the event on the device that it has to send to the other clients, in case it is not able to successfully deliver in several attempts during the kaa-node server outage.

Is there a way I can set timeout in kaa-client untill it has to retry to send event on failure attempts?

Thanks
-Rizwan

答:
The behaviour of the Kaa SDK on the Kaa client side in case of Operations server outage or inability to communicate depends on the failover model used on the client side. The default failover mechanism depends on the Kaa SDK type and platform.

See Kaa Documentation for more information.

Title: Event Timeout At Kaa-Client


问:
How Do I Create a Account Email Confirmation in Php?
I am trying to send the user an email with a link (like many sites do) and when they click this link, their account will be activated. How exactly would I do this in Php? </p>

答:
I do the following.

Collect their email address and password

Store their password as a protected hash.  I'm using PHP 7 so I use
password_hash($user_password, PASSWORD_DEFAULT);

Create and store a unique confirmation ID.  I'm anal and paranoid, so I create long strings.  In this case, 64 characters (32 bytes, bin2hex = 64 characters).
$confirm_code = bin2hex(random_bytes(32));

Email the user the confirmation link built using $confirm_code.

When the user clicks the link, set a database flag (e.g., "active_user") to indicate confirmation is complete.  I do not delete the confirmation code.

OK, remember that I'm anal and paranoid.  The backend does not delete the confirmation code and every new confirmation code is checked against all previous confirmation codes to ensure it really is unique.  Why?  So people can't happenstantially use their email link at a later date to confirm an account that isn't actually theirs and to guarantee no one gets a confirmation code that was issued to but possibly not used by someone else.  (Remember, nothing is ever actually "unique" or "random" in the world of computers.  If you don't check, you don't know.)

Also, you should NEVER automatically log someone in from their confirmation link.  That's a huge security violation.  Anyone could click the link before activation and suddenly they have full access to the account.  Always force users to log in after confirmation.


问:
GZipOutputStream & appengine
I'm writing a java servlet on AppEngine. This servlet generates png images. I would like to "gzip" the response. I do it this way:

```<code>resp.setHeader("Content-Encoding","gzip");
resp.setContentType("image/png");

// ... png generation ...

GZIPOutputStream gzos = new GZIPOutputStream(resp.getOutputStream());
gzos.write(myPNGdata);
gzos.close();
</code>```

But: in development server, it's ok, the png displays fine and the response is well gzipped. Then I test on production server (AppEngine) and all I get is a "broken" image...

What could be wrong with my code? Is it related to dev/prod environment?

Off course, If I don't gzip the output, it's ok in both environments.

Thanks for any help.

Edit: I tried this too:

```<code>GZIPOutputStream gzos = new GZIPOutputStream(resp.getOutputStream());
gzos.write(ImagesServiceFactory.makeImage(readImage("somePicture.png")).getImageData());
gzos.flush();
gzos.finish();
gzos.close();
</code>```

and it doesn't work either.

Edit 2: in fact, the response is gzip. I fetched the servlet with "curl theUrl > tmp.gz", then I gunzip "tmp.gz", and the image is fine. But no browser can display it correctly :( What's wrong with my gzip?

答: Check the size of your downloaded image. If it is smaller then you expecting, most likely you need to flush the stream before closing.</p>

Title: GZipOutputStream & appengine

Body:
I'm writing a java servlet on AppEngine. This servlet generates png images. I would like to "gzip" the response. I do it this way:

resp.setHeader("Content-Encoding","gzip");
resp.setContentType("image/png");

// ... png generation ...

GZIPOutputStream gzos = new GZIPOutputStream(resp.getOutputStream());
gzos.write(myPNGdata);
gzos.close();

But: in development server, it's ok, the png displays fine and the response is well gzipped. Then I test on production server (AppEngine) and all I get is a "broken" image...

What could be wrong with my code? Is it related to dev/prod environment?

Off course, If I don't gzip the output, it's ok in both environments.

Thanks for any help.

Edit: I tried this too:

GZIPOutputStream gzos = new GZIPOutputStream(resp.getOutputStream());
gzos.write(ImagesServiceFactory.makeImage(readImage("somePicture.png")).getImageData());
gzos.flush();
gzos.finish();
gzos.close();

and it doesn't work either.

Edit 2: in fact, the response is gzip. I fetched the servlet with "curl theUrl > tmp.gz", then I gunzip "tmp.gz", and the image is fine. But no browser can display it correctly :( What's wrong with my gzip?


问:
Tornado end points
I am experimenting with Tornado and wasnt sure how to support two different REST API end points. Say I want to support "/" and "/Hello". Based on initial documentation I came up with this, do I need to create a handler class for each end point?</p>

```<code>import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    self.write("Hello, Tornado")

class SecondHandler(tornado.web.RequestHandler):
  def get(self):
    self.write("<em>Hello, Second Handler!</em>")

def make_app():
  return tornado.web.Application([
    (r"/", MainHandler),
    (r"/Hello", SecondHandler)
  ])

if __name__ == "__main__":
  app = make_app()
  app.listen(8888)
  tornado.ioloop.IOLoop.current().start()
</code>```

答: Yes, that is the correct way to implement multiple endpoints.</p>

Title: Tornado end points

Body:
I am experimenting with Tornado and wasnt sure how to support two different REST API end points. Say I want to support "/" and "/Hello". Based on initial documentation I came up with this, do I need to create a handler class for each end point?

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    self.write("Hello, Tornado")

class SecondHandler(tornado.web.RequestHandler):
  def get(self):
    self.write("Hello, Second Handler!")

def make_app():
  return tornado.web.Application([
    (r"/", MainHandler),
    (r"/Hello", SecondHandler)
  ])

if __name__ == "__main__":
  app = make_app()
  app.listen(8888)
  tornado.ioloop.IOLoop.current().start()


问:
Parsing JSON off the main thread using RxJava
I need to parse a few JSON files on startup and populate a database with their data. On app startup, a splash screen is shown while the files are parsed.

I would like to perform all parsing off the main thread, and allow loading animations to progress smoothly.

I have been able to create an Observable using RxJava's Observable.create() method. The current code is shown below:

```<code>Observable.create(new Observable.OnSubscribe<Object>() {
    @Override
    public void call(Subscriber<? super Object> subscriber) {
        parseBundles();
        parsePhrases();
    }
})
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Object>() {
    @Override
    public void onCompleted() {
        startActivity(new Intent(SplashActivity.this, HomeActivity.class),
            ActivityOptionsCompat.makeCustomAnimation(SplashActivity.this,
            android.R.anim.fade_in, android.R.anim.fade_out).toBundle());
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
    }

    @Override
    public void onNext(Object o) {

    }
});
</code>```

This successfully makes the parseBundles() and parsePhrases() methods run on an io thread. For some context, these two methods simply load the local .json files using an InputStream and throw the .json into a String variable, where the relevant JSONObjects are then pulled out of, and the data saved to a DB.

The issue, however, is that onCompleted() is never called. Both the parseBundles() and parsePhrases() methods are plain old methods, without any Rx code. As I understand it, I need to modify them to properly emit something when finished.

How can I modify this code to work as described? Please note, this is currently written using RxJava 1, however answers using RxJava 2 would be acceptable as well.

答:
Your Observable is not properly constructed, you need to drive the async process yourself:

```<code>Observable.create(new Observable.OnSubscribe<Object>() {
  @Override
  public void call(Subscriber<? super Object> subscriber) {
    parseBundles();
    parsePhrases();
    subscriber.onCompleted();
  }
})
</code>```

As an aside, I hate Observable.create - it's at too low level and too many people will get it wrong the first two-three times; never understood why tutorials start with that...

Body:
I need to parse a few JSON files on startup and populate a database with their data. On app startup, a splash screen is shown while the files are parsed.

I would like to perform all parsing off the main thread, and allow loading animations to progress smoothly.

I have been able to create an Observable using RxJava's Observable.create() method. The current code is shown below:

Observable.create(new Observable.OnSubscribe<Object>() {
    @Override
    public void call(Subscriber<? super Object> subscriber) {
        parseBundles();
        parsePhrases();
    }
})
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Object>() {
    @Override
    public void onCompleted() {
        startActivity(new Intent(SplashActivity.this, HomeActivity.class),
            ActivityOptionsCompat.makeCustomAnimation(SplashActivity.this,
            android.R.anim.fade_in, android.R.anim.fade_out).toBundle());
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
    }

    @Override
    public void onNext(Object o) {

    }
});

This successfully makes the parseBundles() and parsePhrases() methods run on an io thread. For some context, these two methods simply load the local .json files using an InputStream and throw the .json into a String variable, where the relevant JSONObjects are then pulled out of, and the data saved to a DB.

The issue, however, is that onCompleted() is never called. Both the parseBundles() and parsePhrases() methods are plain old methods, without any Rx code. As I understand it, I need to modify them to properly emit something when finished.

How can I modify this code to work as described? Please note, this is currently written using RxJava 1, however answers using RxJava 2 would be acceptable as well.

Body:
Your Observable is not properly constructed, you need to drive the async process yourself:

Observable.create(new Observable.OnSubscribe<Object>() {
  @Override
  public void call(Subscriber<? super Object> subscriber) {
    parseBundles();
    parsePhrases();
    subscriber.onCompleted();
  }
})

As an aside, I hate Observable.create - it's at too low level and too many people will get it wrong the first two-three times; never understood why tutorials start with that...


问:
How to import and Connect and listen to a web socket in React Native
In the onMasterClicked method I want to connect and send data to server with a web-socket.

I would prefer to use native web socket library from react-native, I can also use socket.io client but that was not working for me. I do not need server side code in the app, server is cloud.

Just want to know how to connect to server with a web-socket and send data, and listens to it when ever it sends data to the application

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TouchableOpacity } from 'react-native';
import Card from '../common/Card';
import { onMasterClicked } from '../../actions';

class MasterCard extends Component {

     getMasterUnit() {
        return this.props.masterUnit;
    }

    masterClicked() {
        const cardNav = this.props.masterCardNav;

        this.props.onMasterClicked(this.getMasterUnit());

        cardNav('Room', {
            id: this.getMasterUnit().id,
            title: this.getMasterUnit().title,
        });
    }

    render() {

        return (
        <TouchableOpacity onPress={this.masterClicked.bind(this)}>
        <Card>
        <View style={styles.parentContainer}>
        <Text style={styles.masterNameTextStyles}> { this.getMasterUnit().title } </Text>
        <Text style={styles.arrowTextStyle}> > </Text>
        </View>
        </Card>
        </TouchableOpacity>
        );
    }
}

const styles = {

    parentContainer: {
        flexDirection: 'row',
        flex: 1,
        alignItems: 'center',
        height: 50
    },

    masterNameTextStyle: {
        flex: 1,
        textAlign: 'left',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    },

    arrowTextStyle: {
        flex: 1,
        textAlign: 'right',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    }
};

export default connect(null, { onMasterClicked })(MasterCard);
</code>```

答:
Here's how I did it:

I created a WSService.js file to contain all of the web socket logic. That file just had a class in it with a constructor that set up all of the listeners:

```<code>class WSService {
    constructor() {
        this.ws = new WebSocket('ws://localhost:3001');

        this.ws.onopen = (arg) => {
            // connection opened
        };
        this.ws.onmessage = (e) => {
            // a message was received
        };
        this.ws.onerror = (e) => {
            // an error occurred
        };
        this.ws.onclose = this.logout; // function implemented elsewhere
    }
}
export default new WSService();
</code>```

Note how it instantiates the service at the bottom and exports it.

The class contained additional functions that could be used by the actions to send specific messages (for logging in or out, for example).

I'm using Redux so I imported that into my actions file:

import WSService from '../services/WSService';

My actions call the service as necessary.  The service also has access to the store so it dispatches actions when it receives messages.

Overall, it was much easier than I anticipated.

Full code here:
https://github.com/SpaceAppsReno/higher-ground/tree/master/controller

Body:
In the onMasterClicked method I want to connect and send data to server with a web-socket.

I would prefer to use native web socket library from react-native, I can also use socket.io client but that was not working for me. I do not need server side code in the app, server is cloud.

Just want to know how to connect to server with a web-socket and send data, and listens to it when ever it sends data to the application

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TouchableOpacity } from 'react-native';
import Card from '../common/Card';
import { onMasterClicked } from '../../actions';

class MasterCard extends Component {

     getMasterUnit() {
        return this.props.masterUnit;
    }

    masterClicked() {
        const cardNav = this.props.masterCardNav;

        this.props.onMasterClicked(this.getMasterUnit());

        cardNav('Room', {
            id: this.getMasterUnit().id,
            title: this.getMasterUnit().title,
        });
    }

    render() {

        return (
        <TouchableOpacity onPress={this.masterClicked.bind(this)}>
        <Card>
        <View style={styles.parentContainer}>
        <Text style={styles.masterNameTextStyles}> { this.getMasterUnit().title } </Text>
        <Text style={styles.arrowTextStyle}> > </Text>
        </View>
        </Card>
        </TouchableOpacity>
        );
    }
}

const styles = {

    parentContainer: {
        flexDirection: 'row',
        flex: 1,
        alignItems: 'center',
        height: 50
    },

    masterNameTextStyle: {
        flex: 1,
        textAlign: 'left',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    },

    arrowTextStyle: {
        flex: 1,
        textAlign: 'right',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    }
};

export default connect(null, { onMasterClicked })(MasterCard);

Body:
Here's how I did it:

I created a WSService.js file to contain all of the web socket logic. That file just had a class in it with a constructor that set up all of the listeners:

class WSService {
    constructor() {
        this.ws = new WebSocket('ws://localhost:3001');

        this.ws.onopen = (arg) => {
            // connection opened
        };
        this.ws.onmessage = (e) => {
            // a message was received
        };
        this.ws.onerror = (e) => {
            // an error occurred
        };
        this.ws.onclose = this.logout; // function implemented elsewhere
    }
}
export default new WSService();

Note how it instantiates the service at the bottom and exports it.

The class contained additional functions that could be used by the actions to send specific messages (for logging in or out, for example).

I'm using Redux so I imported that into my actions file:

import WSService from '../services/WSService';

My actions call the service as necessary.  The service also has access to the store so it dispatches actions when it receives messages.

Overall, it was much easier than I anticipated.

Full code here:
https://github.com/SpaceAppsReno/higher-ground/tree/master/controller


问:
Determine the complexity
Let say i have given an algorithmen X, which gets as an input an integer n.

Now consider  the X needs for  all input n which are smaller then x(  x is a fixed arbitrarily natural number)
 O(n2) steps. But for every input n > x it takes n steps.

Question: What is the (worstcase)runtime complexity of X?

Answer: The (worstcase) runtime complexity of X is O(n). For every fixed x, we can find numbers n such that n>(x2) and the (worst case) runtime for all n with n>(x2) is O(n). I am not sure if my answer is correct.

Edit: for better understanding T(n, x) \in if n <= x then O(n^2) else O(n). What is the worstcase runtime complexity?

答:
By definition, all that matters for Big-Oh (or any complexity bound) is behavior for all values of n above some fixed bound. Your algorithm is eventually linear in n and so the runtime is bound by O(n).

Note that if your algorithm accepts an input of n, what that actually means is that is accepting a representation of n in some number system. On typical computers this will be a 2-bit (binary) representation. A base-k (k-ary) representation will take log_k(n) digits, rounded up. So if you are in a binary system and the number is 9, the representation is 1001 and it takes 4 bits (log base 2 of 9 is greater than 3 but less than 2, so four bits).

Given this, your input size isn't actually n but log_2(n) (assuming binary) and if your algorithm takes time n, the runtime w.r.t. the input size is actually exponential (since n = 2^(log_2 n)).

This is a minor nitpick but one that might make you think about algorithms differently. The distinction disappears if instead of taking a number you take a list with n elements in it.

Title: Determine the complexity


问:
Selenium 'browserName was not a boolean' InvalidArgumentException, unable to solve
I'm facing a problem making automatic tests with Selenium on Firefox.
My configuration is the following:

OS:          Windows 7

Browser:     Firefox 53.0.3 (tried both x32 and x64 versions)

Selenium:    3.4.0

Geckodriver: 0.16.1

Running the following code

```<code>DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability("browserName", DesiredCapabilities.firefox().getBrowserName());
dc.setCapability("browserVersion", "");
dc.setCapability("platformName", "WINDOWS");
dc.setCapability("firefox_binary", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
dc.setCapability("acceptInsecureCerts", true);
dc.setCapability("marionette", true);

System.out.println("BrowserName : " + dc.getCapability("browserName"));

driver = new FirefoxDriver(dc);
</code>```

I systematically get the following exception

```<code>org.openqa.selenium.InvalidArgumentException: browserName was not a boolean
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: '<ComputerName>', ip: '<IpAddress>', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
Driver info: driver.version: FirefoxDriver
remote stacktrace: stack backtrace:
   0:   0x47f1a6 - <no info>
   1:   0x437327 - <no info>
   2:   0x42bd8c - <no info>
   3:   0x437ded - <no info>
   4:   0x41a7b3 - <no info>
   5:   0x40570c - <no info>
   6:   0x692906 - <no info>
   7:   0x413838 - <no info>
   8:   0x68d401 - <no info>
   9: 0x7573336a - BaseThreadInitThunk
  10: 0x774b9902 - RtlInitializeExceptionChain
</code>```

Looking at the Mozilla source code, I found that raised exception should derive from the following file

```<code>gecko-dev-master\third_party\rust\webdriver\src\capabilities.rs
</code>```

in these lines

```<code>        for (key, value) in capabilities.iter() {
        match &**key {
            "acceptInsecureCerts" => if !value.is_boolean() {
                    return Err(WebDriverError::new(ErrorStatus::InvalidArgument,
                                                   "acceptInsecureCerts was not a boolean"))
                },
            x @ "browserName" |
            x @ "browserVersion" |
            x @ "platformName" => if !value.is_string() {
                    return Err(WebDriverError::new(ErrorStatus::InvalidArgument,
                                                   format!("{} was not a boolean", x)))
                },
</code>```

To be sure that browserName capability was correctly set, I added the println before creating the FirefoxDriver object.
As stated before, I tried the code with both Firefox 32 bits and 64 bits versions without any different result.

Whereas Chrome and chromedriver work fine.

May any of you suggest how to solve this issue?

Thanks in advance and best regards.

答:
Set the browser name to "firefox" as lined out in the official documentation.</p>

```<code>dc.setCapability("browserName", "firefox");
</code>```

Body:
I'm facing a problem making automatic tests with Selenium on Firefox.
My configuration is the following:

OS:          Windows 7

Browser:     Firefox 53.0.3 (tried both x32 and x64 versions)

Selenium:    3.4.0

Geckodriver: 0.16.1

Running the following code

DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability("browserName", DesiredCapabilities.firefox().getBrowserName());
dc.setCapability("browserVersion", "");
dc.setCapability("platformName", "WINDOWS");
dc.setCapability("firefox_binary", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
dc.setCapability("acceptInsecureCerts", true);
dc.setCapability("marionette", true);

System.out.println("BrowserName : " + dc.getCapability("browserName"));

driver = new FirefoxDriver(dc);

I systematically get the following exception

org.openqa.selenium.InvalidArgumentException: browserName was not a boolean
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: '<ComputerName>', ip: '<IpAddress>', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
Driver info: driver.version: FirefoxDriver
remote stacktrace: stack backtrace:
   0:   0x47f1a6 - <no info>
   1:   0x437327 - <no info>
   2:   0x42bd8c - <no info>
   3:   0x437ded - <no info>
   4:   0x41a7b3 - <no info>
   5:   0x40570c - <no info>
   6:   0x692906 - <no info>
   7:   0x413838 - <no info>
   8:   0x68d401 - <no info>
   9: 0x7573336a - BaseThreadInitThunk
  10: 0x774b9902 - RtlInitializeExceptionChain

Looking at the Mozilla source code, I found that raised exception should derive from the following file

gecko-dev-master\third_party\rust\webdriver\src\capabilities.rs

in these lines

        for (key, value) in capabilities.iter() {
        match &**key {
            "acceptInsecureCerts" => if !value.is_boolean() {
                    return Err(WebDriverError::new(ErrorStatus::InvalidArgument,
                                                   "acceptInsecureCerts was not a boolean"))
                },
            x @ "browserName" |
            x @ "browserVersion" |
            x @ "platformName" => if !value.is_string() {
                    return Err(WebDriverError::new(ErrorStatus::InvalidArgument,
                                                   format!("{} was not a boolean", x)))
                },

To be sure that browserName capability was correctly set, I added the println before creating the FirefoxDriver object.
As stated before, I tried the code with both Firefox 32 bits and 64 bits versions without any different result.

Whereas Chrome and chromedriver work fine.

May any of you suggest how to solve this issue?

Thanks in advance and best regards.

Body:
Set the browser name to "firefox" as lined out in the official documentation.

dc.setCapability("browserName", "firefox");


问:
div id in php echo doesn't work
For a school project I need to make a site. I want to make a div inside an echo in PHP but somehow it doesn't work.
Here is my code:

```<code><!DOCTYPE html>
<html>
<head>
    <link rel="icon" type="image/png" href="./images/favicon-32x32.png"
    sizes="32x32" />
    <link rel="icon" type="image/png" href="./images/favicon-16x16.png"
    sizes="16x16" />
    <title>MLB: Major League Baseball</title>
    <link href="css folder/MLBstylesheet.css" rel="stylesheet"
    type="text/css"/>
</head>
<body>
    <div id="container">
        <div id="titel">

           <img class="MLBTitel"  src="./images/MLBtitel.jpg" alt="MLBTitel" >
           <div id="titeltekst">
               MAJOR LEAGUE BASEBALL
               <br>
           </div>

           <nav>
              <ul>
                 <li><a class= "menu" href="index.html">Home</a></li>
                 <li><a class= "menu" href="spelers.php">Spelers</a></li>
                 <li><a class= "menu" href="teams.php">Teams</a></li>
                 <li><a class= "menu" href="wedstrijden.html">Wedstrijden</a></li>
                 <li><a class= "menu" href="contact.html">Contact</a></li>
             </ul>
         </nav>

         <br><br>
     </div>
     <div id="spelerstabel">
        <?php
        $servername = "localhost";
        $username = "id1419279_root";
        $password = "nivardenjoey";
        $dbname = "id1419279_mlb";

        $conn = new mysqli($localhost, $username, $password, $dbname);

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        $sql = "SELECT foto, voornaam, achternaam, team FROM spelers";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {

            while($row = $result->fetch_assoc()) {
                echo "<div id='spelersfoto'> <img class='spelersfoto' src=' " .
                $row["foto"]. "'/> - Name: " . $row["voornaam"]. " " . $row["achternaam"]. "
                - Team: " .$row["team"]. " </div>";

            }
        } else {
            echo "0 results";
        }
        $conn->close();
        ?>
    </div>
</div>
</body>
</html>
</code>```

Can someone help me please?

*I copied my whole code in here maybe that's easier

答:
NivardJ,

Try this:

```<code>$cntr = 1;
while($row = $result->fetch_assoc()) {
    echo "<div id='spelersfoto-$cntr'>
              <img class='spelersfoto' src='" . $row["foto"]. "'/>
              - Name: " . $row["voornaam"]. " " . $row["achternaam"]. "
              - Team: " .$row["team"]. "
          </div>";
    $cntr++;
}
</code>```

Hope this helps!

Best,

-Rush

Title: div id in php echo doesn't work

Body:
For a school project I need to make a site. I want to make a div inside an echo in PHP but somehow it doesn't work.
Here is my code:

<!DOCTYPE html>

    <link rel="icon" type="image/png" href="./images/favicon-32x32.png"
    sizes="32x32" />
    <link rel="icon" type="image/png" href="./images/favicon-16x16.png"
    sizes="16x16" />
    <title>MLB: Major League Baseball</title>
    <link href="css folder/MLBstylesheet.css" rel="stylesheet"
    type="text/css"/>

               MAJOR LEAGUE BASEBALL

Home

Spelers

Teams

Wedstrijden

Contact

        <?php
        $servername = "localhost";
        $username = "id1419279_root";
        $password = "nivardenjoey";
        $dbname = "id1419279_mlb";

        $conn = new mysqli($localhost, $username, $password, $dbname);

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        $sql = "SELECT foto, voornaam, achternaam, team FROM spelers";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {

            while($row = $result->fetch_assoc()) {
                echo "
  - Name: " . $row["voornaam"]. " " . $row["achternaam"]. "
                - Team: " .$row["team"]. "
";

            }
        } else {
            echo "0 results";
        }
        $conn->close();
        ?>

Can someone help me please?

*I copied my whole code in here maybe that's easier

Body:
NivardJ,

Try this:

$cntr = 1;
while($row = $result->fetch_assoc()) {
    echo "<div id='spelersfoto-$cntr'>
              <img class='spelersfoto' src='" . $row["foto"]. "'/>
              - Name: " . $row["voornaam"]. " " . $row["achternaam"]. "
              - Team: " .$row["team"]. "
          </div>";
    $cntr++;
}

Hope this helps!

Best,

-Rush


问:
Which hosting provider supports Haskell?
I have a hosting account with GoDaddy, but it does not support Haskell.</p>

答:
I recommend amazon web services, $15/month for a micro instance for testing/devel, and the costs go up from there depending on your needs.  For the love of all that is good and wonderful in this universe, however, do not use godaddy for anything but SSL certificates and domain names.  This just seems like an absolutely horrible idea.  They're just not the kinda people you want to work with on things like that.

As alternative VPS providers go, there are slicehost, linode, rackspace cloud, and I'm sure some others too.  In my experience with rackspace cloud, slicehost, and AWS, AWS has been best by far.


答:
I removed the space in your src=' " argument. Also, please try to have a unique ID. If you need to apply some css to every div, use a class instead:

```<code>$i = 0;
while($row = $result->fetch_assoc()) {
    $i++;
    echo "<div id='spelersfoto-'".$i."><img class='spelersfoto' src='" . $row["foto"]. "'/> - Name: " . $row["voornaam"]. " " . $row["achternaam"]. " - Team: " .$row["team"]. " </div>";
}
</code>```

Title: div id in php echo doesn't work

Body:
I removed the space in your src=' " argument. Also, please try to have a unique ID. If you need to apply some css to every div, use a class instead:

$i = 0;
while($row = $result->fetch_assoc()) {
    $i++;
    echo "<div id='spelersfoto-'".$i."><img class='spelersfoto' src='" . $row["foto"]. "'/> - Name: " . $row["voornaam"]. " " . $row["achternaam"]. " - Team: " .$row["team"]. " </div>";
}


问:
NSCoding encodeObject Error
import UIKit

class Event: NSObject, NSCoding {

```<code>// MARK: Properties
var name: String
var created_at: String
var stands:[Stand?]

// MARK: Archiving Paths

static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("events")

// MARK: Types

struct PropertyKey {
    static let nameKey = "name"
    static let createdAtKey = "created_at"
    static let standsAtKey = "stands"

}

// MARK: Initialization
init?(name: String, created_at: String, stands:[Stand?]) {
    // Initialize stored properties.
    self.name = name
    self.created_at = created_at
    self.stands = stands

    super.init()

    // Initialization should fail if there is no name or if no created_at.
    if name.isEmpty || created_at.isEmpty {
        return nil
    }
}

// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
    aCoder.encodeObject(created_at, forKey: PropertyKey.createdAtKey)
    aCoder.encodeObject(stands, forKey: PropertyKey.standsAtKey)

}

required convenience init?(coder aDecoder: NSCoder) {
    let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String

    let created_at = aDecoder.decodeObjectForKey(PropertyKey.createdAtKey) as! String

    let stands = aDecoder.decodeObjectForKey(PropertyKey.standsAtKey) as! [Stand?]

    // Must call designated initializer.
    self.init(name: name, created_at: created_at, stands: stands)
}
</code>```

}

I have got error from "aCoder.encodeObject(stands, forKey: PropertyKey.standsAtKey)" saying "Cannot convert value of type[Stand?] to expected argument type 'AnyObject?'"

I am using NSCoding to save the object with array of empty Stand, then later retrieve it and update the Stands property of this Class (Event)

答:
In Swift 4 you can conform to the protocol Codable which does the encoding en decoding

```<code>class Test: Codable {

}
</code>```

For more information, read https://developer.apple.com/documentation/swift/codable

Title: NSCoding encodeObject Error

Body:
import UIKit

class Event: NSObject, NSCoding {

// MARK: Properties
var name: String
var created_at: String
var stands:[Stand?]

// MARK: Archiving Paths

static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("events")

// MARK: Types

struct PropertyKey {
    static let nameKey = "name"
    static let createdAtKey = "created_at"
    static let standsAtKey = "stands"

}

// MARK: Initialization
init?(name: String, created_at: String, stands:[Stand?]) {
    // Initialize stored properties.
    self.name = name
    self.created_at = created_at
    self.stands = stands

    super.init()

    // Initialization should fail if there is no name or if no created_at.
    if name.isEmpty || created_at.isEmpty {
        return nil
    }
}

// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
    aCoder.encodeObject(created_at, forKey: PropertyKey.createdAtKey)
    aCoder.encodeObject(stands, forKey: PropertyKey.standsAtKey)

}

required convenience init?(coder aDecoder: NSCoder) {
    let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String

    let created_at = aDecoder.decodeObjectForKey(PropertyKey.createdAtKey) as! String

    let stands = aDecoder.decodeObjectForKey(PropertyKey.standsAtKey) as! [Stand?]

    // Must call designated initializer.
    self.init(name: name, created_at: created_at, stands: stands)
}

}

I have got error from "aCoder.encodeObject(stands, forKey: PropertyKey.standsAtKey)" saying "Cannot convert value of type[Stand?] to expected argument type 'AnyObject?'"

I am using NSCoding to save the object with array of empty Stand, then later retrieve it and update the Stands property of this Class (Event)

Body:
In Swift 4 you can conform to the protocol Codable which does the encoding en decoding

class Test: Codable {

}

For more information, read https://developer.apple.com/documentation/swift/codable


问:
Python 3 dictionary update sequence element error
I'm trying to make a simple Def so I can append my json file easily. I cant get the value(s) to work no matter how I try.

At the top I'm using

```<code>def AppendPersonal_data(X,Y):
    with open( username +'.json') as f:
        keymaster= X,Y
        Personal_data = json.load(f)
        Personal_data.update(keymaster)
        with open(username + '.json', 'w') as f:
            json.dump(Personal_data, f)
</code>```

Then on my button press in my menu I have

```<code>choice = input()
random_number = "1"
if choice == "1":
    if random_number == choice:
        now = str(datetime.now())
        print("YOU PICKED CORRECT!! ")
    else:
        print("YOU PICKED WRONG!! ")
    AppendPersonal_data(random_number,now)
</code>```

No matter what I try I always end up with a :

ValueError: dictionary update sequence element #0 has length 1; 2 is required

答:
After a few hours of messing with it I've gotten this to work
At the top

```<code>def AppendPersonal_data(X):
    with open( username +'.json') as f:
        Personal_data = json.load(f)
        Personal_data.update(X)
        with open(username + '.json', 'w') as f:
            json.dump(Personal_data, f)
</code>```

and then for the button press

```<code>    choice = input()
        random_sound = "1"
        if choice == "1":
            now = str(datetime.now())
            if random_sound == choice:
                print("YOU PICKED CORRECT!! ")
                guess1= { ''+ str(datetime.now())+'' : ''+ str(random_sound) + '_Y' }
            else:
                guess1= { ''+ str(datetime.now())+'' : ''+ str(random_sound) + '_X' }
                print("YOU PICKED WRONG!! ")

            print (guess1)
            AppendPersonal_data(guess1)
</code>```

I switched the datetime and random_sound values, but switching them back works the same.
Sorry about all the ugliness. This is my 3rd day working with Python. So like 15h.
Thank you guys for the tips. If there's a way to optimize this, please let me know.

Body:
I'm trying to make a simple Def so I can append my json file easily. I cant get the value(s) to work no matter how I try.

At the top I'm using

def AppendPersonal_data(X,Y):
    with open( username +'.json') as f:
        keymaster= X,Y
        Personal_data = json.load(f)
        Personal_data.update(keymaster)
        with open(username + '.json', 'w') as f:
            json.dump(Personal_data, f)

Then on my button press in my menu I have

choice = input()
random_number = "1"
if choice == "1":
    if random_number == choice:
        now = str(datetime.now())
        print("YOU PICKED CORRECT!! ")
    else:
        print("YOU PICKED WRONG!! ")
    AppendPersonal_data(random_number,now)

No matter what I try I always end up with a :

ValueError: dictionary update sequence element #0 has length 1; 2 is required

Body:
After a few hours of messing with it I've gotten this to work
At the top

def AppendPersonal_data(X):
    with open( username +'.json') as f:
        Personal_data = json.load(f)
        Personal_data.update(X)
        with open(username + '.json', 'w') as f:
            json.dump(Personal_data, f)

and then for the button press

    choice = input()
        random_sound = "1"
        if choice == "1":
            now = str(datetime.now())
            if random_sound == choice:
                print("YOU PICKED CORRECT!! ")
                guess1= { ''+ str(datetime.now())+'' : ''+ str(random_sound) + '_Y' }
            else:
                guess1= { ''+ str(datetime.now())+'' : ''+ str(random_sound) + '_X' }
                print("YOU PICKED WRONG!! ")

            print (guess1)
            AppendPersonal_data(guess1)

I switched the datetime and random_sound values, but switching them back works the same.
Sorry about all the ugliness. This is my 3rd day working with Python. So like 15h.
Thank you guys for the tips. If there's a way to optimize this, please let me know.


问:
Escape special characters of JSON in c#
I hava JSON object with one field has string value

```<code>" Ran a defrag removed a few virus' and tried again "
</code>```

' is special character in JSON. I am using c#, NewtonSoftJSON library.

Is there any best way to  escape all special character with Newtonsoft and c#.

答:
You can try this:</p>

```<code>HttpUtility.JavaScriptStringEncode(inputString);
</code>```

Title: Escape special characters of JSON in c#

Body:
I hava JSON object with one field has string value

" Ran a defrag removed a few virus' and tried again "

' is special character in JSON. I am using c#, NewtonSoftJSON library.

Is there any best way to  escape all special character with Newtonsoft and c#.

Body:
You can try this:

HttpUtility.JavaScriptStringEncode(inputString);


问:
Data structure for looking up values based on keys being in a range
I'm looking for an alternative to a dictionary that will allow me to efficiently use ranges as keys. Presumably the data structure needs to be sorted - maybe something like a b tree? I haven't found a good python implementation.

For example, given the following dictionary-like data structure:

d = {'38.1003827193': 'value1', '58.29932891733': 'value2'}

Searching for the range 38 -> 38.337 should return value1

答: I'm not sure why your keys are kept as strings, but the bisect module in the standard library can help you do binary searches in a sorted index. Multidimensional indexing is another chapter in turn, and the primary question is how you use your data; trees may be faster for insertions or particular distributions, for instance. </p>


问:
Google address autofill appears in wrong place on page
I am using the Google address autofill API and when I start typing an address the address box appears higher on the page when it is meant to appear directly under the input box. Its position is ALSO affected by how far you are scrolled down on the page; the further you're scrolled down, the higher the box appears. This eliminates the possibility to hard code the boxes position as it is dynamically changing with the scroll.

Any ideas?

```<code><input type="text" class="moving-input form-control" id="address" autocomplete="true" placeholder="">

    <script>
    // This example displays an address form, using the autocomplete feature
    // of the Google Places API to help users fill in the information.
    // This example requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
    var placeSearch, autocomplete;
    var componentForm = {
      street_number: 'short_name',
      route: 'long_name',
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      //country: 'long_name',
      postal_code: 'short_name'
    };

    var typeToFieldMap = {
        administrative_area_level_1:"billing_state",
        locality:"billing_city",
        postal_code:"billing_zip",
        street_number: 'billing_street',
        route: 'billing_route'
    }

    function initAutocomplete() {
      // Create the autocomplete object, restricting the search to geographical
      // location types.
      autocomplete = new google.maps.places.Autocomplete(
          /** @type {!HTMLInputElement} */(document.getElementById('address')),
          {types: ['address']});
      // When the user selects an address from the dropdown, populate the address
      // fields in the form.
      autocomplete.addListener('place_changed', fillInAddress);
    }
    function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            var el = document.getElementById(typeToFieldMap[addressType]);
            if (addressType == "route")
                el.value = el.value + " " + val;
            //else if (addressType == "administrative_area_level_1")
            //  selectItemByValue(el, val);
            else
                el.value = val;
            console.log(val);
          }
        }

        $('.moving-input').each(
        function(){
            var input_wrap = $(this).closest('.moving-input');
            var val = $(this).val().trim();
            if (val.length){
               input_wrap.addClass('filled');
            }
        });
    }

    function selectItemByValue(elmnt, value){
        for(var i=0; i < elmnt.options.length; i++)
        {
            //var sname = getStateName(value);
          if(elmnt.options[i].value == value)
            elmnt.selectedIndex = i;
        }

     }
    // Bias the autocomplete object to the user's geographical location,
    // as supplied by the browser's 'navigator.geolocation' object.
    function geolocate() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
          });
          autocomplete.setBounds(circle.getBounds());
        });
      }
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC-3Akj68Di27JBiFK2xkV6YLFdUMIWDGE&libraries=places&callback=initAutocomplete" async defer></script>
</code>```

答: The html was set to 100%. Removing this corrected the placement of the Google address drop down.</p>

Body:
I am using the Google address autofill API and when I start typing an address the address box appears higher on the page when it is meant to appear directly under the input box. Its position is ALSO affected by how far you are scrolled down on the page; the further you're scrolled down, the higher the box appears. This eliminates the possibility to hard code the boxes position as it is dynamically changing with the scroll.

Any ideas?

<input type="text" class="moving-input form-control" id="address" autocomplete="true" placeholder="">


问:
store multi images in mat file using matlab
The bellow matlab code is to read 6 images from folder and save them in mat file
then return to read the mat file and check the images inside it

the problem is that
just the last images stores in mat file

the problem is in save function::

what should I edit to make save function store all images that stored in result cell into mat file

```<code>%Generate mat file
srcFile = dir('C:\Users\Desktop\images\*.jpg');
result = cell(1,length(srcFile));
for i = 1 : length(srcFile)
    filename = strcat('C:\Users\Desktop\images\',srcFile(i).name);
    I = imread(filename);
    %figure, imshow(I);
    I = imresize(I,[128 128]);
    result{i} = I;
    figure, imshow(result{i});
end

save images, result;

%Read mat file
for j =1 :length(srcFile)
    filename = strcat('C:\Users\Desktop\images\',srcFile(j).name);
    I = imread(filename);
    a='I';
    input = load('images.mat',a);
    figure, imshow(input.(a));
end
</code>```

答:
Your first loop, up to the save, is fine.

When you load the data, use load('images.mat') before the second loop. Then, you have back the result variable in your workspace and you iterate on it:

```<code>load('images.mat')
for j = 1:length(srcFile)
    figure, imshow(result{j});
end
</code>```

What you have to remember is that your .mat file only contains the variables you saved, but you can't access them directly with load. You first load them, and then access the loaded variables (which have a different name from the file, usually).

Finally, if you want to check this code, you need to clear the workspace after the save, otherwise you may not notice that some of the variables you use are not there anymore (like the error you have got with I).

Body:
The bellow matlab code is to read 6 images from folder and save them in mat file
then return to read the mat file and check the images inside it

the problem is that
just the last images stores in mat file

the problem is in save function::

what should I edit to make save function store all images that stored in result cell into mat file

%Generate mat file
srcFile = dir('C:\Users\Desktop\images\*.jpg');
result = cell(1,length(srcFile));
for i = 1 : length(srcFile)
    filename = strcat('C:\Users\Desktop\images\',srcFile(i).name);
    I = imread(filename);
    %figure, imshow(I);
    I = imresize(I,[128 128]);
    result{i} = I;
    figure, imshow(result{i});
end

save images, result;

%Read mat file
for j =1 :length(srcFile)
    filename = strcat('C:\Users\Desktop\images\',srcFile(j).name);
    I = imread(filename);
    a='I';
    input = load('images.mat',a);
    figure, imshow(input.(a));
end

Body:
Your first loop, up to the save, is fine.

When you load the data, use load('images.mat') before the second loop. Then, you have back the result variable in your workspace and you iterate on it:

load('images.mat')
for j = 1:length(srcFile)
    figure, imshow(result{j});
end

What you have to remember is that your .mat file only contains the variables you saved, but you can't access them directly with load. You first load them, and then access the loaded variables (which have a different name from the file, usually).

Finally, if you want to check this code, you need to clear the workspace after the save, otherwise you may not notice that some of the variables you use are not there anymore (like the error you have got with I).


问:
Distinct enclosing environment, function environment, etc. in R
I have a few questions about the different environments of a function. Take the following example:

```<code>environment(sd)
# <environment: namespace:stats>
</code>```

Does namespace:stats point to the enclosing environment of function sd?

```<code>pryr::where(sd)
# <environment: package:stats>
</code>```

Does package:stats point to the binding environment of function sd?

According to Advanced R by Hadley Wickham: "The enclosing environment belongs to the function, and never changes..."

But the enclosing environment of function can be changed like the below:

```<code>new.env <- new.env()
environment(f) <- new.env
</code>```

A function' environment property indicates a function's executing environment, correct? An online article regarding R finding stuff through environments

To sum up my questions:

Can we actually change the enclosing environment of a function or not?

What are those two different environments of the stats package?

What is the function's environment?

It's similar to a previous post in here.

答:
environment(function) gives the function's enclosing environment (i.e. the closure) which is assigned a pointer to the environment in which the function was defined.  This convention is called lexical scoping, and is what lets you use patterns like factory functions.   Here is a simple example

```<code>factory <- function(){
    # get a reference to the current environment -- i.e. the environment
    # that was created when the function `factory` was called.
    envir = environment()
    data <- 0
    add <- function(x=1){
        # we can use the lexical scoping assignment operator to re-assign the value of data
        data <<- data + x
        # return the value of the lexically scoped variable `data`
        return(data)
    }
    return(list(envir=envir,add=add))
}

L = factory()

# check that the environment for L$add is the environment in which it was created
identical(L$envir,environment(L$add))
#> TRUE

L$add()
#> 1
L$add(3)
#> 4
</code>```

note that we can re-assign the value of data in the enclosing environment using assign() like so:

```<code>assign("data",100,L$envir)
L$add()
#> 101
</code>```

Also, when we call the function factory() again, another new environment is created
and is assigned as the closure for the functions that get defined in that
function call, which is what allows us to have to separate foo$add() funcitons
wich scope to their own separate environments:

```<code>M = factory()
M$add()
#> 1
#> 2
L$add()
#> 102
</code>```

The above factory function illustrates the link between the function and it's enclosing environment via continuation of the search for a variable (and use of the scoping assignment operator, whereas the following illustrates the link between a local environment and the calling frame via Promises which is how R passes variables in a function call.

Specifically, when you call a function, R creates promises for the value of variables and expressions passed.  These value of the Promise is passed (copied) from the variable / expression by evaluating the Promise in the context of the calling environment when the parameter is force()'d or used -- and not sooner!

For example, This factory function takes a parameter which is stored as a promise until the returned function is called:

```<code>factory2 <- function(x){
    out <-function(){
         return(x)
    }
    return(out)
}
</code>```

Now factory2 behaves intuitively in some cases:

```<code>y = 1
f = factory2(y)
f()
#> 1
</code>```

but not in others:

```<code>y = 1
h = factory2(y)
y = 2
h()
#> 2
</code>```

because the promise for the expression y is not evaluated until h() is called, and in the second example, the value of y is 2!  Of course, now that the value has been copied from the calling environment into the local environment via Promise evaluation, changing the value of y won't affect the value returned by h():

```<code>y = 3
h()
#> 2
</code>```

Body:
I have a few questions about the different environments of a function. Take the following example:

environment(sd)
# <environment: namespace:stats>

Does namespace:stats point to the enclosing environment of function sd?

pryr::where(sd)
# <environment: package:stats>

Does package:stats point to the binding environment of function sd?

According to Advanced R by Hadley Wickham: "The enclosing environment belongs to the function, and never changes..."

But the enclosing environment of function can be changed like the below:

new.env <- new.env()
environment(f) <- new.env

A function' environment property indicates a function's executing environment, correct? An online article regarding R finding stuff through environments

To sum up my questions:

Can we actually change the enclosing environment of a function or not?

What are those two different environments of the stats package?

What is the function's environment?

It's similar to a previous post in here.

Body:
environment(function) gives the function's enclosing environment (i.e. the closure) which is assigned a pointer to the environment in which the function was defined.  This convention is called lexical scoping, and is what lets you use patterns like factory functions.   Here is a simple example

factory <- function(){
    # get a reference to the current environment -- i.e. the environment
    # that was created when the function `factory` was called.
    envir = environment()
    data <- 0
    add <- function(x=1){
        # we can use the lexical scoping assignment operator to re-assign the value of data
        data <<- data + x
        # return the value of the lexically scoped variable `data`
        return(data)
    }
    return(list(envir=envir,add=add))
}

L = factory()

# check that the environment for L$add is the environment in which it was created
identical(L$envir,environment(L$add))
#> TRUE

L$add()
#> 1
L$add(3)
#> 4

note that we can re-assign the value of data in the enclosing environment using assign() like so:

assign("data",100,L$envir)
L$add()
#> 101

Also, when we call the function factory() again, another new environment is created
and is assigned as the closure for the functions that get defined in that
function call, which is what allows us to have to separate foo$add() funcitons
wich scope to their own separate environments:

M = factory()
M$add()
#> 1
#> 2
L$add()
#> 102

The above factory function illustrates the link between the function and it's enclosing environment via continuation of the search for a variable (and use of the scoping assignment operator, whereas the following illustrates the link between a local environment and the calling frame via Promises which is how R passes variables in a function call.

Specifically, when you call a function, R creates promises for the value of variables and expressions passed.  These value of the Promise is passed (copied) from the variable / expression by evaluating the Promise in the context of the calling environment when the parameter is force()'d or used -- and not sooner!

For example, This factory function takes a parameter which is stored as a promise until the returned function is called:

factory2 <- function(x){
    out <-function(){
         return(x)
    }
    return(out)
}

Now factory2 behaves intuitively in some cases:

y = 1
f = factory2(y)
f()
#> 1

but not in others:

y = 1
h = factory2(y)
y = 2
h()
#> 2

because the promise for the expression y is not evaluated until h() is called, and in the second example, the value of y is 2!  Of course, now that the value has been copied from the calling environment into the local environment via Promise evaluation, changing the value of y won't affect the value returned by h():

y = 3
h()
#> 2