问:
Using variables in the values-form in multiple-value-bind
I am trying to implement a function read-from-whole-string in lisp, where it uses the inbuilt function read-from-string.

About read-from-string

read-from-string is used to read an object from a string which can be specified using the keywords :start,:end etc. It returns two values, the object and the position of the next element, which wasn't read. I plan to use this value.

The plan

The plan is to use the second value returned from the read-from-string function, again on itself to insert the value of the keyword :start. But the problem comes with the function multiple-value-bind. We can't:

Initialize a variable in multiple-value-bind.

Use a variable just defined into the values-form.

To be specific, I want to:

```<code>(multiple-value-bind (x (y 0))
         (read-from-string str :Start y)
         y)
</code>```

Any other clean method is appreciated.

答:
You can make a string stream, read and discard an object, and then read again:

```<code>$ clisp -q
[1]> (with-input-from-string (*standard-input* "1 2") (read) (read))
2
</code>```

To read all the elements from the input string we can loop on read and use a unique value to detect EOF, rather than have it throw an error:

```<code>(with-input-from-string (s "1 2 3 4")
  (loop with eof = '#:eof
        for item = (read s nil eof)
        until (eq item eof)
        collecting item))
-> (1 2 3 4)
</code>```

To extract all the objects in a string, we could also wrap it in parentheses and use a single application of read-from-string:

```<code>(read-from-string (format nil "(~a)" "1 2 3 4"))
-> (1 2 3 4); 11
</code>```

The danger there is the lack of diagnosis for situations when the string contains this sort of problem: "a b ) c d".  We can check for that situation by comparing the returned length to the string length to make sure all of it was read, and issue some generic diagnostic if it wasn't.

```<code>(defun read-whole-string (str)
  (let ((par-str (format nil "(~a)" str)))
    (multiple-value-bind (obj len) (read-from-string par-str)
      (if (eql len (length par-str))
        obj
        (error "read-whole-string: ~a is malformed at position ~s"
               str (- len 2))))))
</code>```

Body:
I am trying to implement a function read-from-whole-string in lisp, where it uses the inbuilt function read-from-string.

About read-from-string

read-from-string is used to read an object from a string which can be specified using the keywords :start,:end etc. It returns two values, the object and the position of the next element, which wasn't read. I plan to use this value.

The plan

The plan is to use the second value returned from the read-from-string function, again on itself to insert the value of the keyword :start. But the problem comes with the function multiple-value-bind. We can't:

Initialize a variable in multiple-value-bind.

Use a variable just defined into the values-form.

To be specific, I want to:

(multiple-value-bind (x (y 0))
         (read-from-string str :Start y)
         y)

Any other clean method is appreciated.

Body:
You can make a string stream, read and discard an object, and then read again:

$ clisp -q
[1]> (with-input-from-string (*standard-input* "1 2") (read) (read))
2

To read all the elements from the input string we can loop on read and use a unique value to detect EOF, rather than have it throw an error:

(with-input-from-string (s "1 2 3 4")
  (loop with eof = '#:eof
        for item = (read s nil eof)
        until (eq item eof)
        collecting item))
-> (1 2 3 4)

To extract all the objects in a string, we could also wrap it in parentheses and use a single application of read-from-string:

(read-from-string (format nil "(~a)" "1 2 3 4"))
-> (1 2 3 4); 11

The danger there is the lack of diagnosis for situations when the string contains this sort of problem: "a b ) c d".  We can check for that situation by comparing the returned length to the string length to make sure all of it was read, and issue some generic diagnostic if it wasn't.

(defun read-whole-string (str)
  (let ((par-str (format nil "(~a)" str)))
    (multiple-value-bind (obj len) (read-from-string par-str)
      (if (eql len (length par-str))
        obj
        (error "read-whole-string: ~a is malformed at position ~s"
               str (- len 2))))))


来源: stackexchange

问:
Bootstrap 4 full width carousel
I have a problem with my bs 4 carousel. I have video in it and I want it to be full width and height like in this link https://www.jeunesseglobal.com/ . Problem is that my video is in center and looks like this example

Here's my HTML

```<code><div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner" role="listbox">
      <div class="carousel-item active">
        <video autoplay="true" loop muted class="d-block img-fluid" src="img/video.mp4" type="video/mp4">
      </div>
    </div>
  </div>
</code>```

My CSS

```<code>video {
  width: 100vw;
  left: 0;
  right: 0;
}
</code>```

I am bit lost whatever I do video is still in center and won't spread out

答:
CHANGES:

Try a CSS reset

Add some additional CSS to hide the scrollbars but still be able to scroll

Add a closing </video> tag

video {
  width: 100vw;
  left: 0;
  right: 0;
}

#parent {
 overflow: hidden;
}

#carouselExampleSlidesOnly {
overflow-y: scroll;
}

::-webkit-scrollbar {
    display: none;
}

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
 margin: 0;
 padding: 0;
 border: 0;
 font-size: 100%;
 font: inherit;
 vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
 display: block;
}
body {
 line-height: 1;
}
ol, ul {
 list-style: none;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
 content: '';
 content: none;
}
table {
 border-collapse: collapse;
 border-spacing: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner" role="listbox">
      <div class="carousel-item active">
        <video autoplay="true" loop muted class="d-block img-fluid" src="https://r1---sn-vgqs7nly.googlevideo.com/videoplayback?expire=1496618693&ratebypass=yes&lmt=1481043164463513&dur=59.350&pl=15&id=o-AL1AUoU6a3Nfcj7LH03aWUedATMzZser2fPJuYfXIks0&source=youtube&signature=4292002183801D0F3305E4F2C63F3CF53C6253E0.4BE60D1FB40096BD45D531BCDE2ECC2D39B0CDBA&key=cms1&mime=video%2Fmp4&requiressl=yes&ip=73.247.17.20&ei=ZEI0WcfDOoPPuALRm4-4DQ&sparams=dur,ei,expire,id,initcwndbps,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pl,ratebypass,requiressl,source&ipbits=0&itag=22&redirect_counter=1&cm2rm=sn-vgqys7s&req_id=2b645fa084caa3ee&cms_redirect=yes&mm=34&mn=sn-vgqs7nly&ms=ltu&mt=1496597003&mv=m" type="video/mp4"></video>
      </div>
    </div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Bootstrap 4 full width carousel

Body:
I have a problem with my bs 4 carousel. I have video in it and I want it to be full width and height like in this link https://www.jeunesseglobal.com/ . Problem is that my video is in center and looks like this example

Here's my HTML

        <video autoplay="true" loop muted class="d-block img-fluid" src="img/video.mp4" type="video/mp4">

My CSS

video {
  width: 100vw;
  left: 0;
  right: 0;
}

I am bit lost whatever I do video is still in center and won't spread out

Body:
CHANGES:

Try a CSS reset

Add some additional CSS to hide the scrollbars but still be able to scroll

Add a closing </video> tag

video {
  width: 100vw;
  left: 0;
  right: 0;
}

#parent {
 overflow: hidden;
}

#carouselExampleSlidesOnly {
overflow-y: scroll;
}

::-webkit-scrollbar {
    display: none;
}

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
 margin: 0;
 padding: 0;
 border: 0;
 font-size: 100%;
 font: inherit;
 vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
 display: block;
}
body {
 line-height: 1;
}
ol, ul {
 list-style: none;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
 content: '';
 content: none;
}
table {
 border-collapse: collapse;
 border-spacing: 0;
}

<div id="parent">
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner" role="listbox">
      <div class="carousel-item active">
        <video autoplay="true" loop muted class="d-block img-fluid" src="https://r1---sn-vgqs7nly.googlevideo.com/videoplayback?expire=1496618693&ratebypass=yes&lmt=1481043164463513&dur=59.350&pl=15&id=o-AL1AUoU6a3Nfcj7LH03aWUedATMzZser2fPJuYfXIks0&source=youtube&signature=4292002183801D0F3305E4F2C63F3CF53C6253E0.4BE60D1FB40096BD45D531BCDE2ECC2D39B0CDBA&key=cms1&mime=video%2Fmp4&requiressl=yes&ip=73.247.17.20&ei=ZEI0WcfDOoPPuALRm4-4DQ&sparams=dur,ei,expire,id,initcwndbps,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pl,ratebypass,requiressl,source&ipbits=0&itag=22&redirect_counter=1&cm2rm=sn-vgqys7s&req_id=2b645fa084caa3ee&cms_redirect=yes&mm=34&mn=sn-vgqs7nly&ms=ltu&mt=1496597003&mv=m" type="video/mp4"></video>
      </div>
    </div>
  </div>
</div>


问:
Pygame display causing segmentation fault 11
I'm using python 2.7.10 and pygame 1.9.1 on OS X 10.11.1

