问:
Can I make a <button> not submit a form?
I've got a form, with 2 buttons

```<code><a href="index.html"><button>Cancel changes</button></a>

<button type="submit">Submit</button>
</code>```

I use jQuery UI's button on them too, simply like this

```<code>$('button').button();
</code>```

However, the first button also submits the form. I would have thought that if it didn't have the type="submit", it wouldn't.

Obviously I could do this

```<code>$('button[type!=submit]').click(function(event) { event.stopPropagation(); });
</code>```

But is there a way I can stop that back button from submitting the form without JavaScript intervention?

To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).

答:
```<code>  <form class="form-horizontal" method="post">
        <div class="control-group">

            <input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
        </div>
        <div class="control-group">
            <input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
        </div>
        <div class="control-group">
            <input type="text" class="span1" name="unit" id="inputPassword" required>
        </div>
            <div class="control-group">
            <label class="control-label" for="inputPassword">Semester</label>
            <div class="controls">
                <select name="semester">
                    <option></option>
                    <option>1st</option>
                    <option>2nd</option>
                </select>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="inputPassword">Deskripsi</label>
            <div class="controls">
                    <textarea name="description" id="ckeditor_full"></textarea>
 <script>CKEDITOR.replace('ckeditor_full');</script>
            </div>
        </div>

        <div class="control-group">
        <div class="controls">

        <button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
        </div>
        </div>
        </form>

        <?php
        if (isset($_POST['save'])){
        $subject_code = $_POST['subject_code'];
        $title = $_POST['title'];
        $unit = $_POST['unit'];
        $description = $_POST['description'];
        $semester = $_POST['semester'];

        $query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
        $count = mysql_num_rows($query);

        if ($count > 0){ ?>
        <script>
        alert('Data Sudah Ada');
        </script>
        <?php
        }else{
        mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());

        mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());

        ?>
        <script>
        window.location = "subjects.php";
        </script>
        <?php
        }
        }

        ?>
</code>```

Body:
I've got a form, with 2 buttons

<button>Cancel changes</button>

<button type="submit">Submit</button>

I use jQuery UI's button on them too, simply like this

$('button').button();

However, the first button also submits the form. I would have thought that if it didn't have the type="submit", it wouldn't.

Obviously I could do this

$('button[type!=submit]').click(function(event) { event.stopPropagation(); });

But is there a way I can stop that back button from submitting the form without JavaScript intervention?

To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).


来源: stackexchange

问:
accessing list in python 3
I'm storing key and value in a dictionary called campaign_name, then access the value using randvalue. That works fine. But when I try to access certain element in the randvalue, let's say randvalue[0] or randvalue[1] it would throw an error.

I can print(randvalue) perfectly and the value would show like this [[16949.070963, 2694507, 76606]]. But I can't print just 16949.070963. My complete section of code is as follows: Thanks for the help.

```<code>  def startchecking():
        storepast()
        # loading file into opepyxl
        ref_workbook = openpyxl.load_workbook(path)
        # Grab all the sheet name in the workbook
        workbook_tab = ref_workbook.get_sheet_names()
        for i in workbook_tab:
            ws = ref_workbook[i]
            randvalue=campaign_name.get(str(ws['B4'].value))
            print(randvalue)
            temptext = "Starting Check" + str(ws)
            textoutput(temptext)
        checkdaily(45, 52)
</code>```

答:
It looks like that randvalue is a list in list. So try to print

print(randvalue[0][0])

so it will print 16949.070963

ContentLicense: CC BY-SA 3.0

Title: accessing list in python 3

Body:
I'm storing key and value in a dictionary called campaign_name, then access the value using randvalue. That works fine. But when I try to access certain element in the randvalue, let's say randvalue[0] or randvalue[1] it would throw an error.

I can print(randvalue) perfectly and the value would show like this [[16949.070963, 2694507, 76606]]. But I can't print just 16949.070963. My complete section of code is as follows: Thanks for the help.

  def startchecking():
        storepast()
        # loading file into opepyxl
        ref_workbook = openpyxl.load_workbook(path)
        # Grab all the sheet name in the workbook
        workbook_tab = ref_workbook.get_sheet_names()
        for i in workbook_tab:
            ws = ref_workbook[i]
            randvalue=campaign_name.get(str(ws['B4'].value))
            print(randvalue)
            temptext = "Starting Check" + str(ws)
            textoutput(temptext)
        checkdaily(45, 52)


问:
How to avoid errors when just one page URL- Python - Web scraping
 Hello Everyone, I am beginner and I try to use IF ELSE function with url link in web scraping.
I want to select all the pages from de department 64 to 66.
My url is : http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/{}/0 (with {} = 64 or 65 or 66).
My loop works and select all my pages for 64. But when I am inside the 65 I saw I have only one page so my code line last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1] cannot work. here my code :

```<code>import requests
from bs4 import BeautifulSoup
url_list = ['http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/{}/0']
for link in url_list:
    r=requests.get(link)
    soup = BeautifulSoup(r.content, "html.parser")
    page_Url_test=[link.format(i) for i in range(64, 66)]
    for depart_page in page_Url_test:
        depart_page1=str(depart_page)+"?page={}"
        r=requests.get(depart_page1)
        soup = BeautifulSoup(r.content, "html.parser")
        last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
        dept_page_Url=[depart_page1.format(i) for i in range(0, int(last_page)+1)]
print(dept_page_Url)
</code>```

I tried to incorporate an IF ELSE like this:

```<code>for depart_page in page_Url_test:
    depart_page1=str(depart_page)+"?page={}"
    r=requests.get(depart_page1)
    soup = BeautifulSoup(r.content, "html.parser")
    if len(depart_page1) == 0 :
        dept_page_Url=depart_page1
    else:
        last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
        dept_page_Url=[depart_page1.format(i) for i in range(0, int(last_page)+1)]
print(dept_page_Url)
</code>```

But It doesn't work. How can I say to my code: If I have just one page select just the first one else do my next step?
Any clue ? I don't have enough knowledge to find alone...
Thank you a lot

答:
As sir t.m.adam has already pointed out, you can try like the below approach. I also have trimmed your code to make it concise.

```<code>import requests
from bs4 import BeautifulSoup

url_list = 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/{}/0'
for link in [url_list.format(page) for page in range(64,67)]:
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    depart_page = str(link) + "?page={}"
    if soup.find('ul', class_='pagination'):
        last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
        dept_page_Url = [depart_page.format(i) for i in range(0, int(last_page)+1)]
        print(dept_page_Url)
</code>```

Additional approach when in need:

```<code>if soup.find('ul', class_='pagination'):
    last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
    dept_page_Url = [depart_page.format(i) for i in range(0, int(last_page)+1)]
    print(dept_page_Url)
else:
    print(link)
</code>```

Result:

```<code>['http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/64/0?page=0', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/64/0?page=1', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/64/0?page=2']
['http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/66/0?page=0', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/66/0?page=1', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/66/0?page=2']
</code>```

Body:
 Hello Everyone, I am beginner and I try to use IF ELSE function with url link in web scraping.
I want to select all the pages from de department 64 to 66.
My url is : http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/{}/0 (with {} = 64 or 65 or 66).
My loop works and select all my pages for 64. But when I am inside the 65 I saw I have only one page so my code line last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1] cannot work. here my code :

import requests
from bs4 import BeautifulSoup
url_list = ['http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/{}/0']
for link in url_list:
    r=requests.get(link)
    soup = BeautifulSoup(r.content, "html.parser")
    page_Url_test=[link.format(i) for i in range(64, 66)]
    for depart_page in page_Url_test:
        depart_page1=str(depart_page)+"?page={}"
        r=requests.get(depart_page1)
        soup = BeautifulSoup(r.content, "html.parser")
        last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
        dept_page_Url=[depart_page1.format(i) for i in range(0, int(last_page)+1)]
print(dept_page_Url)

I tried to incorporate an IF ELSE like this:

for depart_page in page_Url_test:
    depart_page1=str(depart_page)+"?page={}"
    r=requests.get(depart_page1)
    soup = BeautifulSoup(r.content, "html.parser")
    if len(depart_page1) == 0 :
        dept_page_Url=depart_page1
    else:
        last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
        dept_page_Url=[depart_page1.format(i) for i in range(0, int(last_page)+1)]
print(dept_page_Url)

But It doesn't work. How can I say to my code: If I have just one page select just the first one else do my next step?
Any clue ? I don't have enough knowledge to find alone...
Thank you a lot

Body:
As sir t.m.adam has already pointed out, you can try like the below approach. I also have trimmed your code to make it concise.

import requests
from bs4 import BeautifulSoup