I'm getting Segmentation fault: 11 & python crashes whenever I draw anything on or fill a pygame surface (at least I think that's the cause). I have several pygame projects I've done for school that have worked on this same machine in the past, but simply crash now. I don't recall changing python or pygame versions since then, only updating OS X version.

This is a simple little program that should just display a red rectangle on a purple-ish background:

```<code>import pygame
import pygame.locals

class ExampleClass:
    def __init__(self):
        self.screen = pygame.display.set_mode(
                        (100, 100),
                        pygame.locals.DOUBLEBUF |
                        pygame.locals.SRCALPHA)

    def paint(self, surface):
        surface.fill((100, 50, 255))        # blue-purple-y background
        pygame.draw.rect(surface, (255, 50, 100), (10, 10, 50, 25))     # red rectangle

    def main_loop(self):
        clock = pygame.time.Clock()

        while True:
            clock.tick(30)

            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    pygame.quit()
                    return
                if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
                    pygame.quit()
                    return

                self.paint(self.screen)

                pygame.display.flip()

example = ExampleClass()
example.main_loop()
</code>```

I tried this on a windows machine & it worked completely fine, however it crashes on my mac. If you comment out self.paint(self.screen), the window pops up & there's no crash. I've searched around a bit and not found much. I have no idea what's causing it to do this, any help would be greatly appreciated.

答:
I know this is old, but it's a bug in the built in SDL library.

Download the SDL-1.2.15 lib for Mac from the official site

Body:
I'm using python 2.7.10 and pygame 1.9.1 on OS X 10.11.1

I'm getting Segmentation fault: 11 & python crashes whenever I draw anything on or fill a pygame surface (at least I think that's the cause). I have several pygame projects I've done for school that have worked on this same machine in the past, but simply crash now. I don't recall changing python or pygame versions since then, only updating OS X version.

This is a simple little program that should just display a red rectangle on a purple-ish background:

import pygame
import pygame.locals

class ExampleClass:
    def __init__(self):
        self.screen = pygame.display.set_mode(
                        (100, 100),
                        pygame.locals.DOUBLEBUF |
                        pygame.locals.SRCALPHA)

    def paint(self, surface):
        surface.fill((100, 50, 255))        # blue-purple-y background
        pygame.draw.rect(surface, (255, 50, 100), (10, 10, 50, 25))     # red rectangle

    def main_loop(self):
        clock = pygame.time.Clock()

        while True:
            clock.tick(30)

            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    pygame.quit()
                    return
                if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
                    pygame.quit()
                    return

                self.paint(self.screen)

                pygame.display.flip()

example = ExampleClass()
example.main_loop()

I tried this on a windows machine & it worked completely fine, however it crashes on my mac. If you comment out self.paint(self.screen), the window pops up & there's no crash. I've searched around a bit and not found much. I have no idea what's causing it to do this, any help would be greatly appreciated.


问:
C# SoundPlayer Question
I'm trying to get one .wav file to play as ambient music though when another sound is played, it halts the ambient music and I've tried doing play-loop and tried the various sync, async , load.

I think I'm missing something here. Thank you in advance.

答: Check this question on SO and the suggestions made there. The basic problem is that SoundPlayer can only play one sound stream at a time - if you want to play multiple sounds concurrently you need a different solution.

ContentLicense: CC BY-SA 2.5

Title: C# SoundPlayer Question


问:
Can't get value from DateTime object in PHP
I am facing an issue while trying to get value from an object in PHP. Here is the object:

```<code>DateTime Object
(
    [date] => 2017-06-03 18:33:48.000000
    [timezone_type] => 1
    [timezone] => +00:00
)
</code>```

it's all in this variable $call->dateCreated

and here is how I am trying to get the value of "date" from the object:

```<code>$call->dateCreated->date;
</code>```

but when I try to do this, I got an error:

Undefined property: DateTime::$date

答:
This should fix it, try something like this

```<code>$date_array = (array) $call->dateCteated;
</code>```

Then use the date value as

```<code>$date_array['date']
</code>```

Hope this helps!

Body:
I am facing an issue while trying to get value from an object in PHP. Here is the object:

DateTime Object
(
    [date] => 2017-06-03 18:33:48.000000
    [timezone_type] => 1
    [timezone] => +00:00
)

it's all in this variable $call->dateCreated

and here is how I am trying to get the value of "date" from the object:

$call->dateCreated->date;

but when I try to do this, I got an error:

Undefined property: DateTime::$date

Body:
This should fix it, try something like this

$date_array = (array) $call->dateCteated;

Then use the date value as

$date_array['date']

Hope this helps!


答:
It's a DateTime object, so you can get wanted format date by calling format() function:

```<code>$call->dateCreated->format('Y-m-d H:i:s');
</code>```

Title: Can't get value from DateTime object in PHP

Body:
It's a DateTime object, so you can get wanted format date by calling format() function:

$call->dateCreated->format('Y-m-d H:i:s');


问:
MVC Entity Type Missing
I'm brand new to ASP.NET MVC (Literally just two days of learning on the fly). I'm trying to create a website using MVC, however, I've screwed something up in my solution.

I created this table that had foreign key constraints but I initially forgot to set up a primary key on the id field and forgot to set it identity specification to yes.  So when I updated my DataModel and brought this table in, it showed every field as being the primary key and it showed the relationship to the other tables.  So I went back to the database and changed the id field for the table to be the primary key and identity specification to yes.

I went back to the DataModel, tried to Update Model From Database, went to the refresh tab, expanded the tables, and selected the table I wanted to refresh, then click on "Finish".

The data model appeared to make the changes but it showed the relationships to the other tables twice.

So I thought I'd delete the table (entity) from the DataModel diagrahm and bring the table back in through Update Model From Database.  But when I went back to the Update Model From Database...

Under the Add tab, the table isn't under the Tables

Under the Refresh tab, the table is listed, but when I select it and click on "Finish" the table doesn't reaapear in the diagrahm.

In the model browser...
Under Models

Entity Types, The entity isn't listed

Under Associations, The relationships no longer appear (obviously because the entity is gone).

Under Models.Store

Tables/Views, The table is listed.

Constraints, the relationships are shown.

I've tried dragging the table over to the diagrahm from the Model Browser, but that doesn't appear to work.

I've tried to right click in the diagrahm, add Entity but my table doesn't appear as a Base Type.

I've tried to google but I'm coming up with nothing.  With this entity missing, I cannot even build my solution.  Please help.

答:
Try to delete the entity file and add it again. But you have to name it as previous entity and don't forget to delete the connectionString in web.config before add it.

If you don't know what I am saying just let me know.

Title: MVC Entity Type Missing


问:
Launch IPython notebook with selected browser
I am trying to start IPython with a non default browser (in my case Firefox)
and thought I could replicate the replicate the script given in this blog

I am on Windows 7

I put the following code in a file say "module.py"

```<code>import subprocess
subprocess.call("ipython notebook --no-browser", shell=True)
subprocess.call([r'C:\Program Files (x86)\Mozilla Firefox\Firefox.exe', '-new-tab', 'http://127.0.0.1:8888/'])
</code>```

However when I run it from the command line

```<code> python C:\Users\mugabal\Desktop\module1.py
</code>```

It execute the first line but not the second one (both lines work fine individually)

My question (in a more general term) how can I launch a process and tell it not to highjack the console window?

I apologize in advance if I have overseen an obvious explanation but I looked both in the subprocess documentation and on this platform

----- UPDATE -----

I should have added that I tried to launch IPython with selected browser but could not figure out how to get it work

```<code>>ipython notebook --browser='C:\Program Files (x86)\Mozilla Firefox\Firefox.exe'
...
[NotebookApp] The IPython Notebook is running at: http://127.0.0.1:8888/
...
**[NotebookApp] No web browser found: could not locate runnable browser.**
</code>```

To be precise, the following command in a Windows command prompt window works as expected:

```<code>start firefox
</code>```

but

```<code>ipython notebook --browser=firefox
</code>```

does not work (same error as above).

答:
This is not a real answer. I just want to share with the less computer savvy what JPG's answer looks like step-by-step. Presumably, on Windows Explorer (screen capture attached below), the file jupyter_notebook_config.py is listed:

In my case, the directory for the file (on top menu of Explorer) was C:\Users\My_name\.jupyter

The second part of the answer can be implemented by simply pasting:

```<code>import webbrowser
webbrowser.register('firefox', None, webbrowser.GenericBrowser('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'))
c.NotebookApp.browser = 'firefox'
</code>```

in the space on the space seen on the screen capture below, corresponding to the jupyter_notebook_config.py opened within PyCharm:

... only that I set it up to open in Opera:

```<code>import webbrowser
webbrowser.register('opera', None, webbrowser.GenericBrowser('C:\\Program Files (x86)\\Opera\\launcher.exe'))
c.NotebookApp.browser = 'opera'
</code>```

Body:
I am trying to start IPython with a non default browser (in my case Firefox)
and thought I could replicate the replicate the script given in this blog