url_list = 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/{}/0'
for link in [url_list.format(page) for page in range(64,67)]:
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    depart_page = str(link) + "?page={}"
    if soup.find('ul', class_='pagination'):
        last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
        dept_page_Url = [depart_page.format(i) for i in range(0, int(last_page)+1)]
        print(dept_page_Url)

Additional approach when in need:

if soup.find('ul', class_='pagination'):
    last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
    dept_page_Url = [depart_page.format(i) for i in range(0, int(last_page)+1)]
    print(dept_page_Url)
else:
    print(link)

Result:

['http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/64/0?page=0', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/64/0?page=1', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/64/0?page=2']
['http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/66/0?page=0', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/66/0?page=1', 'http://www.pour-les-personnes-agees.gouv.fr/annuaire-accueil-de-jour/66/0?page=2']


问:
Disable all the controls in a form typescript
How to disable all the controls in a template driven form.

Tried Solutions.

using filedset and set [disabled] to that - which will not work in IE 9+.
Also using fieldset, the inputs are not disabled

```<code> <button class="icon-btn pull-right addNewBtn" type="button" title="Add New " data-toggle="modal" id="Btn" data-backdrop="false"><i (click)="Person(Code)" class="fa fa-user-plus"></i></button>

  <p-radioButton name="type" value="I" label="Inc" [(ngModel)]="type"></p-radioButton>
</code>```

I don't have a form group, so that solution also didn't work here.

Let me know Is there any other solution in AngularJS 2

答: You will need to make sure that each of your inputs understands what "disabled" means for it. Some html elements having the disabled property - like a regular html button - will react to [disabled]="condition". But for your own elements - like p-radioButton - you would need to set a certain "disabled" styling, and prevent parts of your p-radioButton (for example a surrounding div) from forwarding events which should not be forwarded if it's disabled. Then you can use ngClass and set the disabled property to every input where the disabling condition is true.</p>

Body:
How to disable all the controls in a template driven form.

Tried Solutions.

using filedset and set [disabled] to that - which will not work in IE 9+.
Also using fieldset, the inputs are not disabled

 <button class="icon-btn pull-right addNewBtn" type="button" title="Add New " data-toggle="modal" id="Btn" data-backdrop="false"></button>

I don't have a form group, so that solution also didn't work here.

Let me know Is there any other solution in AngularJS 2


问:
Load COLLADA - geometry, animation, textures - what applies?
I've been recommended to load 3D animations in the COLLADA format - I consulted the quick reference and docs for a while but I am pretty lost. What parts of the format do I actually care about if I want to:

Load all vertices

Load up all triangles or trianglestrips in the objects (relationships between verts)

load animation info of where verts move to over time

Textures and texcoord info

Also is there a file format I can convert COLLADA to that will more concisely and conveniently describe just that data? Or is it easier to pull from COLLADA format than I may think...

答: What language is your game engine in? You could look at the easy-to-understand jMonkeyEngine or Ardor3D sources, both of which support COLLADA loading. You can trace the geometry creation directly.</p>

ContentLicense: CC BY-SA 2.5


问:
Window.scroll within an iframe
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

```<code><div class="container">
        <header class="header-wrapper">
            <div class="sticky-header">
                <div class="row">
                        <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Customer Name: </label>
                            <label>Person!! </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">Address: </label>
                            <label>101 Main Street </label>
                        </div>

                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Email:</label>
                            <label>something@email.com </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">City, State:</label>
                            <label>Tavierner, FL </label>
                        </div>

                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Phone:</label>
                            <label>555-555-5555 </label>
                        </div>

                        <div class="form-group">
                            <label class="bold">Club Code:</label>
                            <label>456 </label>
                            <label class="bold">Associate#:</label>
                            <label>45 </label>
                        </div>
                    </div>
                </div>
            </div>
        </header>
  <section>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>

  </section>
</div>
</code>```

and my jquery

```<code> if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }
</code>```

A screenshot of what the menu looks like when it's not working:

答:
Try this code to get scroll offset inside iframe:</p>

```<code>$(document).ready(function()
{

    $('#yourFrameId').load(function()
    {

        var iframe = $(this).get(0);
        iframe.contentWindow.onscroll = function(evt)
        {
            console.log(evt.pageY);
        };

    });

});
</code>```

Title: Window.scroll within an iframe

Body:
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

                            Customer Name:
                            Person!!

                            Address:
                            101 Main Street

                            Email:
                            something@email.com

                            City, State:
                            Tavierner, FL

                            Phone:
                            555-555-5555

                            Club Code:
                            456
                            Associate#:
                            45

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

and my jquery

 if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }

A screenshot of what the menu looks like when it's not working:

Body:
Try this code to get scroll offset inside iframe:

$(document).ready(function()
{

    $('#yourFrameId').load(function()
    {

        var iframe = $(this).get(0);
        iframe.contentWindow.onscroll = function(evt)
        {
            console.log(evt.pageY);
        };

    });

});


问:
Smooch NPM package not installing JS file
I am trying to integrate smooch into my React app via an npm install, but the smooch directory in my node_modules does not include any JS files upon installation. Using smooch with the scripts works, though. What am I doing wrong that the smooch directory in node_modules does not include the JS file?</p>

答: This was a bug in v4.4 of the smooch npm package. v4.5.1 Fixes this issue.</p>


问:
Geode/Gemfire OQL's return data is incorrect in transaction view

Hello, I inserted a new entry to a region, and queried an OQL (SELECT * FROM /some_region_name) both within the same transaction, and I found that the new inserted entry was not returned in the OQL result. Dose anyone know what was going on with it?

Here are my testing codes:

```<code>    ClientCache cache = (ClientCache) EcnSpringContext.getBean("gemfireCache");

    Region<String, RUserEntity> userRegion = (Region<String, RUserEntity>) EcnSpringContext.getBean("r_user");

    CacheTransactionManager txmgr = cache.getCacheTransactionManager();
    EcnGeodeTemplate ecnGeodeTemplate = (EcnGeodeTemplate) EcnSpringContext.getBean("rUserTemplate");

    String username = "forrest";
    System.out.println("Transaction begin.");
    txmgr.begin();

    System.out.println("checking username[" + username + "] before added.");
    RUserEntity found = (RUserEntity) userRegion.selectValue("SELECT * FROM /r_user WHERE username = '" + username + "'");
    if (found == null)
        System.out.println("rUserEntity NOT found");
    else
        System.out.println("rUserEntity  found");

    RUserEntity rUserEntity = new RUserEntity();
    rUserEntity.setUsername("forrest");
    rUserEntity.setId(username);
    userRegion.put(username, rUserEntity);

    System.out.println("checking username[" + username + "] after added.");
    found = (RUserEntity) userRegion.selectValue("SELECT * FROM /r_user WHERE username = '" + username + "'");
    if (found == null)
        System.out.println("rUserEntity NOT found");
    else
        System.out.println("rUserEntity  found");

    txmgr.commit();
    System.out.println("Transaction end.");

    System.out.println("checking username[" + username + "] after transaction.");
    found = (RUserEntity) userRegion.selectValue("SELECT * FROM /r_user WHERE username = '" + username + "'");
    if (found == null)
        System.out.println("rUserEntity NOT found");
    else
        System.out.println("rUserEntity  found");
</code>```

I expected the result:

```<code>Transaction begin.
checking username[forrest] before added.
rUserEntity NOT found
checking username[forrest] after added.
**rUserEntity found**
Transaction end.
checking username[forrest] after transaction.
rUserEntity  found
</code>```

But unfortunately I got this result:

```<code>Transaction begin.
checking username[forrest] before added.
rUserEntity NOT found
checking username[forrest] after added.
**rUserEntity NOT found**
Transaction end.
checking username[forrest] after transaction.
rUserEntity  found
</code>```

答:
This is a known limitation. From the docs:</p>

```<code>Queries and indexes reflect the cache contents and ignore the changes
 made by ongoing transactions. If you do a query from inside a transaction,
the query does not reflect the changes made inside that transaction.
</code>```

Body:
Hello, I inserted a new entry to a region, and queried an OQL (SELECT * FROM /some_region_name) both within the same transaction, and I found that the new inserted entry was not returned in the OQL result. Dose anyone know what was going on with it?