I am on Windows 7

I put the following code in a file say "module.py"

import subprocess
subprocess.call("ipython notebook --no-browser", shell=True)
subprocess.call([r'C:\Program Files (x86)\Mozilla Firefox\Firefox.exe', '-new-tab', 'http://127.0.0.1:8888/'])

However when I run it from the command line

 python C:\Users\mugabal\Desktop\module1.py

It execute the first line but not the second one (both lines work fine individually)

My question (in a more general term) how can I launch a process and tell it not to highjack the console window?

I apologize in advance if I have overseen an obvious explanation but I looked both in the subprocess documentation and on this platform

----- UPDATE -----

I should have added that I tried to launch IPython with selected browser but could not figure out how to get it work

>ipython notebook --browser='C:\Program Files (x86)\Mozilla Firefox\Firefox.exe'
...
[NotebookApp] The IPython Notebook is running at: http://127.0.0.1:8888/
...
**[NotebookApp] No web browser found: could not locate runnable browser.**

To be precise, the following command in a Windows command prompt window works as expected:

start firefox

but

ipython notebook --browser=firefox

does not work (same error as above).

Body:
This is not a real answer. I just want to share with the less computer savvy what JPG's answer looks like step-by-step. Presumably, on Windows Explorer (screen capture attached below), the file jupyter_notebook_config.py is listed:

In my case, the directory for the file (on top menu of Explorer) was C:\Users\My_name\.jupyter

The second part of the answer can be implemented by simply pasting:

import webbrowser
webbrowser.register('firefox', None, webbrowser.GenericBrowser('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'))
c.NotebookApp.browser = 'firefox'

in the space on the space seen on the screen capture below, corresponding to the jupyter_notebook_config.py opened within PyCharm:

... only that I set it up to open in Opera:

import webbrowser
webbrowser.register('opera', None, webbrowser.GenericBrowser('C:\\Program Files (x86)\\Opera\\launcher.exe'))
c.NotebookApp.browser = 'opera'


问:
Mongodb query using db.collection.find() method 100 times faster than using db.collection.aggregate()?
My collection testData has some 4 milion documents with the identical structure:

```<code>{"_id" : ObjectId("5932c56571f5a268cea12226"),
"x" : 1.0,
"text" : "w592cQzC5aAfZboMujL3knCUlIWgHqZNuUcH0yJNS9U4",
"country" : "Albania",
"location" : {
    "longitude" : 118.8775183,
    "latitude" : 75.4316019
}}
</code>```

The collection is indexed on (country, location.longitude) pair.

The following two queries, which I would consider identical and which produce identical output, differ in execution time by a factor of 100:

```<code>db.testData.aggregate(
[
    { $match : {country : "Brazil"} },
    { $sort : { "location.longitude" : 1 } },
    { $project : {"_id" : 0, "country" : 1, "location.longitude" : 1} }
]);
</code>```

(this one produces output within about 6 seconds for the repeated query and about 120 seconds for the first-time query)

```<code>db.testData.find(
    { country : "Brazil" },
    {"_id" : 0, "country" : 1, "location.longitude" : 1}
).sort(
    {"location.longitude" : 1}
);
</code>```

(this one produces output within 15 milliseconds for the repeated query and about 1 second for the first-time query).

What am I missing here? Thanx for any feedback.

答:
MongoDB find operation is used to fetch documents from a collection according to filters .
MongoDB aggregation groups values from a collection and performs computation on group of values through execution of stages in pipeline and return computed result.

MongoDB find operation performs speedily as compared to aggregation operation as aggregate operation encapsulates multiple stages into pipeline  which performs computation on data stored into collection with each stage's output serving as input to another stage and return processed result.
Mongo DB find operation returns a cursor to fetched documents that match filters and cursor is iterated to access document.

According to above mentioned description  we need to fetch only those  documents where value of country key is Brazil and sort documents according to values of longitude key in ascending order which can be accomplished easily using MongoDB find operation.

Body:
My collection testData has some 4 milion documents with the identical structure:

{"_id" : ObjectId("5932c56571f5a268cea12226"),
"x" : 1.0,
"text" : "w592cQzC5aAfZboMujL3knCUlIWgHqZNuUcH0yJNS9U4",
"country" : "Albania",
"location" : {
    "longitude" : 118.8775183,
    "latitude" : 75.4316019
}}

The collection is indexed on (country, location.longitude) pair.

The following two queries, which I would consider identical and which produce identical output, differ in execution time by a factor of 100:

db.testData.aggregate(
[
    { $match : {country : "Brazil"} },
    { $sort : { "location.longitude" : 1 } },
    { $project : {"_id" : 0, "country" : 1, "location.longitude" : 1} }
]);

(this one produces output within about 6 seconds for the repeated query and about 120 seconds for the first-time query)

db.testData.find(
    { country : "Brazil" },
    {"_id" : 0, "country" : 1, "location.longitude" : 1}
).sort(
    {"location.longitude" : 1}
);

(this one produces output within 15 milliseconds for the repeated query and about 1 second for the first-time query).

What am I missing here? Thanx for any feedback.


问:
Find a path of robot in a grid algorithm
While doing this exercice from cracking the coding interview:

a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limit" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

Code:

```<code>static int[][] MOVES = new int[][] { { 1, 0 }, { 0, 1 } };

private boolean isSafe(boolean[][] GRID, Point current) {
    if (current.row < 0 || current.row >= GRID.length
        || current.col < 0 || current.col >= GRID[0].length
                      || !GRID[current.row][current.col]) {
            return false;
    }
    return true;
}

/*** Check if there is a Path **/
public boolean getPath(boolean[][] grid, Point start, Point end, List<Point> path) {
    // if already reached, return true. The caller will print the path
    if (start.equals(end)) {
         return true;
    }
    // try out all the moves from the array.
    for (int i = 0; i < MOVES.length; i++) {
        int newRow = start.row + MOVES[i][0];
        int newCol = start.col + MOVES[i][1];
        Point current = new Point(newRow, newCol);
        // if it is safe to move, move forward
        if (isSafe(grid, current)) {
           // recursively try next targets and keep moving
           if (getPath(grid, current, end, path)) {
              // if the path lands up to destination,
              // then the current position was also responsible for that,
              // hence add it to the path.
              path.add(current);
              return true;
           }
        }
    }
    return false;
}

public class Point {

    int row, col;

    public Point(int row, int col) {
        super();
        this.row = row;
        this.col = col;
    }
}
</code>```

And to test:

```<code>boolean[][] GRID = new boolean[][] {
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true } };

Point start = new Point(0, 0);
Point end = new Point(GRID.length - 1, GRID[0].length - 1);
List<Point> path = new ArrayList<Point>();
path.add(start);
algo.getPath(GRID, start, end, path);
System.out.println( algo.getPath(GRID, start, end, path));
</code>```

I always get false as a result. I don't understand what's wrong with the code.

答:
This condition will never be true:

```<code>if (start.equals(end)) {
    return true;
}
</code>```

Because you did not override equals in Point.
The class inherits the default implementation of Object.equals,
and so two distinct instances of Point will never be equal,
because there is no logic anywhere to compare their row and col fields.

Body:
While doing this exercice from cracking the coding interview:

a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limit" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

Code:

static int[][] MOVES = new int[][] { { 1, 0 }, { 0, 1 } };

private boolean isSafe(boolean[][] GRID, Point current) {
    if (current.row < 0 || current.row >= GRID.length
        || current.col < 0 || current.col >= GRID[0].length
                      || !GRID[current.row][current.col]) {
            return false;
    }
    return true;
}

/*** Check if there is a Path **/
public boolean getPath(boolean[][] grid, Point start, Point end, List<Point> path) {
    // if already reached, return true. The caller will print the path
    if (start.equals(end)) {
         return true;
    }
    // try out all the moves from the array.
    for (int i = 0; i < MOVES.length; i++) {
        int newRow = start.row + MOVES[i][0];
        int newCol = start.col + MOVES[i][1];
        Point current = new Point(newRow, newCol);
        // if it is safe to move, move forward
        if (isSafe(grid, current)) {
           // recursively try next targets and keep moving
           if (getPath(grid, current, end, path)) {
              // if the path lands up to destination,
              // then the current position was also responsible for that,
              // hence add it to the path.
              path.add(current);
              return true;
           }
        }
    }
    return false;
}

public class Point {

    int row, col;

    public Point(int row, int col) {
        super();
        this.row = row;
        this.col = col;
    }
}

And to test:

boolean[][] GRID = new boolean[][] {
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true },
        { true, true, true, true, true, true } };

Point start = new Point(0, 0);
Point end = new Point(GRID.length - 1, GRID[0].length - 1);
List<Point> path = new ArrayList<Point>();
path.add(start);
algo.getPath(GRID, start, end, path);
System.out.println( algo.getPath(GRID, start, end, path));

I always get false as a result. I don't understand what's wrong with the code.

Body:
This condition will never be true:

if (start.equals(end)) {
    return true;
}

Because you did not override equals in Point.
The class inherits the default implementation of Object.equals,
and so two distinct instances of Point will never be equal,
because there is no logic anywhere to compare their row and col fields.


问:
Ziparchive for multiple files into memory stream
I have studied the answers to similar questions, but have not seen one where multiple files are gathered into an ziparchive for transmission to download. The following gives no errors but does not return a recognizable zip file.</p>

```<code>public async Task<HttpResponseMessage> SendAZipOfFiles()
{
      var memoryStream = new MemoryStream();
      var response = new HttpResponseMessage(HttpStatusCode.OK);

      List<string> filepaths = await GetSomeFiles();
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
      {
          foreach (string filepath in filepaths)
          {
               string filename = Path.GetFileName(filepath);
               using (StreamReader reader = new StreamReader(filepath))
               using (StreamWriter writer = new StreamWriter(archive.CreateEntry(filename).Open()))
               {
                    writer.Write(reader.ReadToEnd());
               }
          }
      }
      memoryStream.Position = 0;
      response.Content = new StreamContent(memoryStream);
      response.Content.Headers.ContentLength = memoryStream.Length;
      response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
      {
          FileName = "TheFile.zip")
      };
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     return response;
}
</code>```

答:
I see you are using StreamReader and StreamWriter, which not only are useless for your purpose, but may create encoding problems because they are specifically used to read and write Text files.

If you need to add to your archive any kind of file and not only plain text files they may corrupt the data when reading/writing.

Instead, just copy raw streams to archive entries:

```<code>public async Task<HttpResponseMessage> SendAZipOfFiles()
{
    var memoryStream = new MemoryStream();
    var response = new HttpResponseMessage(HttpStatusCode.OK);

    List<string> filepaths = await GetSomeFiles();
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        foreach (string filepath in filepaths)
        {
             string filename = Path.GetFileName(filepath);
             var entry = archive.CreateEntry(filename);
             using (var file = File.OpenRead(filename))
             using (var entryStream = entry.Open())
             {
                  await file.CopyToAsync(entryStream);
             }
        }
    }
    memoryStream.Position = 0;
    response.Content = new StreamContent(memoryStream);
    response.Content.Headers.ContentLength = memoryStream.Length;
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "TheFile.zip")
    };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    return response;
}
</code>```

Body:
I have studied the answers to similar questions, but have not seen one where multiple files are gathered into an ziparchive for transmission to download. The following gives no errors but does not return a recognizable zip file.

public async Task<HttpResponseMessage> SendAZipOfFiles()
{
      var memoryStream = new MemoryStream();
      var response = new HttpResponseMessage(HttpStatusCode.OK);

      List<string> filepaths = await GetSomeFiles();
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
      {
          foreach (string filepath in filepaths)
          {
               string filename = Path.GetFileName(filepath);
               using (StreamReader reader = new StreamReader(filepath))
               using (StreamWriter writer = new StreamWriter(archive.CreateEntry(filename).Open()))
               {
                    writer.Write(reader.ReadToEnd());
               }
          }
      }
      memoryStream.Position = 0;
      response.Content = new StreamContent(memoryStream);
      response.Content.Headers.ContentLength = memoryStream.Length;
      response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
      {
          FileName = "TheFile.zip")
      };
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     return response;
}

Body:
I see you are using StreamReader and StreamWriter, which not only are useless for your purpose, but may create encoding problems because they are specifically used to read and write Text files.

If you need to add to your archive any kind of file and not only plain text files they may corrupt the data when reading/writing.

Instead, just copy raw streams to archive entries:

public async Task<HttpResponseMessage> SendAZipOfFiles()
{
    var memoryStream = new MemoryStream();
    var response = new HttpResponseMessage(HttpStatusCode.OK);

    List<string> filepaths = await GetSomeFiles();
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        foreach (string filepath in filepaths)
        {
             string filename = Path.GetFileName(filepath);
             var entry = archive.CreateEntry(filename);
             using (var file = File.OpenRead(filename))
             using (var entryStream = entry.Open())
             {
                  await file.CopyToAsync(entryStream);
             }
        }
    }
    memoryStream.Position = 0;
    response.Content = new StreamContent(memoryStream);
    response.Content.Headers.ContentLength = memoryStream.Length;
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "TheFile.zip")
    };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    return response;
}


问:
keras with tensorflow : a CUDA runtime call was likely performed without using a StreamExecutor context
I am using kears with tensorflow backend, and following is the problem. Is there any can solve this problem, thanks!

答:
The error is caused by a illegal value of CNMEM. According to theano doc, CNMEM can only be assigned as a float.

0: not enabled.

0 < N <= 1: use this fraction of the total GPU memory (clipped to .95 for driver memory).

1: use this number in megabytes (MB) of memory.

You can also refer to here.

The warning is due to a change in Theano (Kera's backend). It will change from CUDA to GpuArray. You can refer to here for a solution.

Actually if you fix the warning, the error will disappear as well according to:

This value allocates GPU memory ONLY when using (CUDA backend) and has no effect when the GPU backend is (GpuArray Backend). For the new backend, please see config.gpuarray.preallocate


问:
alignment is getting messed up in the menu header
I am working on menu header but somehow all my elements are not getting aligned in one horizontal line. They are getting shown just below each other. Here is my jsfiddle

Below is my HTML:

```<code><div class="topnav">
    <img src="https://s4.postimg.org/ojd13poal/northman_wordmark_CMYK.png">
    <nav>
        <ul>
            <li class="dropdown">
                <a href="#"><b>INSURANCE</b> <i class="fa fa-angle-down"></i></a>
                <ul class="dropdown-content">
                    <li><a href="#"><i>INDIVIDUAL</i></a>
                    </li>
                    <li><a href="#"><i>CORPORATE</i></a>
                    </li>
                </ul>
            </li>
            <li class="our-story">OUR STORY</li>
            <li class="login-signup">Log In | Sign up</li>
            <li class="get-covered">GET <strong style="font-style:italic">COVERED</strong>
            </li>
        </ul>
    </nav>
</div>
</code>```

And here is my CSS:

```<code>@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
}
.topnav > img,
nav {
    display: inline-block;
    vertical-align: middle;
}
nav > ul {
    margin: 0;
}
.topnav .dropdown {
    display: block;
    float: left;
    text-align: center;
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}
li.insurance {
    padding-top: 30px !important;
}
li.our-story {
    padding-top: 30px !important;
}
li.login-signup {
    padding-top: 30px !important;
}
li.get-covered {
    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important;
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}
</code>```

I want everything to be aligned horizontally in one line in the menu header. As an example look at this image, it is slightly tilted but you will get an idea how my menu header looks on that black background.

答:
Add the following to your CSS:</p>

```<code>nav > ul > li {
  display:inline-block;
}
</code>```

Body:
I am working on menu header but somehow all my elements are not getting aligned in one horizontal line. They are getting shown just below each other. Here is my jsfiddle

Below is my HTML:

                INSURANCE

INDIVIDUAL

CORPORATE

OUR STORY

Log In | Sign up

GET COVERED

And here is my CSS:

@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
}
.topnav > img,
nav {
    display: inline-block;
    vertical-align: middle;
}
nav > ul {
    margin: 0;
}
.topnav .dropdown {
    display: block;
    float: left;
    text-align: center;
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}
li.insurance {
    padding-top: 30px !important;
}
li.our-story {
    padding-top: 30px !important;
}
li.login-signup {
    padding-top: 30px !important;
}
li.get-covered {
    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important;
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}

I want everything to be aligned horizontally in one line in the menu header. As an example look at this image, it is slightly tilted but you will get an idea how my menu header looks on that black background.

Body:
Add the following to your CSS:

nav > ul > li {
  display:inline-block;
}


问:
How to load controller in Angular 1.6 (Argument 'simpleController' is not a function, got undefined)
I am trying to learn AngularJS, I have View1 which uses simpleController, but AngularJS (1.6) is throwing an error and I can't find the right syntax to make it work.

My Repository is: https://github.com/tommcclean/Learning_Angular.

Error: ng:areq. Bad Argument. Argument 'simpleController' is not a
  function, got undefined

View1 contains...

```<code><div ng-controller="simpleController as ctrl">
    <h2>View One</h2>

    <p>{{ ctrl.testValue }}</p>
</div>
</code>```

simpleController contains...

```<code>"use strict";

(function () {
    angular.module('demoApp').controller('simpleController', []);

    function simpleController() {
        var self = this;

        self.testValue = "Test Value";

        self.updateValue = function () {
            self.testValue = "Test Value Updated";
        };

        return self;
    };
});
</code>```

demoApp is created by my routes.js file which is loaded first.