Here are my testing codes:

    ClientCache cache = (ClientCache) EcnSpringContext.getBean("gemfireCache");

    Region<String, RUserEntity> userRegion = (Region<String, RUserEntity>) EcnSpringContext.getBean("r_user");

    CacheTransactionManager txmgr = cache.getCacheTransactionManager();
    EcnGeodeTemplate ecnGeodeTemplate = (EcnGeodeTemplate) EcnSpringContext.getBean("rUserTemplate");

    String username = "forrest";
    System.out.println("Transaction begin.");
    txmgr.begin();

    System.out.println("checking username[" + username + "] before added.");
    RUserEntity found = (RUserEntity) userRegion.selectValue("SELECT * FROM /r_user WHERE username = '" + username + "'");
    if (found == null)
        System.out.println("rUserEntity NOT found");
    else
        System.out.println("rUserEntity  found");

    RUserEntity rUserEntity = new RUserEntity();
    rUserEntity.setUsername("forrest");
    rUserEntity.setId(username);
    userRegion.put(username, rUserEntity);

    System.out.println("checking username[" + username + "] after added.");
    found = (RUserEntity) userRegion.selectValue("SELECT * FROM /r_user WHERE username = '" + username + "'");
    if (found == null)
        System.out.println("rUserEntity NOT found");
    else
        System.out.println("rUserEntity  found");

    txmgr.commit();
    System.out.println("Transaction end.");

    System.out.println("checking username[" + username + "] after transaction.");
    found = (RUserEntity) userRegion.selectValue("SELECT * FROM /r_user WHERE username = '" + username + "'");
    if (found == null)
        System.out.println("rUserEntity NOT found");
    else
        System.out.println("rUserEntity  found");

I expected the result:

Transaction begin.
checking username[forrest] before added.
rUserEntity NOT found
checking username[forrest] after added.
**rUserEntity found**
Transaction end.
checking username[forrest] after transaction.
rUserEntity  found

But unfortunately I got this result:

Transaction begin.
checking username[forrest] before added.
rUserEntity NOT found
checking username[forrest] after added.
**rUserEntity NOT found**
Transaction end.
checking username[forrest] after transaction.
rUserEntity  found

Body:
This is a known limitation. From the docs:

Queries and indexes reflect the cache contents and ignore the changes
 made by ongoing transactions. If you do a query from inside a transaction,
the query does not reflect the changes made inside that transaction.


问:
p5 resize window without clearing the background
The following code makes use of the p5dom add-on to position the canvas in the centre of the window. To dynamically resize the canvas I'm using the windowResized() function. I want to keep the background function in setup. How do I prevent the background colour from clearing when I resize the window? Many thanks.

var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){

}

function windowResized() {
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight)
}
```

答:
One thing you might do is draw everything to a buffer instead of directly to the screen. The createGraphics() function is your friend here. From the P5.js reference:

var pg;
function setup() {
  createCanvas(100, 100);
  pg = createGraphics(100, 100);
}
function draw() {
  background(200);
  pg.background(100);
  pg.noStroke();
  pg.ellipse(pg.width/2, pg.height/2, 50, 50);
  image(pg, 50, 50);
  image(pg, 0, 0, 50, 50);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script></code>```

You would want to draw everything to a buffer, and then when the screen is resized, redraw that buffer.

Body:
One thing you might do is draw everything to a buffer instead of directly to the screen. The createGraphics() function is your friend here. From the P5.js reference:

var pg;
function setup() {
  createCanvas(100, 100);
  pg = createGraphics(100, 100);
}
function draw() {
  background(200);
  pg.background(100);
  pg.noStroke();
  pg.ellipse(pg.width/2, pg.height/2, 50, 50);
  image(pg, 50, 50);
  image(pg, 0, 0, 50, 50);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>

You would want to draw everything to a buffer, and then when the screen is resized, redraw that buffer.


问:
Issue with the size of the To field in CRM Email form
We use CRM 2016 SP1 on-premise. We are experiencing an issue with the size of the To field of the built-in email View form whereby the field only displays up to three lines of email addresses and truncates the rest.

I know that I can click the list and scroll it in the Edit form, but this is not an option in the View form.

Is there any way to get the To field to expand/scroll in the View form?

答:
This is product limitation to show maximum 3 rows. But you should see scroll bar to look at all other recipients.

Another option is click on Lens icon & inline Lookup window will open, if you scroll all the way down - you can see Look up More Records, click it. This will open Lookup popup where 5 lines of recipients will show, where you can add/remove in bulk.

Update:

It seems your issue is with Closed activities, this form may be limited for customizations. Try Print (Ctrl+P) to see whether all the recipients are showing.


问:
can't install OpenAI gym
i am trying to install complete library of openAI gym (a toolkit for developing and comparing reinforcement learning algorithms) with help of pip. But i am getting same error again and again. i have tried everything i got on net to solve the problem but can't make it.plz help me to get a way.
here is my code---</p>

```<code>mukesh@mukesh-Inspiron-5558:~/gym$ sudo pip install -e .[all]
The directory '/home/mukesh/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/mukesh/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Obtaining file:///home/mukesh/gym
Requirement already satisfied: numpy>=1.10.4 in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: requests>=2.0 in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: six in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: pyglet>=1.2.0 in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: PyOpenGL in /usr/lib/python2.7/dist-packages (from gym==0.7.3)
Collecting box2d-py (from gym==0.7.3)
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Could not find a version that satisfies the requirement box2d-py (from gym==0.7.3) (from versions: )
No matching distribution found for box2d-py (from gym==0.7.3)
</code>```

答:
You are behind a proxy, so you need to setup pip so that it uses your proxy. The basic format is of this form:

```<code> [user:passwd@]proxy.server:port
</code>```

For example:

```<code>pip --proxy http://<your proxy>:<your port> (for http)
pip --proxy https://<your proxy>:<your port> (for https)
</code>```

Title: can't install OpenAI gym

Body:
i am trying to install complete library of openAI gym (a toolkit for developing and comparing reinforcement learning algorithms) with help of pip. But i am getting same error again and again. i have tried everything i got on net to solve the problem but can't make it.plz help me to get a way.
here is my code---

mukesh@mukesh-Inspiron-5558:~/gym$ sudo pip install -e .[all]
The directory '/home/mukesh/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/mukesh/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Obtaining file:///home/mukesh/gym
Requirement already satisfied: numpy>=1.10.4 in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: requests>=2.0 in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: six in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: pyglet>=1.2.0 in /home/mukesh/.local/lib/python2.7/site-packages (from gym==0.7.3)
Requirement already satisfied: PyOpenGL in /usr/lib/python2.7/dist-packages (from gym==0.7.3)
Collecting box2d-py (from gym==0.7.3)
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authentication Required',))': /simple/box2d-py/
  Could not find a version that satisfies the requirement box2d-py (from gym==0.7.3) (from versions: )
No matching distribution found for box2d-py (from gym==0.7.3)

Body:
You are behind a proxy, so you need to setup pip so that it uses your proxy. The basic format is of this form:

 [user:passwd@]proxy.server:port

For example:

pip --proxy http://<your proxy>:<your port> (for http)
pip --proxy https://<your proxy>:<your port> (for https)


问:
Shared memory for grpc client and server
My project is to read an image in a server, do some processing and then pass the whole image to the client. Client takes up the image and do some more processing and returns some output values to the server. The image being used between both the server and client is of size [640x480x3].

Following are the various techniques that came in my mind to implement this problem:

Pass the whole pixel values through the message from server to client

It takes 75ms for just sending a message from one server to one client, even if they are in the same system! (Never a good idea)

Split the whole image to chunks, and then message from server to client using stream.

There are various answers in SO for this. I am currently working on getting this working.

Assign the pixel values to a variable recognised by gRPC in both server and client. In other words have the image in a shared memory of gRPC, which could be accessed by both the server and client (assuming both server and client to be in the same system).

Is this mode of messaging between server and client possible? If yes, please provide some references to the doc or examples for the same.

答:
gRPC doesn't (at the current time) support any kind of shared-memory transport between different processes on the same system in any of the language APIs. A close variant is the in-process transport that is supported by C++ and Java. This is used for sending messages between a client and a server in the same process (for example, if you want to run a proxy in the same address space as a server that might also have a direct external interface), and the only difference between this and traditional gRPC operations is at channel creation in both languages and when building the server in Java. The Java documentation for this is at https://grpc.io/grpc-java/javadoc/io/grpc/inprocess/InProcessServerBuilder.html . For C++, you just call Server::InProcessChannel on the server rather than grpc::CreateChannel since all servers automatically have an in-process capability in C++ as long as you have their pointer.

Hope that helps!

@vjpai


问:
jquery animate opacity has an impact of other divs? weird behavior
I've got a really strange jquery behavior. I want to make a grid like background with animated tiles (opacity to .8 and back to .25 on mouseover and mouseleave).

As this should be my background it should'n have an impact on my content div.

Unfortunately it doesn't work as expected. THe content div(Which i colored red for testing purposes) gets animated, too.

Here's a link the the site.

答:
I'm adjusting your code to use the .hover() event instead of juggling mouseover/mouseout, also I'm using fadeTo instead of manually animating opacity.

```<code>$(document).ready(function() {
    $('#page-bg ul li img.keyword').hover(function(){
            $(this).fadeTo('slow',0.8);
        },
        function() {
            $(this).fadeTo('slow',0.25);
        });
    ...
});
</code>```

Body:
I'm adjusting your code to use the .hover() event instead of juggling mouseover/mouseout, also I'm using fadeTo instead of manually animating opacity.

$(document).ready(function() {
    $('#page-bg ul li img.keyword').hover(function(){
            $(this).fadeTo('slow',0.8);
        },
        function() {
            $(this).fadeTo('slow',0.25);
        });
    ...
});


问:
boost process running() and exit_code() thread safety
I am using boost::process::child and boost::process::async_pipe to start an application and read asynchronously (through the means of boost::asio) everything that app outputs on screen whenever this happens.

I want to check also if the application is alive by using child::running() method; if not running I'd like to read the exit code using child::exit_code.

This is very useful ESPECIALLY as it is a way to be notified about an application crashing or exiting unexpectedly (I could not find a better way); when the app exits the callback is called with boost::system::error_code set.

Do you know if I can use these two methods inside the callback called by async_pipe::async_read_some ?

In general the much more simple question would be if child::running() and child::exit_code() are thread safe (in both Windows and Linux).

```<code> namespace bp = boost::process;

 char my_buffer[1024];

 boost::asio::io_service io;
 bp::async_pipe in_pipe(io);

 void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred);

 void schedule_read()  {
     in_pipe.async_read_some(
         boost::asio::buffer(my_buffer),
         boost::bind(&handle_pipe_read,
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
 }

 void handle_pipe_read(
    const boost::system::error_code &ec,
    std::size_t bytes_transferred
    )
 {
     // Q: Is this call possible? 'handle_pipe_read' can run in any thread
     if(c->running())
        std::cout << "I am alive" << std::endl;
     else
        std::cout << "EXIT CODE:" << c->exit_code() << std::endl;

     if(ec) return; //app probably exit

     // Do something with buffer and re-schedule

     schedule_read();
 }

 int main() {
   bp::child c("my_program_url", bp::std_out > in_pipe);
   any_c = &c;

   schedule_read();
   io.run();
 }
</code>```

答:
The only solution that worked for me is the following

schedule a completion read

always check calling child::running()

on error_code set don't reschedule

When the pipe gets broken (because of a crash)  the completion handler for a read has the boost::error_code argument set to true. Despite this I've seen cases where child::running() is false also when boost::error_code is NOT set.

Body:
I am using boost::process::child and boost::process::async_pipe to start an application and read asynchronously (through the means of boost::asio) everything that app outputs on screen whenever this happens.

I want to check also if the application is alive by using child::running() method; if not running I'd like to read the exit code using child::exit_code.

This is very useful ESPECIALLY as it is a way to be notified about an application crashing or exiting unexpectedly (I could not find a better way); when the app exits the callback is called with boost::system::error_code set.

Do you know if I can use these two methods inside the callback called by async_pipe::async_read_some ?

In general the much more simple question would be if child::running() and child::exit_code() are thread safe (in both Windows and Linux).

 namespace bp = boost::process;

 char my_buffer[1024];

 boost::asio::io_service io;
 bp::async_pipe in_pipe(io);

 void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred);

 void schedule_read()  {
     in_pipe.async_read_some(
         boost::asio::buffer(my_buffer),
         boost::bind(&handle_pipe_read,
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
 }

 void handle_pipe_read(
    const boost::system::error_code &ec,
    std::size_t bytes_transferred
    )
 {
     // Q: Is this call possible? 'handle_pipe_read' can run in any thread
     if(c->running())
        std::cout << "I am alive" << std::endl;
     else
        std::cout << "EXIT CODE:" << c->exit_code() << std::endl;

     if(ec) return; //app probably exit

     // Do something with buffer and re-schedule

     schedule_read();
 }

 int main() {
   bp::child c("my_program_url", bp::std_out > in_pipe);
   any_c = &c;

   schedule_read();
   io.run();
 }


问:
SQL result with aggregation data
I need to select some details data from a table and 'create' a new custom record, containing the aggregation of the data selected

For example, I have this data:

```<code>SELECT abi, cmp, amount, recordid
FROM mytable;
</code>```

```<code>abi     cmp     amount     recordId
------------------------------------
01025   25       200         1
01025   25       200         2
01025   25       400         3
99904   04       100         4
99904   04       100         5
</code>```

What I need is to have for each abi column, a new record containing sub totals and aggregation data aggregation like this:

```<code>abi     cmp     amount     recordId
------------------------------------
01025   25       200         1
01025   25       200         2
01025   25       400         3
>> For Abi 01005 there are 3 records on cmp 25 and total amount 800
99904   04       100         4
99904   04       100         5
>>For Abi 99904 there are 2 records on cmp 04 and total amount 200
</code>```

There is a way to generate these new records using a query?

I checked rollup() function but I'm not able to generate the result expected.

答:
For what you want, union all is probably best:

```<code>select abi, cmp, amount, recordid, 1 as priority
from mytable
union all
select abi, cmp, sum(amount), count(*), 2
from mytable
group by abi, cmp
order by abi, cmp, priority;
</code>```

This leaves the priority in the outer query.  You can get around that using a subquery:

```<code>select abi, cmp, amount, recordid
from ((select abi, cmp, amount, recordid, 1 as priority
       from mytable
      ) union all
      (select abi, cmp, sum(amount), count(*), 2
       from mytable
       group by abi, cmp
      )
     ) t
order by abi, cmp, priority;
</code>```

Title: SQL result with aggregation data

Body:
I need to select some details data from a table and 'create' a new custom record, containing the aggregation of the data selected

For example, I have this data:

SELECT abi, cmp, amount, recordid
FROM mytable;

abi     cmp     amount     recordId
------------------------------------
01025   25       200         1
01025   25       200         2
01025   25       400         3
99904   04       100         4
99904   04       100         5

What I need is to have for each abi column, a new record containing sub totals and aggregation data aggregation like this:

abi     cmp     amount     recordId
------------------------------------
01025   25       200         1
01025   25       200         2
01025   25       400         3
>> For Abi 01005 there are 3 records on cmp 25 and total amount 800
99904   04       100         4
99904   04       100         5
>>For Abi 99904 there are 2 records on cmp 04 and total amount 200

There is a way to generate these new records using a query?

I checked rollup() function but I'm not able to generate the result expected.

Body:
For what you want, union all is probably best:

select abi, cmp, amount, recordid, 1 as priority
from mytable
union all
select abi, cmp, sum(amount), count(*), 2
from mytable
group by abi, cmp
order by abi, cmp, priority;

This leaves the priority in the outer query.  You can get around that using a subquery:

select abi, cmp, amount, recordid
from ((select abi, cmp, amount, recordid, 1 as priority
       from mytable
      ) union all
      (select abi, cmp, sum(amount), count(*), 2
       from mytable
       group by abi, cmp
      )
     ) t
order by abi, cmp, priority;


问:
Java REST API that uses OpenAM token to determine user?
I am having trouble being able to validate a users token with OpenAM. Particularly what type of Agent I should create. Is there anyone that can recommend a solution?

Essentially the REST API will read the users OpenAM tokenid and validate the token with OpenAM which then will return data which contains a username. That username can be used in the REST API method to identify who is accessing the method.

Even more simplified is how can I use a OpenAM token to get the OpenAM user info.

Thanks!

答:
don't you need cookies to be set ..

```<code>   Response fieldResponse = given().auth().oauth2( oAuthLogin.getToken())
                .config(new RestAssuredConfig().
                        decoderConfig(
                                new DecoderConfig("UTF-8")
                        ).encoderConfig(
                        new EncoderConfig("UTF-8", "UTF-8")
                ))
                .header("iplanetDirectoryPro", oAuthLogin.getToken())
                .header("Content-Type", "application/json")
//                .contentType("application/json")
                .body(myRequest).with()
                .when()
                .post(dataPostUrl)
                .then()
                .assertThat()
                .log().ifError()
                .statusCode(200)
                .extract().response();
</code>```

is failing as bad request 400.Same content header is working in postman.
Only difference i see is cookie.enter image description here
Working as per postman

Not working one which used restassured framework enter image description here

Body:
don't you need cookies to be set ..

   Response fieldResponse = given().auth().oauth2( oAuthLogin.getToken())
                .config(new RestAssuredConfig().
                        decoderConfig(
                                new DecoderConfig("UTF-8")
                        ).encoderConfig(
                        new EncoderConfig("UTF-8", "UTF-8")
                ))
                .header("iplanetDirectoryPro", oAuthLogin.getToken())
                .header("Content-Type", "application/json")
//                .contentType("application/json")
                .body(myRequest).with()
                .when()
                .post(dataPostUrl)
                .then()
                .assertThat()
                .log().ifError()
                .statusCode(200)
                .extract().response();

is failing as bad request 400.Same content header is working in postman.
Only difference i see is cookie.enter image description here
Working as per postman

Not working one which used restassured framework enter image description here


问:
How to import enum in interface declaration file (d.ts)
I want to extend string with a method that needs an enumeration to be passed. How do I import that enum into the declaration file?

CapitalizationStyle.tsx:

```<code>export enum CapitalizationStyle {
    None = 0,
    Lowercase = 1,
    Word = 2
}
</code>```

StringExtensions.d.ts:

```<code>import { CapitalizationStyle } from "Utils/CapitalizationStyle"; //This line breaks everything.

declare interface String {
    applyCapitalizationStyle(this: string, style: CapitalizationStyle): string;
}
</code>```

The import breaks the interface declaration, like if the declaration does not exist anymore. All extension implementations of the String class become invalid as soon as I add the import:

StringExtensions.tsx:

Minimal reproducible example project: https://wetransfer.com/downloads/d1a707c0ac734985b877058967c35a6820171212143715/410f48

答:
Since you don't have a default export from that module, you need to wrap it in {}:

```<code>import { CapitalizationStyle } from "Utils/CapitalizationStyle";
</code>```

Body:
I want to extend string with a method that needs an enumeration to be passed. How do I import that enum into the declaration file?

CapitalizationStyle.tsx:

export enum CapitalizationStyle {
    None = 0,
    Lowercase = 1,
    Word = 2
}

StringExtensions.d.ts:

import { CapitalizationStyle } from "Utils/CapitalizationStyle"; //This line breaks everything.

declare interface String {
    applyCapitalizationStyle(this: string, style: CapitalizationStyle): string;
}

The import breaks the interface declaration, like if the declaration does not exist anymore. All extension implementations of the String class become invalid as soon as I add the import:

StringExtensions.tsx:

Minimal reproducible example project: https://wetransfer.com/downloads/d1a707c0ac734985b877058967c35a6820171212143715/410f48

Body:
Since you don't have a default export from that module, you need to wrap it in {}:

import { CapitalizationStyle } from "Utils/CapitalizationStyle";


问:
Checking hgrc file into Mercurial
I have a project using mercurial for version control, SCons to build, and google test to write unit tests. The hgrc file hooks pre-commit and runs SCons to build the project and and run unit tests. Is there a way to "check-in" a portion of the hgrc file so that newly checked out copies, and any merges with my version of the project automatically get an hgrc file that runs SCons when they try to commit?</p>

答: You cannot checking anything under the .hg folder.  What my team does it that we have a common mercurial.ini file which as part of the dev box setup we put in our user profile folders. </p>

Title: Checking hgrc file into Mercurial


问:
Eliminate style loading using media queries
I try to speed up initial loading by eliminating unnecessary downloading.
I split styles in to portrait and landscape css.
And want to load only one style based on media queries.
But is seems they are loading together.

  <link rel="stylesheet" type="text/css" href="style-p.css" media="(orientation: portrait)" />
  <link rel="stylesheet" type="text/css" href="style-l.css" media="(orientation: landscape)" />
```

答:
As of the moment, browsers still don't have the ability to dynamically load resources in <link> based on its media attribute.

See this article for a more in-depth discussion and implementation of this feature.

Option 1: Keep it as-is

If you're app isn't that big and the styles don't take up much bandwidth, it'd be best to keep them both intact. The cache is your friend. The initial load may be slow, but subsequent requests on the resources will be proxied through the cache.

Option 2: Load the styles with JavaScript

If your styles take about 500KB each, you're probably better off loading them asynchronously with JavaScript.

This will add much more complexity to your application (not to mention if you're using complex build tools like grunt, gulp, or webpack), but it can make initial load faster (or at least, seem faster).

If you want to pursue this path, you can simply include a small script at the bottom of your  that checks the user's environment, loads the appropriate css file, inject the contents into a style tag, and append that style tag to the document .

Other notes

Personally, I think separating styles into landscape styles and portrait styles isn't the best way to organize your styles. A better code-separation technique might be to have different styles for different pages of your app, and have only the specific styles load based on the active page. (But it still depends if your layout relies heavily on the portait/landscape media query).

It goes without saying, but these all depend on the environment you're working with and the available server-side solutions you may have access to. It even depends as to how much effort you're willing to give just to reduce your initial load times by 10ms.

I'd say your best bet right now is to merge both files into a single one (so resources loaded pre-HTTP/2 loads faster) and keep it on all your pages. After the first load, it gets cached and that resource will load (almost) instantly. If you absolutely hate white screens, add a fun animated preloaded at the start of your app to entertain your users while they wait for your styles to load on the first render.

Body:
As of the moment, browsers still don't have the ability to dynamically load resources in <link> based on its media attribute.

See this article for a more in-depth discussion and implementation of this feature.

Option 1: Keep it as-is

If you're app isn't that big and the styles don't take up much bandwidth, it'd be best to keep them both intact. The cache is your friend. The initial load may be slow, but subsequent requests on the resources will be proxied through the cache.

Option 2: Load the styles with JavaScript

If your styles take about 500KB each, you're probably better off loading them asynchronously with JavaScript.

This will add much more complexity to your application (not to mention if you're using complex build tools like grunt, gulp, or webpack), but it can make initial load faster (or at least, seem faster).

If you want to pursue this path, you can simply include a small script at the bottom of your <body> that checks the user's environment, loads the appropriate css file, inject the contents into a style tag, and append that style tag to the document <head>.

Other notes

Personally, I think separating styles into landscape styles and portrait styles isn't the best way to organize your styles. A better code-separation technique might be to have different styles for different pages of your app, and have only the specific styles load based on the active page. (But it still depends if your layout relies heavily on the portait/landscape media query).

It goes without saying, but these all depend on the environment you're working with and the available server-side solutions you may have access to. It even depends as to how much effort you're willing to give just to reduce your initial load times by 10ms.

I'd say your best bet right now is to merge both files into a single one (so resources loaded pre-HTTP/2 loads faster) and keep it on all your pages. After the first load, it gets cached and that resource will load (almost) instantly. If you absolutely hate white screens, add a fun animated preloaded at the start of your app to entertain your users while they wait for your styles to load on the first render.


问:
Using Java Inheritance, how do I refer to a specific subclass while I'm in the superclass
I have 3 different Classes:

Class 1 (Super Class)
Class 2 (SubClass)
Class 3 (SubClass)

In Class 1, I have an instance variable called NUMBER, and a method called myNumber.

I am trying to make an if/else statement, so that if we are calling the .myNumber method for Class 2, NUMBER equals 7.  However, in Class 3, I want that number to equal 8.

My if else statement looked like this:

```<code>if (Class2)
{
   myNumber = 7
}

else if (Class3)
 {
   myNumber = 8
 }
</code>```

However, I have no idea how to refer to Class2 and Class3, while I'm making the code in Class3.

Any help would be great!  :)

答:
You can easily do this via inheritance:

```<code>class Class1 {
    int number = 5;

    public void myNumber() {

    }
}

class Class2 extends Class1 {

    @Override
    public void myNumber() {
        number = 7;
    }
}

class Class3 extends Class1 {

    @Override
    public void myNumber() {
        number = 8;
    }
}
</code>```

Demo

Body:
I have 3 different Classes:

Class 1 (Super Class)
Class 2 (SubClass)
Class 3 (SubClass)

In Class 1, I have an instance variable called NUMBER, and a method called myNumber.

I am trying to make an if/else statement, so that if we are calling the .myNumber method for Class 2, NUMBER equals 7.  However, in Class 3, I want that number to equal 8.

My if else statement looked like this:

if (Class2)
{
   myNumber = 7
}

else if (Class3)
 {
   myNumber = 8
 }

However, I have no idea how to refer to Class2 and Class3, while I'm making the code in Class3.

Any help would be great!  :)

Body:
You can easily do this via inheritance:

class Class1 {
    int number = 5;

    public void myNumber() {

    }
}

class Class2 extends Class1 {

    @Override
    public void myNumber() {
        number = 7;
    }
}

class Class3 extends Class1 {

    @Override
    public void myNumber() {
        number = 8;
    }
}

Demo


问:
Promise doesn't return the right value in JavaScript
I have a weird Promise behavior which returns the incorrect value.

var years = []

$.getJSON('https://omdbapi.com?t=titanic&apikey=thewdb')
.then(function(movie){
  years.push(movie.Year)
  return $.getJSON('https://omdbapi.com?t=shrek&apikey=thewdb')
})
.then(function(movie){
  years.push(movie.Year)
  console.log(years) // ["1997", "2001"]
})

console.log(years) // [] return at the beginning```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

The empty array is being returned in the first place is from the end of the code - which is weird to me. Can you have to explain this? Thanks,

答: The reason the first console.log prints [] is because the $.getJSON and .then() functions have not executed yet. This is known as asynchronous code meaning that things may not execute in the order they appear in the code.</p>

Body:
I have a weird Promise behavior which returns the incorrect value.

var years = []

$.getJSON('https://omdbapi.com?t=titanic&apikey=thewdb')
.then(function(movie){
  years.push(movie.Year)
  return $.getJSON('https://omdbapi.com?t=shrek&apikey=thewdb')
})
.then(function(movie){
  years.push(movie.Year)
  console.log(years) // ["1997", "2001"]
})

console.log(years) // [] return at the beginning

The empty array is being returned in the first place is from the end of the code - which is weird to me. Can you have to explain this? Thanks,


问:
Set EXIF DateTaken as file CreationTime
I'm trying to fix metadata of my photos using powershell.
I need to set exif DateTaken as file CreationTime

Here is my code:

```<code>[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
echo "--------"
echo ""
$files = Get-ChildItem E:\Photos\*.*
ForEach ($file in $files) {

        #Get Date
    $foo=New-Object -TypeName system.drawing.bitmap -ArgumentList $file.fullname
    $date = $foo.GetPropertyItem(36867).value[0..9]
    $arYear = [Char]$date[0],[Char]$date[1],[Char]$date[2],[Char]$date[3]
    $arMonth = [Char]$date[5],[Char]$date[6]
    $arDay = [Char]$date[8],[Char]$date[9]
    $strYear = [String]::Join('',$arYear)
    $strMonth = [String]::Join('',$arMonth)
    $strDay = [String]::Join('',$arDay)
    $DateTaken = $strDay + "/" + $strMonth + "/" + $strYear

        # Get Time
    $time = $foo.GetPropertyItem(36867).value[11..18]
    $arHour = [Char]$time[0],[Char]$time[1]
    $arMinute = [Char]$time[3],[Char]$time[4]
    $arSecond = [Char]$time[6],[Char]$time[7]
    $strHour = [String]::Join('',$arHour)
    $strMinute = [String]::Join('',$arMinute)
    $strSecond = [String]::Join('',$arSecond)
    $TimeTaken = $strHour + ":" + $strMinute + ":" + $strSecond

        # Link into one date and time
    $FullDate = $DateTaken + " " + $TimeTaken

    echo "File name"
    echo $file.name
    echo ""
    echo "Wrong data"
    echo (Get-Item $file).creationtime.datetime
    echo ""
    echo "Right data"
    echo $FullDate
    echo ""

        #Set DateTaken as CreationTime
    (Get-Item $file).creationtime= $FullDate

    pause
}
</code>```

I got error "cannot access the file because it is being used by another process".
I have no idea how to fix it.

PS. I'm not sure if $FullDate has right syntax, because I couldn't test it

Thanks

答:
Thanks to @TomG, that solved my problem
I already finished this project. I post code, this may help someone with fixing dates in photos in future</p>

```<code>[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
Clear-Host
$files = Get-ChildItem E:\Photos\*.*
$i = 1
ForEach ($file in $files) {

        # Print file name
    echo $file.fullname

        # Print Number of File
#   Write-Host 'File no: ' $i
#   echo ""

        #Get Date
    $foo=New-Object -TypeName system.drawing.bitmap -ArgumentList $file.fullname
    $date = $foo.GetPropertyItem(36867).value[0..9]
    $arYear = [Char]$date[0],[Char]$date[1],[Char]$date[2],[Char]$date[3]
    $arMonth = [Char]$date[5],[Char]$date[6]
    $arDay = [Char]$date[8],[Char]$date[9]
    $strYear = [String]::Join('',$arYear)
    $strMonth = [String]::Join('',$arMonth)
    $strDay = [String]::Join('',$arDay)

#       Date to string
#   $DateTaken = $strDay + "/" + $strMonth + "/" + $strYear

        # Get Time
    $time = $foo.GetPropertyItem(36867).value[11..18]
    $arHour = [Char]$time[0],[Char]$time[1]
    $arMinute = [Char]$time[3],[Char]$time[4]
    $arSecond = [Char]$time[6],[Char]$time[7]
    $strHour = [String]::Join('',$arHour)
    $strMinute = [String]::Join('',$arMinute)
    $strSecond = [String]::Join('',$arSecond)

    $foo.dispose()

#       Time to string
#   $TimeTaken = $strHour + ":" + $strMinute + ":" + $strSecond

    $NewDate = (Get-Date -Year $strYear -Month $strMonth -Day $strDay -Hour $strHour -Minute $strMinute -Second $strSecond)

        #Set DateTaken as CreationTime
    (Get-Item $file).CreationTime = $NewDate
    (Get-Item $file).LastWriteTime = $NewDate

    $i++

#   Clear-Host
}

echo ""
echo "Done"
pause
</code>```

Title: Set EXIF DateTaken as file CreationTime

Body:
I'm trying to fix metadata of my photos using powershell.
I need to set exif DateTaken as file CreationTime

Here is my code:

[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
echo "--------"
echo ""
$files = Get-ChildItem E:\Photos\*.*
ForEach ($file in $files) {

        #Get Date
    $foo=New-Object -TypeName system.drawing.bitmap -ArgumentList $file.fullname
    $date = $foo.GetPropertyItem(36867).value[0..9]
    $arYear = [Char]$date[0],[Char]$date[1],[Char]$date[2],[Char]$date[3]
    $arMonth = [Char]$date[5],[Char]$date[6]
    $arDay = [Char]$date[8],[Char]$date[9]
    $strYear = [String]::Join('',$arYear)
    $strMonth = [String]::Join('',$arMonth)
    $strDay = [String]::Join('',$arDay)
    $DateTaken = $strDay + "/" + $strMonth + "/" + $strYear

        # Get Time
    $time = $foo.GetPropertyItem(36867).value[11..18]
    $arHour = [Char]$time[0],[Char]$time[1]
    $arMinute = [Char]$time[3],[Char]$time[4]
    $arSecond = [Char]$time[6],[Char]$time[7]
    $strHour = [String]::Join('',$arHour)
    $strMinute = [String]::Join('',$arMinute)
    $strSecond = [String]::Join('',$arSecond)
    $TimeTaken = $strHour + ":" + $strMinute + ":" + $strSecond

        # Link into one date and time
    $FullDate = $DateTaken + " " + $TimeTaken

    echo "File name"
    echo $file.name
    echo ""
    echo "Wrong data"
    echo (Get-Item $file).creationtime.datetime
    echo ""
    echo "Right data"
    echo $FullDate
    echo ""

        #Set DateTaken as CreationTime
    (Get-Item $file).creationtime= $FullDate

    pause
}

I got error "cannot access the file because it is being used by another process".
I have no idea how to fix it.

PS. I'm not sure if $FullDate has right syntax, because I couldn't test it

Thanks

Body:
Thanks to @TomG, that solved my problem
I already finished this project. I post code, this may help someone with fixing dates in photos in future

[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
Clear-Host
$files = Get-ChildItem E:\Photos\*.*
$i = 1
ForEach ($file in $files) {

        # Print file name
    echo $file.fullname

        # Print Number of File
#   Write-Host 'File no: ' $i
#   echo ""

        #Get Date
    $foo=New-Object -TypeName system.drawing.bitmap -ArgumentList $file.fullname
    $date = $foo.GetPropertyItem(36867).value[0..9]
    $arYear = [Char]$date[0],[Char]$date[1],[Char]$date[2],[Char]$date[3]
    $arMonth = [Char]$date[5],[Char]$date[6]
    $arDay = [Char]$date[8],[Char]$date[9]
    $strYear = [String]::Join('',$arYear)
    $strMonth = [String]::Join('',$arMonth)
    $strDay = [String]::Join('',$arDay)

#       Date to string
#   $DateTaken = $strDay + "/" + $strMonth + "/" + $strYear

        # Get Time
    $time = $foo.GetPropertyItem(36867).value[11..18]
    $arHour = [Char]$time[0],[Char]$time[1]
    $arMinute = [Char]$time[3],[Char]$time[4]
    $arSecond = [Char]$time[6],[Char]$time[7]
    $strHour = [String]::Join('',$arHour)
    $strMinute = [String]::Join('',$arMinute)
    $strSecond = [String]::Join('',$arSecond)

    $foo.dispose()

#       Time to string
#   $TimeTaken = $strHour + ":" + $strMinute + ":" + $strSecond

    $NewDate = (Get-Date -Year $strYear -Month $strMonth -Day $strDay -Hour $strHour -Minute $strMinute -Second $strSecond)

        #Set DateTaken as CreationTime
    (Get-Item $file).CreationTime = $NewDate
    (Get-Item $file).LastWriteTime = $NewDate

    $i++

#   Clear-Host
}

echo ""
echo "Done"
pause


问:
How to display a specific value from the array in Jquery / getJSON?
Basically I am getting a JSON feed using jquery using:

```<code>$.getJSON("http://localhost/1.php?method=getAllUsers&jsoncallback=?")
</code>```

I get the values successfully from the feed stored in an array called data

eg.:

```<code>x => 1
y => 3
z => 5
</code>```

(obviously this is in the json format)

after this script i have the html, and a table

```<code><table><tr><td>y</td><td>value of y from the feed</td></tr></table>
</code>```

now how can i get the specific value of y into my table? any help would be apreciated.

Thanks

答:
You need to use DOM methods to find the appropriate  element and change its content.

As you're already using jQuery the simplest thing would be to put an id on that :

```<code><td id="foo"> ... </td>
</code>```

and then use this in your script:

```<code>$('#foo').html(data.y);
</code>```

(i.e. set the inner HTML content of the element with ID foo to data.y)

Body:
Basically I am getting a JSON feed using jquery using:

$.getJSON("http://localhost/1.php?method=getAllUsers&jsoncallback=?")

I get the values successfully from the feed stored in an array called data

eg.:

x => 1
y => 3
z => 5

(obviously this is in the json format)

after this script i have the html, and a table

y	value of y from the feed

now how can i get the specific value of y into my table? any help would be apreciated.

Thanks

Body:
You need to use DOM methods to find the appropriate <td> element and change its content.

As you're already using jQuery the simplest thing would be to put an id on that <td>:

<td id="foo"> ... </td>

and then use this in your script:

$('#foo').html(data.y);

(i.e. set the inner HTML content of the element with ID foo to data.y)


问:
Regex to Capture last email Address
I need a regex to capture last email addresss

2017-11-30T17:00:02.596Z,10.1.20.211,RenjuXXX,X.X.X.X,mxa-0003fe01.xx.renjj.com,;250 2.0.0 2ej1k6mass-1 Message accepted for delivery;ClientSubmitTime:,Outbound to Internet,SMTP,SEND,asadasdasd1212,,b4b8c0b5-ce3b-4aca-8335-08d53813c96a,Jose.renj@renj.org,250 2.1.5 Recipient ok,41758,1,,,RE: my CV,renjujacob@renju.com,renjujacob@renju.com,

I tried using this regex below to capture the email ID , but its capturing the first email

((?P(?<=,)[a-zA-Z0-9-.]+@[a-zA-Z0-9-.]+(?=\s*(?:\w+=|,))))

need a regex to capture last email id (renjujacob@renju.com). Any help will be appreciated.

答:
The regex

```<code>,([^,@]+@[^,@]),[^,]*$
</code>```

captures inside the parentheses an email address from the penultimate comma-separated field without a lot of (very often false) assumptions about what an email address can or cannot contain - we require exactly one @ and rule out commas because the format is comma-separated, but that's it.

Title: Regex to Capture last email Address

Body:
The regex

,([^,@]+@[^,@]),[^,]*$

captures inside the parentheses an email address from the penultimate comma-separated field without a lot of (very often false) assumptions about what an email address can or cannot contain - we require exactly one @ and rule out commas because the format is comma-separated, but that's it.


问:
Angular 2 component doesnt render even if i put it in NgModule
I have a problem with rendering custom component. Even if i put my shared module in NgModule it doesnt render. I get an error where it says that i should add component to NgModule or add property schemas with parameter CUSTOM_ELEMENTS_SCHEMA. As i said i added component to shared module and shared module to component where i want to use it. And then i tried with CUSTOM_ELEMENTS_SCHEMA and i got rid of and error but it doesnt render the content of "custom" component it just renders the tag od the comp.

Custom component module

checkbox.module.ts

```<code>import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { CheckboxComponent } from './checkbox.component';

@NgModule({
    imports: [FormsModule],
    exports: [CheckboxComponent],
    declarations: [CheckboxComponent]
})
export class CheckboxModule { }
</code>```

Shared module

shared.module.ts

Edit:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CheckboxModule, CheckboxComponent } from '../components/checkbox';
@NgModule({
    imports: [
        CommonModule,
        CheckboxModule
    ],
    declarations: [],
    exports: [ CheckboxComponent ]
})
export class SharedModule { }
</code>```

Module where i am trying to use shared module and custom component tag:

dashboard.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { SharedModule } from '../shared/shared.module';
@NgModule({
    imports: [
        SharedModule,
        CommonModule
    ],
   declarations: [DashboardComponent]
})

export class DashboardModule { }
</code>```

And it renders like a tag with no content

```<code><app-checkbox _ngcontent-c1 name="sth"></app-checkbox>
</code>```

答:
I found where the problem was. In app.module.ts I had to import dashboard.module.ts module instead of declaring dashboard.component.ts componnent. I guess that everything should be done through modules if possible :)

I hope this helps someone.

Body:
I have a problem with rendering custom component. Even if i put my shared module in NgModule it doesnt render. I get an error where it says that i should add component to NgModule or add property schemas with parameter CUSTOM_ELEMENTS_SCHEMA. As i said i added component to shared module and shared module to component where i want to use it. And then i tried with CUSTOM_ELEMENTS_SCHEMA and i got rid of and error but it doesnt render the content of "custom" component it just renders the tag od the comp.

Custom component module

checkbox.module.ts

import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { CheckboxComponent } from './checkbox.component';

@NgModule({
    imports: [FormsModule],
    exports: [CheckboxComponent],
    declarations: [CheckboxComponent]
})
export class CheckboxModule { }

Shared module

shared.module.ts

Edit:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CheckboxModule, CheckboxComponent } from '../components/checkbox';
@NgModule({
    imports: [
        CommonModule,
        CheckboxModule
    ],
    declarations: [],
    exports: [ CheckboxComponent ]
})
export class SharedModule { }

Module where i am trying to use shared module and custom component tag:

dashboard.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { SharedModule } from '../shared/shared.module';
@NgModule({
    imports: [
        SharedModule,
        CommonModule
    ],
   declarations: [DashboardComponent]
})

export class DashboardModule { }

And it renders like a tag with no content

<app-checkbox _ngcontent-c1 name="sth"></app-checkbox>


答:
Try wrapping in curly braces, like this:

```<code>import {CapitalizationStyle} from "Utils/CapitalizationStyle";
</code>```

since you don't default-export your custom enumeration.

Title: How to import enum in interface declaration file (d.ts)

Body:
Try wrapping in curly braces, like this:

import {CapitalizationStyle} from "Utils/CapitalizationStyle";

since you don't default-export your custom enumeration.


问:
In which file am I supposed to configure Socket.io, considering I'm using express?
I've used express-generator to create my app skeleton and since my file that creates the server and my routes are separated, I don't know where to setup the socket.io code. The tutorials usually have the server code, the socket.io code and the routes in 1 file.

app.js contains:

```<code>var routes = require('./routes/');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
                  secret: 'secretText',
                  saveUninitialized: true,
                  resave: true
                }))
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes.home);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

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

www contains:

```<code>#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}
</code>```

home.js

```<code>var express = require('express');
var router = express.Router();
var db = require('../helpers/db');

router.get('/', function(req, res, next) {
    res.send("Hello");
});

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

index.js

```<code>var home = require('./home');

module.exports = {
    home
};
</code>```

答:
As with all module design and layout in node.js, there is no "right" answer.  It depends upon your own design ideas, how much code you're going to have of different types, what code needs to share with what and so on.  As such, I can offer some ideas and you can pick which seems to appeal to you.

If your server-side socket.io code is fairly minimal, you can just include it in www where the server is initialized (since you need access to the server object there).

If you want your server-side socket.io code in its own module, then you can put it in its own module/file and import that file into your www file much the same way you import app.js and then hook the app object up to your server.  Similarly, you would create the socket.io instance in your socket.io module and then import that instance into www and hook that up to your server.

If you have a lot of code sharing between your socket.io code and your app.js code or need to make socket.io calls from your app.js routes, then you may want to import the socket.io code into your app.js code and then export both app and socket.io instance from app.js so www can then hook them both up.

Body:
I've used express-generator to create my app skeleton and since my file that creates the server and my routes are separated, I don't know where to setup the socket.io code. The tutorials usually have the server code, the socket.io code and the routes in 1 file.

app.js contains:

var routes = require('./routes/');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
                  secret: 'secretText',
                  saveUninitialized: true,
                  resave: true
                }))
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes.home);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

www contains:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

home.js

var express = require('express');
var router = express.Router();
var db = require('../helpers/db');

router.get('/', function(req, res, next) {
    res.send("Hello");
});

module.exports = router;

index.js

var home = require('./home');

module.exports = {
    home
};


问:
Change PouchDB's rev algorithm to use a blockchain / hashchain pattern
Is it within reason to change CouchDB / PouchDB's revision algorithm 'under the hood' to use a blockchain style 'hashchain' such that the _rev of every doc is the result of a hash of it's previous revisions?  </p>

<p>Such a model would help preserve the integrity of revisions; in a distributed network for example it could essentially be the basis of an immutable history for your entire db. </p>

答:
In fact, the _rev is a deterministic hash over the document and all of its revisions, at least for CouchDB. It's also using the previous _rev, so you basically get a deterministic hash if you make the same sequence of updates to a document.

Unfortunately, it's an MD5 hash, so it isn't really suitable for security-related stuff.

AFAIK, the actual value of the _rev is never checked, only the part before the dash must be numeric. So you could write a PouchDB plugin that changes the _rev generation and also checks the integrity of the _rev value on every update.

Body:
Is it within reason to change CouchDB / PouchDB's revision algorithm 'under the hood' to use a blockchain style 'hashchain' such that the _rev of every doc is the result of a hash of it's previous revisions?