```<code>"use strict";

var app = angular.module('demoApp', ["ngRoute"]);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/view1',
        {
            controller: 'simpleController',
            templateUrl: '../views/view1.html'
        })
        .otherwise({ redirectTo: '/view1' });
});
</code>```

My main page which is the home of my "spa" contains...

```<code><!DOCTYPE html>
<html>

<head>
    <title>Sample Demo Application</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>

<body ng-app="demoApp" class="container">
    <h1>Welcome to my Sample Application</h1>

    <a href="#!view1">View 1</a>

    <div ng-view></div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
    <script src="../app/initialise/routes.js"></script>
    <script src="../app/controllers/simpleController.js"></script>

    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>

</html>
</code>```

答:
Check out the .controller definition should have the function not an empty array as the second argument.

```<code>"use strict";

(function () {
    angular.module('demoApp').controller('simpleController', simpleController);

    function simpleController() {
        var self = this;

        self.testValue = "Test Value";

        self.updateValue = function () {
            self.testValue = "Test Value Updated";
        };

        return self;
    };
});
</code>```

"use strict";

var app = angular.module('demoApp', ["ngRoute"]);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/view1',
        {
            controller: 'simpleController',
            controllerAs: 'ctrl',
            templateUrl: '/view1.html'
        })
        .otherwise({ redirectTo: '/view1' });
});

(function () {
    function simpleController() {
        var self = this;

        self.testValue = "Test Value";

        self.updateValue = function () {
            self.testValue = "Test Value Updated";
        };

        return self;
    };
    angular.module('demoApp').controller('simpleController', simpleController);

})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body ng-app="demoApp" class="container">
    <h1>Welcome to my Sample Application</h1>

    View 1

    <div ng-view></div>

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

    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>

    <script type="text/ng-template" id="/view1.html">

<div>
    <h2>View One</h2>

    <p>{{ ctrl.testValue }}</p>
</div>
</script>
</body></code>```

Body:
I am trying to learn AngularJS, I have View1 which uses simpleController, but AngularJS (1.6) is throwing an error and I can't find the right syntax to make it work.

My Repository is: https://github.com/tommcclean/Learning_Angular.

Error: ng:areq. Bad Argument. Argument 'simpleController' is not a
  function, got undefined

View1 contains...

View One

{{ ctrl.testValue }}

simpleController contains...

"use strict";

(function () {
    angular.module('demoApp').controller('simpleController', []);

    function simpleController() {
        var self = this;

        self.testValue = "Test Value";

        self.updateValue = function () {
            self.testValue = "Test Value Updated";
        };

        return self;
    };
});

demoApp is created by my routes.js file which is loaded first.

"use strict";

var app = angular.module('demoApp', ["ngRoute"]);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/view1',
        {
            controller: 'simpleController',
            templateUrl: '../views/view1.html'
        })
        .otherwise({ redirectTo: '/view1' });
});

My main page which is the home of my "spa" contains...

<!DOCTYPE html>

    <title>Sample Demo Application</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Welcome to my Sample Application

    View 1

Body:
Check out the .controller definition should have the function not an empty array as the second argument.

"use strict";

(function () {
    angular.module('demoApp').controller('simpleController', simpleController);

    function simpleController() {
        var self = this;

        self.testValue = "Test Value";

        self.updateValue = function () {
            self.testValue = "Test Value Updated";
        };

        return self;
    };
});

"use strict";

var app = angular.module('demoApp', ["ngRoute"]);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/view1',
        {
            controller: 'simpleController',
            controllerAs: 'ctrl',
            templateUrl: '/view1.html'
        })
        .otherwise({ redirectTo: '/view1' });
});

(function () {
    function simpleController() {
        var self = this;

        self.testValue = "Test Value";

        self.updateValue = function () {
            self.testValue = "Test Value Updated";
        };

        return self;
    };
    angular.module('demoApp').controller('simpleController', simpleController);

})();

<body ng-app="demoApp" class="container">
    <h1>Welcome to my Sample Application</h1>

    <a href="#!view1">View 1</a>

    <div ng-view></div>

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

    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>

    <script type="text/ng-template" id="/view1.html">

<div>
    <h2>View One</h2>

    <p>{{ ctrl.testValue }}</p>
</div>
</script>
</body>


问:
Augmented Reality : Recognize hand written number?
I am trying to find a solution for this AR app as the topic tells.

I want my app to recognize a hand-written number by the user.

The app will tell the user to write down for example number 24 on a paper and move the camera over the written number to see the 3d object.

This might be used for saving a Birthday, a wedding date .. etc

For accuracy, the app instructions will show the user a preview to tell please write the number 24 similar to this..

Although each hand writing will differ, but at least we do not get curly "2"-s or "4" with an open edge ..etc

So here we need AR to recognize the number, or be able to read the number according to approximation.

And the first question is: Is such a behavior doable or anyone familiar with a similar concept?

After searching similar apps, I found "Ink Hunter" apps for tatoo preview-s, although these apps use symbols not number, but we can think of a number as a symbol as well.

Also as this video: https://www.youtube.com/watch?v=9rXJcIE2Fcs shows, each user draws the symbol in a different way and still they get it working.

I am using Unity3d and Vuforia.
Vuforia offers free samples(unity3d packages) on the website, and there is one named "Text Recognition" , and here's the tutorial link: https://www.youtube.com/watch?v=W3MK6nC5FWE

But unfortunately couldn't make it work.

If someone has developed such a functionality using these sample projects from vuforia or have any ulternative method please I need you help :)

thanks in advance moghes

答:
Here's a tutorial our team created on text recognition using the Hololens and Vuforia with Unity: https://www.youtube.com/watch?v=WdMeHgD4fMY. In the first portion of the video, we show how to get text recognition working with just Vuforia and Unity - no Hololens required. For your application, just change the text to numbers.

I believe the biggest challenge you will have is the "hand-written" component. From our research, Vuforia prefers computer-generated, predefined font types.


问:
php-fpm and nginx session problems
I've been having this problem for the past week or so. I've been working on a PHP project that relies HEAVILY on Sessions. For some reason we've been having troubles with the sessions saving the past few days. Any idea why?

Here's the error:

```<code>Warning: Unknown: open(/tmp/sess_mmd0ru5pl2h2h9bummcu1uu620, O_RDWR) failed: Permission denied (13) in Unknown on line 0 Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0
Warning: session_start(): open(/tmp/sess_mmd0ru5pl2h2h9bummcu1uu620, O_RDWR) failed: Permission denied (13)
</code>```

nginx version:

```<code>nginx version: nginx/1.0.11
</code>```

PHP-FPM config:

```<code>;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;

; All relative paths in this configuration file are relative to PHP's install
; prefix.