Such a model would help preserve the integrity of revisions; in a distributed network for example it could essentially be the basis of an immutable history for your entire db.


问:
WCF SQL adapter issue while inserting the records into a SQL Server 2012 tables
Issue while inserting the records into the SQL Server 2012 table using the WCF SQL adapter. I am getting the following error message.

Error details: Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The start element with name "NewDataSet" and namespace "http://www.ATM.Schemas.ATMAcquirerTransactionsDetails" was unexpected. Please ensure that your input XML conforms to the schema for the operation.

URI:  mssql://WIN-UHMK25Q5BMH/BLUECLOUDSQL/ATM?

Action: TableOp/Insert/dbo/ATMAcquirerTransactionsDetails

Please help me resolve the issue.

答: I have similar problem. This is perhaps because the schema contains more than one element (NewDataSet must be the second, judging by my case). This means you are trying to write simultaneously to two tables. I haven't figured out a solution yet.</p>


问:
How to automatically save plotly images of type "surface" in R (webGL issue)
this is my first question within stackoverflow and I want to thank for the useful hints and solutions helping me out so many times before! But since a few weeks I have an issue, which I couldn´t solve and as well I couldn´t find any solution within the www. I´m working with measured 3D data and trying to set up a code for imaging the data. Therefor I´m using the package plotly so far. After some time I get it worked and the result is okay for me. Next I implemented it within a loop because there are several measured samples. For documentation matters I need to store an image of each sample and that´s not working in an automated way. At the moment the loop runs well and within RStudio there is the subwindow for the 3d-Plotly-Viewer. I need to store each sample manually and this takes a lot of time. So I tried to automate it, but without success. The problem is shown by the simple code below:

```<code>library(plotly)
zz <- data.frame(c(0,0,0,0,0),c(0.1,.2,.4,.2,.1),c(0.2,.4,.8,.4,.2),c(0.1,.2,.4,.2,.1),c(0,0,0,0,0))
zz <- cbind(t(zz),rep(NA,length(zz[,1])))
xx <- rep(seq(-1,1.5,.5),5)
print(plot_ly(z=zz,x=xx, type="surface"))

# My simple way, which doesn´t work.
# Storing in the working directory
export(p = last_plot(), file = "plotly.png")
</code>```

The result of implementing this in the loop is an image without the surface like shown in the viewer (the scale bar is shown?!)

Additionally there is a text hint "WebGl is not supported by your browser - visit http://get.webgl.org for more info". Visiting this pages leads to the information, that my browser supports WebGL (Mozilla Firefox).

My suggestions: While exporting with "export" a html-file appears for a short time within the working directory. It is deleted after some seconds right before the image-file appears. I suggest this is in matter of using the webshot-package (or something connected to that). I stored a copy of the html-file while processing and opened it in my browser. It is just an empty window with the toolbar of plotly appearing in the right upper corner (though webGL seems to work at the browser). Maybe there are any configurations disabled within the webshot package? Could it be a matter of rights (I´m not the administrator) or is there even a bug with the graphic card (integrated Intel® HD-Grafik 4600)? I´m fishing in murky waters..