; Include one or more files. If glob(3) exists, it is used to include a bunch of
; files from a glob(3) pattern. This directive can be used everywhere in the
; file.
include=/etc/php-fpm.d/*.conf

;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;

[global]
; Pid file
; Default Value: none
pid = /var/run/php-fpm/php-fpm.pid

; Error log file
; Default Value: /var/log/php-fpm.log
error_log = /var/log/php-fpm/error.log

; Log level
; Possible Values: alert, error, warning, notice, debug
; Default Value: notice
;log_level = notice

; If this number of child processes exit with SIGSEGV or SIGBUS within the time
; interval set by emergency_restart_interval then FPM will restart. A value
; of '0' means 'Off'.
; Default Value: 0
;emergency_restart_threshold = 0

; Interval of time used by emergency_restart_interval to determine when
; a graceful restart will be initiated.  This can be useful to work around
; accidental corruptions in an accelerator's shared memory.
; Available Units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;emergency_restart_interval = 0

; Time limit for child processes to wait for a reaction on signals from master.
; Available units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;process_control_timeout = 0

; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
;daemonize = yes

;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;

; See /etc/php-fpm.d/*.conf
</code>```

nginx.conf:

```<code>#######################################################################
#
# This is the main Nginx configuration file.
#
# More information about the configuration options is available on
#   * the English wiki - http://wiki.nginx.org/Main
#   * the Russian documentation - http://sysoev.ru/nginx/
#
#######################################################################

#----------------------------------------------------------------------
# Main Module - directives that cover basic functionality
#
#   http://wiki.nginx.org/NginxHttpMainModule
#
#----------------------------------------------------------------------

user              nginx nginx;
worker_processes  5;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;

#----------------------------------------------------------------------
# Events Module
#
#   http://wiki.nginx.org/NginxHttpEventsModule
#
#----------------------------------------------------------------------

events {
    worker_connections  4096;
}

#----------------------------------------------------------------------
# HTTP Core Module
#
#   http://wiki.nginx.org/NginxHttpCoreModule
#
#----------------------------------------------------------------------

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

        index index.php index.html index.htm;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    # Load config files from the /etc/nginx/conf.d directory
    # The default server is in conf.d/default.conf
    include /etc/nginx/conf.d/*.conf;
        server {
                listen 80;
                server_name stats.smilingdevil.com;

                error_page   404   /404.php;

                root /var/www;

                access_log /var/log/nginx/access.log;
                error_log /var/log/nginx/error.log;

                location / {
                        set $page_to_view "/index.php";
                        try_files $uri $uri/ @rewrites;
                        root /var/www/;
                        index index.php;
                }

                location @rewrites {
                        if ($uri ~* ^/([a-z0-9]+)$) {
                                set $page_to_view "/$1.php";
                                rewrite ^/([a-z]+)$ /$1.php last;
                        }
                }

                location ~ \.php$ {
                        include /etc/nginx/fastcgi.conf;
                        fastcgi_pass 127.0.0.1:9000;
                        fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name;
                }
        }
}
</code>```

答:
Just change the ownership of /var/lib/php/session/ to nginx from apache instead of giving a world read.</p>
```<code>sudo chown -R nginx:nginx /var/lib/php/session/
</code>```

Title: php-fpm and nginx session problems

Body:
I've been having this problem for the past week or so. I've been working on a PHP project that relies HEAVILY on Sessions. For some reason we've been having troubles with the sessions saving the past few days. Any idea why?

Here's the error:

Warning: Unknown: open(/tmp/sess_mmd0ru5pl2h2h9bummcu1uu620, O_RDWR) failed: Permission denied (13) in Unknown on line 0 Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0
Warning: session_start(): open(/tmp/sess_mmd0ru5pl2h2h9bummcu1uu620, O_RDWR) failed: Permission denied (13)

nginx version:

nginx version: nginx/1.0.11

PHP-FPM config:

;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;

; All relative paths in this configuration file are relative to PHP's install
; prefix.

; Include one or more files. If glob(3) exists, it is used to include a bunch of
; files from a glob(3) pattern. This directive can be used everywhere in the
; file.
include=/etc/php-fpm.d/*.conf

;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;

[global]
; Pid file
; Default Value: none
pid = /var/run/php-fpm/php-fpm.pid

; Error log file
; Default Value: /var/log/php-fpm.log
error_log = /var/log/php-fpm/error.log

; Log level
; Possible Values: alert, error, warning, notice, debug
; Default Value: notice
;log_level = notice

; If this number of child processes exit with SIGSEGV or SIGBUS within the time
; interval set by emergency_restart_interval then FPM will restart. A value
; of '0' means 'Off'.
; Default Value: 0
;emergency_restart_threshold = 0

; Interval of time used by emergency_restart_interval to determine when
; a graceful restart will be initiated.  This can be useful to work around
; accidental corruptions in an accelerator's shared memory.
; Available Units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;emergency_restart_interval = 0

; Time limit for child processes to wait for a reaction on signals from master.
; Available units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;process_control_timeout = 0

; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
;daemonize = yes

;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;

; See /etc/php-fpm.d/*.conf

nginx.conf:

#######################################################################
#
# This is the main Nginx configuration file.
#
# More information about the configuration options is available on
#   * the English wiki - http://wiki.nginx.org/Main
#   * the Russian documentation - http://sysoev.ru/nginx/
#
#######################################################################

#----------------------------------------------------------------------
# Main Module - directives that cover basic functionality
#
#   http://wiki.nginx.org/NginxHttpMainModule
#
#----------------------------------------------------------------------

user              nginx nginx;
worker_processes  5;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;

#----------------------------------------------------------------------
# Events Module
#
#   http://wiki.nginx.org/NginxHttpEventsModule
#
#----------------------------------------------------------------------

events {
    worker_connections  4096;
}

#----------------------------------------------------------------------
# HTTP Core Module
#
#   http://wiki.nginx.org/NginxHttpCoreModule
#
#----------------------------------------------------------------------

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

        index index.php index.html index.htm;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    # Load config files from the /etc/nginx/conf.d directory
    # The default server is in conf.d/default.conf
    include /etc/nginx/conf.d/*.conf;
        server {
                listen 80;
                server_name stats.smilingdevil.com;

                error_page   404   /404.php;

                root /var/www;

                access_log /var/log/nginx/access.log;
                error_log /var/log/nginx/error.log;

                location / {
                        set $page_to_view "/index.php";
                        try_files $uri $uri/ @rewrites;
                        root /var/www/;
                        index index.php;
                }

                location @rewrites {
                        if ($uri ~* ^/([a-z0-9]+)$) {
                                set $page_to_view "/$1.php";
                                rewrite ^/([a-z]+)$ /$1.php last;
                        }
                }

                location ~ \.php$ {
                        include /etc/nginx/fastcgi.conf;
                        fastcgi_pass 127.0.0.1:9000;
                        fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name;
                }
        }
}

Body:
Just change the ownership of /var/lib/php/session/ to nginx from apache instead of giving a world read.

sudo chown -R nginx:nginx /var/lib/php/session/

ContentLicense: CC BY-SA 4.0


问:
Karma clear screen before running tests
I use karma to run jasmine specs. Every time a file changes the tests are run. This is awesome but it would be even better if the previous test output would be removed from the terminal.

Is there a way to clear the terminal before tests are run in karma?

答:
The issue @Sylvain has created is still open, but there is a plugin karma-clear-screen-reporter which does the job. Internally it uses the magic:

console.log('\u001b[2J\u001b[0;0H');
```

Alternatively you can also place this at the top of your test runner code to clear the console yourself.

Title: Karma clear screen before running tests

Body:
The issue @Sylvain has created is still open, but there is a plugin karma-clear-screen-reporter which does the job. Internally it uses the magic:

console.log('\u001b[2J\u001b[0;0H');

Alternatively you can also place this at the top of your test runner code to clear the console yourself.


问:
Where is bif: URI?
Solution to my problem requires to use bif:st_intersects. I wanted to see the bif ontology i.e. to see what is it, and what is exactly st_intersect, but on dbpedia list of namespaces, bif: does not redirect to any web resource. Why?

答:
bif:st_intersects is a custom Virtuoso predicate. It works only in Virtuoso,
just as spatial:intersectBox works only in Jena. Its definition is rather operational than ontological.

Additional examples of usage: 1, 2; from 2:

PREFIX bif: <http://www.openlinksw.com/schemas/bif#>

Title: Where is bif: URI?


答:
For date type objects, you can not access that value, you can access it through the richness of an expression by following a format.

I'll explain:

```<code>$call->dateCreated->date // It is not accessible
</code>```

But if you ask the data in this form you will get the result

```<code>$call->dateCreated->format('Y-m-d H:i:s');
</code>```

Body:
I am facing an issue while trying to get value from an object in PHP. Here is the object:

DateTime Object
(
    [date] => 2017-06-03 18:33:48.000000
    [timezone_type] => 1
    [timezone] => +00:00
)

it's all in this variable $call->dateCreated

and here is how I am trying to get the value of "date" from the object:

$call->dateCreated->date;

but when I try to do this, I got an error:

Undefined property: DateTime::$date

Body:
For date type objects, you can not access that value, you can access it through the richness of an expression by following a format.

I'll explain:

$call->dateCreated->date // It is not accessible

But if you ask the data in this form you will get the result

$call->dateCreated->format('Y-m-d H:i:s');


问:
requestAnimationFrame scope change to window
I have a chain of objects that looks like this:

```<code>Game.world.update()
</code>```

I would like to use requestAnimationFrame to determine the framerate of this function.

However when I implement it like this:

```<code>World.prototype.update = function()
{
    requestAnimationFrame(this.update);
}
</code>```

The scope changes from the world object to the window object. How do I maintain the scope I want while calling requestAnimationFrame()? I know it has something to do with anonymous functions and such, but I can't get my head around it.

答:
Another way of doing this is to use a lambda expression like so:

requestAnimationFrame((timestamp) => { loop(timestamp) });

This also maintains scope but it's a bit cleaner.

Body:
I have a chain of objects that looks like this:

Game.world.update()

I would like to use requestAnimationFrame to determine the framerate of this function.

However when I implement it like this:

World.prototype.update = function()
{
    requestAnimationFrame(this.update);
}

The scope changes from the world object to the window object. How do I maintain the scope I want while calling requestAnimationFrame()? I know it has something to do with anonymous functions and such, but I can't get my head around it.


问:
Why are these templates ambiguous?
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

```<code>template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};
</code>```

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

答:
j_random_hacker has answered the question, but as a concrete example just using the standard's rules directly:

```<code>template< class T >
class Array {};

template< class T1, class T2 >
class Promotion {};

template <typename T>                   // a
class Promotion<T,T> {
public:
    typedef T ResultT;
};

template<typename T1, typename T2>      // b
class Promotion<Array<T1>, Array<T2> > {
public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

// template<typename T>
// class Promotion<Array<T>, Array<T> > {
//   public:
//     typedef Array<typename Promotion<T,T>::ResultT> ResultT;
// };

//---------------------------- §14.5.4.2/1:

template< class T >
void a_( Promotion< T, T > );                      // a

template< class T1, class T2 >
void b_( Promotion< Array< T1 >, Array< T2 > > );  // b

//---------------------------- §14.5.5.2/3:

class aT {};
class bT1 {};
class bT2 {};

void a( Promotion< aT, aT > );                          // a
void b( Promotion< Array< bT1 >, Array< bT2 > > );      // b

void test()
{
    // Check if the concrete 'a' arguments fit also 'b':
    b_( Promotion< aT, aT >() );
    // Fails, so a is not at least as specialized as b

    // Check if the concrete 'b' arguments fit also 'a':
    a_( Promotion< Array< bT1 >, Array< bT2 > >() );
    // Fails, so b is not at least as specialized as a
}
</code>```

Disclaimer: I had to re-teach myself this again.

I'm posting this because Someone Else™ found my example enlightening, so, might help also readers here.

Cheers & hth.,

Title: Why are these templates ambiguous?

Body:
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

Body:
j_random_hacker has answered the question, but as a concrete example just using the standard's rules directly:

template< class T >
class Array {};

template< class T1, class T2 >
class Promotion {};

template <typename T>                   // a
class Promotion<T,T> {
public:
    typedef T ResultT;
};

template<typename T1, typename T2>      // b
class Promotion<Array<T1>, Array<T2> > {
public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

// template<typename T>
// class Promotion<Array<T>, Array<T> > {
//   public:
//     typedef Array<typename Promotion<T,T>::ResultT> ResultT;
// };

//---------------------------- §14.5.4.2/1:

template< class T >
void a_( Promotion< T, T > );                      // a

template< class T1, class T2 >
void b_( Promotion< Array< T1 >, Array< T2 > > );  // b

//---------------------------- §14.5.5.2/3:

class aT {};
class bT1 {};
class bT2 {};

void a( Promotion< aT, aT > );                          // a
void b( Promotion< Array< bT1 >, Array< bT2 > > );      // b

void test()
{
    // Check if the concrete 'a' arguments fit also 'b':
    b_( Promotion< aT, aT >() );
    // Fails, so a is not at least as specialized as b

    // Check if the concrete 'b' arguments fit also 'a':
    a_( Promotion< Array< bT1 >, Array< bT2 > >() );
    // Fails, so b is not at least as specialized as a
}

Disclaimer: I had to re-teach myself this again.

I'm posting this because Someone Else™ found my example enlightening, so, might help also readers here.

Cheers & hth.,


问:
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed Python
I want to connect to the IRC, using SSL. I write in Python 2.7. However, for the code below:

```<code>HOST = 'chat.freenode.net'
PORT = 7000
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
code = sock.connect_ex((HOST, PORT))
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations('COMODOECCCertificationAuthority.crt')
secure_sock = context.wrap_socket(sock)
</code>```

PyCharm shows error in line secure_sock = context.wrap_socket(sock) what is wrong?

答:
context.load_verify_locations('COMODOECCCertificationAuthority.crt')

I don't know what is in the file COMODOECCCertificationAuthority.crt but it looks like you expecting a certificate signed by Comodo. But, the issuer for the certificate of chat.freenode.net is Let's Encrypt and not Comodo. You can get the chain for example with

```<code>$ openssl s_client -connect chat.freenode.net:7000
...
Certificate chain
0 s:/CN=cherryh.freenode.net
  i:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
  i:/O=Digital Signature Trust Co./CN=DST Root CA X3
</code>```

This means the root CA you need to trust is 'DST Root CA X3'. You can download the certificate for this CA here. If you add this as trusted in load_verify_locations it works.

Body:
I want to connect to the IRC, using SSL. I write in Python 2.7. However, for the code below:

HOST = 'chat.freenode.net'
PORT = 7000
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
code = sock.connect_ex((HOST, PORT))
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations('COMODOECCCertificationAuthority.crt')
secure_sock = context.wrap_socket(sock)

PyCharm shows error in line secure_sock = context.wrap_socket(sock) what is wrong?

Body:
context.load_verify_locations('COMODOECCCertificationAuthority.crt')

I don't know what is in the file COMODOECCCertificationAuthority.crt but it looks like you expecting a certificate signed by Comodo. But, the issuer for the certificate of chat.freenode.net is Let's Encrypt and not Comodo. You can get the chain for example with

$ openssl s_client -connect chat.freenode.net:7000
...
Certificate chain
0 s:/CN=cherryh.freenode.net
  i:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
  i:/O=Digital Signature Trust Co./CN=DST Root CA X3

This means the root CA you need to trust is 'DST Root CA X3'. You can download the certificate for this CA here. If you add this as trusted in load_verify_locations it works.


问:
Actionbar menu buttons not able to navigate to other Activities (Android)
I'm using a menu for the actionbar, and here is my xml mainactivity.xml under menus:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id = "@+id/Viewmain"
        android:orderInCategory="200"
        app:showAsAction="always"
        android:title="VIEW"/>

    <item
        android:id = "@+id/Addmain"
        android:orderInCategory="205"
        app:showAsAction="always"
        android:title="ADD"/>

</menu>
</code>```

Here is the code I used to navigate the buttons on the actionbar to other Activities in mainactivity.java:

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

   }

    public boolean onContextItemSelected (MenuItem item)
    {

        if (item.getItemId()==200)
        {
            Intent myintent = new Intent(this, ViewStats.class );
            startActivity(myintent);
            return  true;
        }
        else if (item.getItemId()==205)
        {
            Intent myaddintent = new Intent(this,Sales.class );
            startActivity(myaddintent);

        }

        return  super.onOptionsItemSelected(item);
    }

   public  boolean onCreateOptionsMenu(Menu menu)
   {
       super.onCreateOptionsMenu(menu);
       this.myMenu = menu;

       getMenuInflater().inflate(R.menu.main, menu);
       return  true;

   }
</code>```

However when I click on the actionbar buttons "VIEW" & "ADD", no changes occur. What is wrong with my codes? Please help. (Note: No errors were shown on the stacktrace)

答:
you have to implement following methods to options menu

for creating menu

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);///here add your menu layout
    return true;
}
</code>```

for select menu item this method need to implemented

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.new_game:
            newGame();
            return true;
        case R.id.help:
            showHelp();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
</code>```

don't add hard coded id comparison u can just add ur item id  by R.id.yourid

Body:
I'm using a menu for the actionbar, and here is my xml mainactivity.xml under menus:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id = "@+id/Viewmain"
        android:orderInCategory="200"
        app:showAsAction="always"
        android:title="VIEW"/>

    <item
        android:id = "@+id/Addmain"
        android:orderInCategory="205"
        app:showAsAction="always"
        android:title="ADD"/>

</menu>

Here is the code I used to navigate the buttons on the actionbar to other Activities in mainactivity.java:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

   }

    public boolean onContextItemSelected (MenuItem item)
    {

        if (item.getItemId()==200)
        {
            Intent myintent = new Intent(this, ViewStats.class );
            startActivity(myintent);
            return  true;
        }
        else if (item.getItemId()==205)
        {
            Intent myaddintent = new Intent(this,Sales.class );
            startActivity(myaddintent);

        }

        return  super.onOptionsItemSelected(item);
    }

   public  boolean onCreateOptionsMenu(Menu menu)
   {
       super.onCreateOptionsMenu(menu);
       this.myMenu = menu;

       getMenuInflater().inflate(R.menu.main, menu);
       return  true;

   }

However when I click on the actionbar buttons "VIEW" & "ADD", no changes occur. What is wrong with my codes? Please help. (Note: No errors were shown on the stacktrace)

Body:
you have to implement following methods to options menu

for creating menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);///here add your menu layout
    return true;
}

for select menu item this method need to implemented

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.new_game:
            newGame();
            return true;
        case R.id.help:
            showHelp();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

don't add hard coded id comparison u can just add ur item id  by R.id.yourid


问:
POST method not inserting data into database table
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.

Code is attached below, would appreciate if someone could point me into the right direction.

index.php:

```<code><form action="index.php" method="post">

<label for="name">Name</label>
<input type="text" name="name" required>

<label for="breed">Breed</label>
<input type="text" name="breed">

<label for="age">Age</label>
<input type="text" name="age">

<input type="submit" name="submit" value="Submit">

</form>

<?php

require "connect.php";

if('submit') {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>
</code>```

connect.php:

```<code><?php

$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');

?>
</code>```

答: Own answer: Figured it out, I had to configure PHPStorm to use MAMP Apache server instead of the internal server since that one apparently doesn't like $_POST[] requests</p>

Body:
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.

Code is attached below, would appreciate if someone could point me into the right direction.

index.php:

<form action="index.php" method="post">

Name
<input type="text" name="name" required>

Breed
<input type="text" name="breed">

Age
<input type="text" name="age">

<input type="submit" name="submit" value="Submit">

</form>

<?php

require "connect.php";

if('submit') {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>

connect.php:

<?php

$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');

?>


问:
How should a GRPC Service be hosted?
I have created a GRPC Server in C# using the example given at Link. Now I want to figure out as how should I be hosting this server so that I achieve following:

Should I make this Server a Console application or a a Windows Service. If I make it a windows Service then updating the service will be cumbersome (which is a big negative) and if I make it a console app then updating will simply need shutting down exe. But that comes with the price of closing the same by mistake. Is there any other better way?

With IIS this issue won't b there as I can simply remove the site from LB and stop the website to perform the update but since GRPC won't be a part of IIS, I am not sure what's the way to get this working.

Any references for the better architecture are welcomed.

答:
I'm going to add one more option.

With dot net core, you can run this as a Linux Daemon now.

Title: How should a GRPC Service be hosted?


问:
How to take data from a form in order to search and filter in MongoDB
I am trying to take the data from a form in order to use that data as a filter and redirect to the page that contains the table with all the filtered data. I am using Django 1.10.5, Python 3.6 and MongoDB with Pymongo. I don't want to save the data of the form, I just need it for the filtering. This is what I have done:

<---Views--->

```<code>def BuscaProyecto(request):
form = FormBuscaProyecto(request.GET or None)
if form.is_valid():
    datos = Proyectos.objects.filter(AñoPresentación__icontains=AñoPresentación & Status__icontains=Status)
return render_to_response(request, 'blog/detail.html', {'datos':datos}))
</code>```

<---html--->

```<code><div id="Proyectos">
                        <form action="" method="get" role="form">
                            {% csrf_token %}
                            <div class="col-xs-12 col-sm-12 centered">

                                <!-- Año de Presentación -->
                                <div class="col-xs-3 col-sm-3 centered">
                                    <div class="form-group">
                                        <input name="AñoPresentación" type="date" class="form-control"/>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xs-12 col-sm-12 centered">
                            <!-- Status -->
                                <div class="col-xs-2 col-sm-2 centered">

                                    <label for="Status" class="control-label">Status</label>
                                </div>
                                <div class="col-xs-3 col-sm-3 centered">
                                    <div class="form-group">
                                        <select id="Status" name="Status" class="selectpicker form-control" data-width="100%" style="display">
                                            <option value="APROBADO">Aprobado</option>
                                            <option value="DENEGADO">Denegado</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <!-- Botón de Buscar -->
                            <div class="centered">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <span class="glyphicon glyphicon-search"></span>
                                    Buscar
                                </button>
                            </div>
</code>```

答:
After the form.valid return the datos to another template </p>

```<code>If form.is_valid():
    ....
    return render(request, 'another_template', {'datos': datos})
</code>```

Body:
I am trying to take the data from a form in order to use that data as a filter and redirect to the page that contains the table with all the filtered data. I am using Django 1.10.5, Python 3.6 and MongoDB with Pymongo. I don't want to save the data of the form, I just need it for the filtering. This is what I have done:

<---Views--->

def BuscaProyecto(request):
form = FormBuscaProyecto(request.GET or None)
if form.is_valid():
    datos = Proyectos.objects.filter(AñoPresentación__icontains=AñoPresentación & Status__icontains=Status)
return render_to_response(request, 'blog/detail.html', {'datos':datos}))

<---html--->

                        <form action="" method="get" role="form">
                            {% csrf_token %}

                                        <input name="AñoPresentación" type="date" class="form-control"/>

                                    Status

                                        <select id="Status" name="Status" class="selectpicker form-control" data-width="100%" style="display">
                                            <option value="APROBADO">Aprobado</option>
                                            <option value="DENEGADO">Denegado</option>
                                        </select>

                                <button type="submit" class="btn btn-primary btn-lg">

                                    Buscar
                                </button>

Body:
After the form.valid return the datos to another template

If form.is_valid():
    ....
    return render(request, 'another_template', {'datos': datos})


问:
java.lang.StackOverflowError due to iterator in DFS
I am currently trying to make a graph represantation of a game by creating the graph class by myself.
The constructor is this one (hope I dont have any logic mistake here):

```<code> private int nNodes;
    private int nEdges;
    private List<Integer> adj[];
    private boolean visited[];

    public GameGraph()
    {
        nNodes = 81;
        adj = new LinkedList[nNodes];
        for(int i = 0; i < nNodes; i++)
            adj[i] = new LinkedList();
        visited = new boolean[nNodes];
    }
</code>```

I check if there is a path between a source and destination by using the depth first search algorithm. This is what I wrote:

```<code> public boolean hasPath(int source , int dest)
        {
            if(source >= nNodes)
                return false;
            else
            {
                visited[source] = true;

                try
                {
                    Iterator<Integer> iterator = adj[source].listIterator();
                    while(iterator.hasNext())
                    {
                        int n = iterator.next();
                        if(n == dest)
                            return true;
                        visited[n] = true;
                        if(hasPath(n, dest))
                            return true;
                    }//end while
                    return false;
                }//end try
                catch(NullPointerException exception)
                {
                    exception.printStackTrace();
                }//end catch

                return false;
            }//end else
        }//end method has path
</code>```

The problem is that when I run this method in a main class , I have this error:

```<code>Exception in thread "main" java.lang.StackOverflowError
    at java.util.LinkedList$ListItr.<init>(Unknown Source)
    at java.util.LinkedList.listIterator(Unknown Source)
    at java.util.AbstractList.listIterator(Unknown Source)
    at java.util.AbstractSequentialList.iterator(Unknown Source)
    at logic.GameGraph.hasPath(GameGraph.java:67)
    at logic.GameGraph.hasPath(GameGraph.java:74)at logic.GameGraph.hasPath(GameGraph.java:74)
    at logic.GameGraph.hasPath(GameGraph.java:74)
    at logic.GameGraph.hasPath(GameGraph.java:74)
</code>```

line 67 is:

```<code>   Iterator<Integer> iterator = adj[source].listIterator();
</code>```

And line 74 is the recursive call:

```<code>if(hasPath(n, dest))
</code>```

I read about StackOverflowError and it had something to do with lack of memory available , I understand that one and my question is not that. But I don't understand why it should happen here cause of the iterator. I tried it even with nodes that are close to each other which make just a few recursive calls, and the same error occurs.

答:
Before going into recursive call check if you have already covered that node by using </p>

```<code>....
int n = iterator.next();
if(!visited[n]){
...
}
</code>```

Body:
I am currently trying to make a graph represantation of a game by creating the graph class by myself.
The constructor is this one (hope I dont have any logic mistake here):

 private int nNodes;
    private int nEdges;
    private List<Integer> adj[];
    private boolean visited[];

    public GameGraph()
    {
        nNodes = 81;
        adj = new LinkedList[nNodes];
        for(int i = 0; i < nNodes; i++)
            adj[i] = new LinkedList();
        visited = new boolean[nNodes];
    }

I check if there is a path between a source and destination by using the depth first search algorithm. This is what I wrote:

 public boolean hasPath(int source , int dest)
        {
            if(source >= nNodes)
                return false;
            else
            {
                visited[source] = true;

                try
                {
                    Iterator<Integer> iterator = adj[source].listIterator();
                    while(iterator.hasNext())
                    {
                        int n = iterator.next();
                        if(n == dest)
                            return true;
                        visited[n] = true;
                        if(hasPath(n, dest))
                            return true;
                    }//end while
                    return false;
                }//end try
                catch(NullPointerException exception)
                {
                    exception.printStackTrace();
                }//end catch

                return false;
            }//end else
        }//end method has path

The problem is that when I run this method in a main class , I have this error:

Exception in thread "main" java.lang.StackOverflowError
    at java.util.LinkedList$ListItr.<init>(Unknown Source)
    at java.util.LinkedList.listIterator(Unknown Source)
    at java.util.AbstractList.listIterator(Unknown Source)
    at java.util.AbstractSequentialList.iterator(Unknown Source)
    at logic.GameGraph.hasPath(GameGraph.java:67)
    at logic.GameGraph.hasPath(GameGraph.java:74)at logic.GameGraph.hasPath(GameGraph.java:74)
    at logic.GameGraph.hasPath(GameGraph.java:74)
    at logic.GameGraph.hasPath(GameGraph.java:74)

line 67 is:

   Iterator<Integer> iterator = adj[source].listIterator();

And line 74 is the recursive call:

if(hasPath(n, dest))

I read about StackOverflowError and it had something to do with lack of memory available , I understand that one and my question is not that. But I don't understand why it should happen here cause of the iterator. I tried it even with nodes that are close to each other which make just a few recursive calls, and the same error occurs.

Body:
Before going into recursive call check if you have already covered that node by using

....
int n = iterator.next();
if(!visited[n]){
...
}