Edit:

OS: Win7 Professional SP1

RStudio: Version 0.99.902 (Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) rstudio Safari/538.1 Qt/5.4.1)

Browser: Firefox Quantum 57.0 (32-Bit)

Is there any idea how to solve that? I would like to automatically save an image out of the plotly-viewer. Any solutions are appreciate!

Best regards
Stefan

答:
I tried your example and i do not get the same error as you get. PhantomJS is needed so it R can "take a printscreen" of the plot being plotted with plotly and i think it needs other packages. This work for me, it might work in your computer but as I said in the comment exporting 3D plotly plots is a pain (you'll see why):

```<code>library(plotly)
zz <- data.frame(c(0,0,0,0,0),c(0.1,.2,.4,.2,.1),c(0.2,.4,.8,.4,.2),c(0.1,.2,.4,.2,.1),c(0,0,0,0,0))
zz <- cbind(t(zz),rep(NA,length(zz[,1])))
xx <- rep(seq(-1,1.5,.5),5)
print(plot_ly(z=zz,x=xx, type="surface"))

if (requireNamespace("RSelenium")) {
  rD <- RSelenium::rsDriver(browser = "chrome")
  export(last_plot(), "plot.png", rD)
}
</code>```

Body:
this is my first question within stackoverflow and I want to thank for the useful hints and solutions helping me out so many times before! But since a few weeks I have an issue, which I couldn´t solve and as well I couldn´t find any solution within the www. I´m working with measured 3D data and trying to set up a code for imaging the data. Therefor I´m using the package plotly so far. After some time I get it worked and the result is okay for me. Next I implemented it within a loop because there are several measured samples. For documentation matters I need to store an image of each sample and that´s not working in an automated way. At the moment the loop runs well and within RStudio there is the subwindow for the 3d-Plotly-Viewer. I need to store each sample manually and this takes a lot of time. So I tried to automate it, but without success. The problem is shown by the simple code below:

library(plotly)
zz <- data.frame(c(0,0,0,0,0),c(0.1,.2,.4,.2,.1),c(0.2,.4,.8,.4,.2),c(0.1,.2,.4,.2,.1),c(0,0,0,0,0))
zz <- cbind(t(zz),rep(NA,length(zz[,1])))
xx <- rep(seq(-1,1.5,.5),5)
print(plot_ly(z=zz,x=xx, type="surface"))

# My simple way, which doesn´t work.
# Storing in the working directory
export(p = last_plot(), file = "plotly.png")

The result of implementing this in the loop is an image without the surface like shown in the viewer (the scale bar is shown?!)

Additionally there is a text hint "WebGl is not supported by your browser - visit http://get.webgl.org for more info". Visiting this pages leads to the information, that my browser supports WebGL (Mozilla Firefox).

My suggestions: While exporting with "export" a html-file appears for a short time within the working directory. It is deleted after some seconds right before the image-file appears. I suggest this is in matter of using the webshot-package (or something connected to that). I stored a copy of the html-file while processing and opened it in my browser. It is just an empty window with the toolbar of plotly appearing in the right upper corner (though webGL seems to work at the browser). Maybe there are any configurations disabled within the webshot package? Could it be a matter of rights (I´m not the administrator) or is there even a bug with the graphic card (integrated Intel® HD-Grafik 4600)? I´m fishing in murky waters..

Edit:

OS: Win7 Professional SP1

RStudio: Version 0.99.902 (Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) rstudio Safari/538.1 Qt/5.4.1)

Browser: Firefox Quantum 57.0 (32-Bit)

Is there any idea how to solve that? I would like to automatically save an image out of the plotly-viewer. Any solutions are appreciate!

Best regards
Stefan

Body:
I tried your example and i do not get the same error as you get. PhantomJS is needed so it R can "take a printscreen" of the plot being plotted with plotly and i think it needs other packages. This work for me, it might work in your computer but as I said in the comment exporting 3D plotly plots is a pain (you'll see why):

library(plotly)
zz <- data.frame(c(0,0,0,0,0),c(0.1,.2,.4,.2,.1),c(0.2,.4,.8,.4,.2),c(0.1,.2,.4,.2,.1),c(0,0,0,0,0))
zz <- cbind(t(zz),rep(NA,length(zz[,1])))
xx <- rep(seq(-1,1.5,.5),5)
print(plot_ly(z=zz,x=xx, type="surface"))

if (requireNamespace("RSelenium")) {
  rD <- RSelenium::rsDriver(browser = "chrome")
  export(last_plot(), "plot.png", rD)
}