问:
How to drop all tables in a SQL Server database?
I'm trying to write a script that will completely empty a SQL Server database. This is what I have so far:

```<code>USE [dbname]
GO
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
EXEC sp_msforeachtable 'DELETE ?'
</code>```

When I run it in the Management Studio, I get:

Command(s) completed successfully.

but when I refresh the table list, they are all still there. What am I doing wrong?

答:
The accepted answer doesn't support Azure. It uses an undocumented stored procedure "sp_MSforeachtable". If you get an "azure could not find stored procedure 'sp_msforeachtable" error when running or simply want to avoid relying on undocumented features (which can be removed or have their functionality changed at any point) then try the below.

This version ignores the entity framework migration history table "__MigrationHistory" and the "database_firewall_rules" which is an Azure table you will not have permission to delete.

Lightly tested on Azure. Do check to make this this has no undesired effects on your environment.

```<code>DECLARE @sql NVARCHAR(2000)

WHILE(EXISTS(SELECT 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY'))
BEGIN
    SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
    EXEC(@sql)
    PRINT @sql
END

WHILE(EXISTS(SELECT * from INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'))
BEGIN
    SELECT TOP 1 @sql=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'
    EXEC(@sql)
    PRINT @sql
END
</code>```

Taken from:

https://edspencer.me.uk/2013/02/25/drop-all-tables-in-a-sql-server-database-azure-friendly/

http://www.sqlservercentral.com/blogs/sqlservertips/2011/10/11/remove-all-foreign-keys/

Body:
I'm trying to write a script that will completely empty a SQL Server database. This is what I have so far:

USE [dbname]
GO
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
EXEC sp_msforeachtable 'DELETE ?'

When I run it in the Management Studio, I get:

Command(s) completed successfully.

but when I refresh the table list, they are all still there. What am I doing wrong?

Body:
The accepted answer doesn't support Azure. It uses an undocumented stored procedure "sp_MSforeachtable". If you get an "azure could not find stored procedure 'sp_msforeachtable" error when running or simply want to avoid relying on undocumented features (which can be removed or have their functionality changed at any point) then try the below.

This version ignores the entity framework migration history table "__MigrationHistory" and the "database_firewall_rules" which is an Azure table you will not have permission to delete.

Lightly tested on Azure. Do check to make this this has no undesired effects on your environment.

DECLARE @sql NVARCHAR(2000)

WHILE(EXISTS(SELECT 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY'))
BEGIN
    SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
    EXEC(@sql)
    PRINT @sql
END

WHILE(EXISTS(SELECT * from INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'))
BEGIN
    SELECT TOP 1 @sql=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'
    EXEC(@sql)
    PRINT @sql
END

Taken from:

https://edspencer.me.uk/2013/02/25/drop-all-tables-in-a-sql-server-database-azure-friendly/

http://www.sqlservercentral.com/blogs/sqlservertips/2011/10/11/remove-all-foreign-keys/


来源: stackexchange

问:
How socket send data?
I got a snippet from internet for send data through a socket .

Here is the code .

```<code>u32_t nLength = 0;
u32_t nOffset = 0;

do {
    nLength = nFullLength - nOffset;
    status = Socket->Send(((u8_t*) buff) + nOffset, &nLength);
    if (status != ERROR_SUCCESS) {
        break;
    }
    nOffset += nLength;
} while (nOffset < nFullLength);
</code>```

My doubts are :

When send(sock_fd, buf+bytes, buflen-bytes, flags); function running , it will send the entire data ?

Let's assume i have a buff with 45 byte length . So it will send like

```<code>send(buf+0, 45-0) = send(buf+0, 45);
</code>```

So it will send complete  data with length 45 ? what is the use of length here ? initially it will 45 . Isn't ?

答:
TCP is a streaming transport.  There is no guarantee that a given send() operation will accept all of the bytes given to it at one time.  It depends on the available kernel buffer space, the I/O mode of the socket (blocking vs non-blocking), etc.  send() returns the number of bytes it actually accepted  and put into the kernel buffer for subsequent transmission.

In the code example shown, it appears that Socket->Send() expects nLength to be initially set to the total number of bytes to sent, and it will then update nLength with the number of bytes actually sent. The code is adjusting its nOffset variable accordingly, looping just in case send() returns fewer bytes than requested, so it can call send() as many times as it takes to send the full number of bytes.

So, for example, lets assume the kernel accepts up to 20 bytes at a time.  The loop would call send() 3 times:

```<code>send(buf+0, 45-0)   // returns 20
send(buf+20, 45-20) // returns 20
send(buf+40, 45-40) // returns 5
// done
</code>```

This is typical coding practice for TCP programming, given the streaming nature of TCP.

ContentLicense: CC BY-SA 3.0

Title: How socket send data?

Body:
I got a snippet from internet for send data through a socket .

Here is the code .

u32_t nLength = 0;
u32_t nOffset = 0;

do {
    nLength = nFullLength - nOffset;
    status = Socket->Send(((u8_t*) buff) + nOffset, &nLength);
    if (status != ERROR_SUCCESS) {
        break;
    }
    nOffset += nLength;
} while (nOffset < nFullLength);

My doubts are :

When send(sock_fd, buf+bytes, buflen-bytes, flags); function running , it will send the entire data ?

Let's assume i have a buff with 45 byte length . So it will send like

send(buf+0, 45-0) = send(buf+0, 45);

So it will send complete  data with length 45 ? what is the use of length here ? initially it will 45 . Isn't ?

Body:
TCP is a streaming transport.  There is no guarantee that a given send() operation will accept all of the bytes given to it at one time.  It depends on the available kernel buffer space, the I/O mode of the socket (blocking vs non-blocking), etc.  send() returns the number of bytes it actually accepted  and put into the kernel buffer for subsequent transmission.

In the code example shown, it appears that Socket->Send() expects nLength to be initially set to the total number of bytes to sent, and it will then update nLength with the number of bytes actually sent. The code is adjusting its nOffset variable accordingly, looping just in case send() returns fewer bytes than requested, so it can call send() as many times as it takes to send the full number of bytes.

So, for example, lets assume the kernel accepts up to 20 bytes at a time.  The loop would call send() 3 times:

send(buf+0, 45-0)   // returns 20
send(buf+20, 45-20) // returns 20
send(buf+40, 45-40) // returns 5
// done

This is typical coding practice for TCP programming, given the streaming nature of TCP.


问:
axis limit and sharex in matplotlib
I would like to show two images like these.

```<code>import matplotlib as plt
import numpy as np
fig, axes = plt.subplots(2, 1, )
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))
</code>```

Then, I tried sharex=True, which unexpectedly changed the ylim of the two plots. Why?? Is it possible to align the plots without changing the y axis limits?

```<code>fig, axes = plt.subplots(2, 1, sharex=True)
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))
</code>```

I use python 3.5.2 and matplotlib 1.5.1.

答:
By default imshow axes have an equal aspect ratio. To preserve this, the limits are changed.

You have two options:

a) Dispense with equal aspect

Set the aspect to "auto". This allows the subplots to take the available space and share their axis.

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

fig, axes = plt.subplots(2, 1,sharex=True )
axes[0].imshow(np.random.random((3, 3)), aspect="auto")
axes[1].imshow(np.random.random((6, 3)), aspect="auto")

plt.show()
</code>```

b) Adjust the figure size or spacings

You can adjust the figure size or the spacings such that the axes actually match. You'd then also need to set the height_ratios according to the image dimensions.

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

fig, axes = plt.subplots(2, 1,sharex=True, figsize=(3,5),
                            gridspec_kw={"height_ratios":[1,2]} )
plt.subplots_adjust(top=0.9, bottom=0.1, left=0.295, right=0.705, hspace=0.2)
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))

plt.show()
</code>```

This method either involves some trial and error or a sophisticated calculation, as e.g. in this answer.

Title: axis limit and sharex in matplotlib

Body:
I would like to show two images like these.

import matplotlib as plt
import numpy as np
fig, axes = plt.subplots(2, 1, )
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))

Then, I tried sharex=True, which unexpectedly changed the ylim of the two plots. Why?? Is it possible to align the plots without changing the y axis limits?

fig, axes = plt.subplots(2, 1, sharex=True)
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))

I use python 3.5.2 and matplotlib 1.5.1.

Body:
By default imshow axes have an equal aspect ratio. To preserve this, the limits are changed.

You have two options:

a) Dispense with equal aspect

Set the aspect to "auto". This allows the subplots to take the available space and share their axis.

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 1,sharex=True )
axes[0].imshow(np.random.random((3, 3)), aspect="auto")
axes[1].imshow(np.random.random((6, 3)), aspect="auto")

plt.show()

b) Adjust the figure size or spacings

You can adjust the figure size or the spacings such that the axes actually match. You'd then also need to set the height_ratios according to the image dimensions.

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 1,sharex=True, figsize=(3,5),
                            gridspec_kw={"height_ratios":[1,2]} )
plt.subplots_adjust(top=0.9, bottom=0.1, left=0.295, right=0.705, hspace=0.2)
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))

plt.show()

This method either involves some trial and error or a sophisticated calculation, as e.g. in this answer.


问:
how to use the object property of NSNotificationcenter
Could somebody please show me how to use the object property on NSNotifcationCenter. I want to be able to use it to pass an integer value to my selector method.

This is how I have set up the notification listener in my UI View. Seeing as I want an integer value to be passed I'm not sure what to replace nil with.

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"myevent" object:nil];

- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}
</code>```

I dispatch the notification from another class like this. The function is passed a variable named index. It's this value that I want to somehow fire off with the notification.

```<code>-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}
</code>```

答:
The object parameter represents the sender of the notification, which is usually self.

If you wish to pass along extra information, you need to use the NSNotificationCenter method postNotificationName:object:userInfo:, which takes an arbitrary dictionary of values (that you are free to define).  The contents needs to be actual NSObject instances, not an integral type such as an integer, so you need to wrap the integer values with NSNumber objects.

```<code>NSDictionary* dict = [NSDictionary dictionaryWithObject:
                         [NSNumber numberWithInt:index]
                      forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent"
                                      object:self
                                      userInfo:dict];
</code>```

Body:
Could somebody please show me how to use the object property on NSNotifcationCenter. I want to be able to use it to pass an integer value to my selector method.

This is how I have set up the notification listener in my UI View. Seeing as I want an integer value to be passed I'm not sure what to replace nil with.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"myevent" object:nil];

- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}

I dispatch the notification from another class like this. The function is passed a variable named index. It's this value that I want to somehow fire off with the notification.

-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}

Body:
The object parameter represents the sender of the notification, which is usually self.

If you wish to pass along extra information, you need to use the NSNotificationCenter method postNotificationName:object:userInfo:, which takes an arbitrary dictionary of values (that you are free to define).  The contents needs to be actual NSObject instances, not an integral type such as an integer, so you need to wrap the integer values with NSNumber objects.

NSDictionary* dict = [NSDictionary dictionaryWithObject:
                         [NSNumber numberWithInt:index]
                      forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent"
                                      object:self
                                      userInfo:dict];

ContentLicense: CC BY-SA 2.5


问:
PropertyChangedEventManager and Moq'd Interfaces
When Mocking (using Moq) an interface/object that supports INotifyPropertyChanged, using PropertyChangedEventManager.AddHandler doesn't property connect up to the event as raised by Raise. A direct += connection works correctly however:

```<code>bool _EventMangerCalled = false;
bool _DirectCalled = false;

private void EventManagerHandler(object sender, PropertyChangedEventArgs e)
{
    _EventMangerCalled = true;
}

private void DirectHandler(object sender, PropertyChangedEventArgs e)
{
    _DirectCalled = true;
}

[TestMethod]
public void PropertyChangedEventManager_AddHandler_OnMoq()
{
    var m = new Mock<INotifyPropertyChanged>();
    m.Object.PropertyChanged += DirectHandler;
    PropertyChangedEventManager.AddHandler(m.Object, EventManagerHandler, "Foo");

    m.Raise(x=>x.PropertyChanged += null, this, new PropertyChangedEventArgs("Foo"));
    // Success
    Assert.IsTrue(_DirectCalled, "directCalled is not true");
    // Failure
    Assert.IsTrue(_EventMangerCalled, "eventManagerCalled is not true");
}
</code>```

I've also tried string.Empty instead of "Foo" in the AddHandler (the way it happens in my actual code). Is there a different way to Raise the event which would work, or any ideas of another way around this? I want to be able to test the event handling of objects which require weak subscriptions.

答:
First of all, think about your first assertion:

```<code>var mock = new Mock<INotifyPropertyChanged>();
mock.Object.PropertyChanged += DirectHandler;
mock.Raise(x=>x.PropertyChanged += null, this, new PropertyChangedEventArgs("Foo"));
Assert.IsTrue(_DirectCalled, "directCalled is not true");
</code>```

You verify that when you raise event on mock object, event handler (which is attached to event of mocked object) will be called. In other words, you are testing implementation of Moq library. Don't worry, it's already tested.

Next, to raise event you don't need to pass reference to class where your tests are defined (this) - simply pass EventArgs which should be passed to handlers:

```<code>.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Foo"))
</code>```

It's hard to tell what behavior your PropertyChangedEventManager should have, but I assume that it should run given handler if source object raised NotifyPropertyChanged event for given property. Sounds good. It's easy to test handler invocations with clojures - use lambda delegate which captures local variable (flag) and changes it when lambda was called:

```<code>[TestMethod]
public void ShouldInvokeHandlerWhenSpecifiedPropertyChanged()
{
    var sourceMock = new Mock<INotifyPropertyChanged>();
    var sut = new PropertyChangedEventManager();
    bool handlerInvoked = false;
    sut.AddHandler(sourceMock.Object, (s, e) => handlerInvoked = true, "Foo");

    sourceMock.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Foo"));

    Assert.IsTrue(handlerInvoked);
}
</code>```

Simplest implementation which makes this test pass will be

```<code>public class PropertyChangedEventManager
{
    public void AddHandler(
        INotifyPropertyChanged source,
        EventHandler<PropertyChangedEventArgs> handler,
        string propertyName)
    {
        source.PropertyChanged += (s, e) => {
            if (e.PropertyName == propertyName)
                handler(s, e);
        };
    }
}
</code>```

Next you should check that handler was not called if source raised event for other property. Change two lines:

```<code>[TestMethod]
public void ShouldNotInvokeHandlerWhenOtherPropertyChanged()
{
    var sourceMock = new Mock<INotifyPropertyChanged>();
    var sut = new PropertyChangedEventManager();
    bool handlerInvoked = false;
    sut.AddHandler(sourceMock.Object, (s, e) => handlerInvoked = true, "Foo");

    sourceMock.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Bar"));

    Assert.IsFalse(handlerInvoked);
}
</code>```

Body:
When Mocking (using Moq) an interface/object that supports INotifyPropertyChanged, using PropertyChangedEventManager.AddHandler doesn't property connect up to the event as raised by Raise. A direct += connection works correctly however:

bool _EventMangerCalled = false;
bool _DirectCalled = false;

private void EventManagerHandler(object sender, PropertyChangedEventArgs e)
{
    _EventMangerCalled = true;
}

private void DirectHandler(object sender, PropertyChangedEventArgs e)
{
    _DirectCalled = true;
}

[TestMethod]
public void PropertyChangedEventManager_AddHandler_OnMoq()
{
    var m = new Mock<INotifyPropertyChanged>();
    m.Object.PropertyChanged += DirectHandler;
    PropertyChangedEventManager.AddHandler(m.Object, EventManagerHandler, "Foo");

    m.Raise(x=>x.PropertyChanged += null, this, new PropertyChangedEventArgs("Foo"));
    // Success
    Assert.IsTrue(_DirectCalled, "directCalled is not true");
    // Failure
    Assert.IsTrue(_EventMangerCalled, "eventManagerCalled is not true");
}

I've also tried string.Empty instead of "Foo" in the AddHandler (the way it happens in my actual code). Is there a different way to Raise the event which would work, or any ideas of another way around this? I want to be able to test the event handling of objects which require weak subscriptions.

Body:
First of all, think about your first assertion:

var mock = new Mock<INotifyPropertyChanged>();
mock.Object.PropertyChanged += DirectHandler;
mock.Raise(x=>x.PropertyChanged += null, this, new PropertyChangedEventArgs("Foo"));
Assert.IsTrue(_DirectCalled, "directCalled is not true");

You verify that when you raise event on mock object, event handler (which is attached to event of mocked object) will be called. In other words, you are testing implementation of Moq library. Don't worry, it's already tested.

Next, to raise event you don't need to pass reference to class where your tests are defined (this) - simply pass EventArgs which should be passed to handlers:

.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Foo"))

It's hard to tell what behavior your PropertyChangedEventManager should have, but I assume that it should run given handler if source object raised NotifyPropertyChanged event for given property. Sounds good. It's easy to test handler invocations with clojures - use lambda delegate which captures local variable (flag) and changes it when lambda was called:

[TestMethod]
public void ShouldInvokeHandlerWhenSpecifiedPropertyChanged()
{
    var sourceMock = new Mock<INotifyPropertyChanged>();
    var sut = new PropertyChangedEventManager();
    bool handlerInvoked = false;
    sut.AddHandler(sourceMock.Object, (s, e) => handlerInvoked = true, "Foo");

    sourceMock.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Foo"));

    Assert.IsTrue(handlerInvoked);
}

Simplest implementation which makes this test pass will be

public class PropertyChangedEventManager
{
    public void AddHandler(
        INotifyPropertyChanged source,
        EventHandler<PropertyChangedEventArgs> handler,
        string propertyName)
    {
        source.PropertyChanged += (s, e) => {
            if (e.PropertyName == propertyName)
                handler(s, e);
        };
    }
}

Next you should check that handler was not called if source raised event for other property. Change two lines:

[TestMethod]
public void ShouldNotInvokeHandlerWhenOtherPropertyChanged()
{
    var sourceMock = new Mock<INotifyPropertyChanged>();
    var sut = new PropertyChangedEventManager();
    bool handlerInvoked = false;
    sut.AddHandler(sourceMock.Object, (s, e) => handlerInvoked = true, "Foo");

    sourceMock.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Bar"));

    Assert.IsFalse(handlerInvoked);
}


问:
Can an Azure container with a blob that has a snapshot be deleted?
I know that an Azure blob with snapshots cannot be deleted until all the snapshots are deleted.  Would it be possible, though, to delete the container that houses the blob (and, by extension, that blob too)?</p>

答:
You should have no problem deleting a non-empty container, as long as there's no lease on the container or content within the container (e.g. a vhd in use as a disk for  VM).

Not sure which SDK you're using (or just raw REST) but... pretty trivial in node.js. Assuming you created a container called deleteme and uploaded a few blobs to it:

```<code>var azure = require('azure-storage')
var blobSvc = azure.createBlobService();
blobSvc.deleteContainer('deleteme', function(error, result, response){
    if(!error){
      console.log('deleted')
    }
    else {
        console.log('not deleted')
    }
});
</code>```

Note the use of deleteContainer(). Once deleted, this call will fail. However, you can use deleteContainerIfExists() which should continue to work even if the container is no longer there.

Also note: this works even if blobs within the container have snapshots.

Body:
You should have no problem deleting a non-empty container, as long as there's no lease on the container or content within the container (e.g. a vhd in use as a disk for  VM).

Not sure which SDK you're using (or just raw REST) but... pretty trivial in node.js. Assuming you created a container called deleteme and uploaded a few blobs to it:

var azure = require('azure-storage')
var blobSvc = azure.createBlobService();
blobSvc.deleteContainer('deleteme', function(error, result, response){
    if(!error){
      console.log('deleted')
    }
    else {
        console.log('not deleted')
    }
});

Note the use of deleteContainer(). Once deleted, this call will fail. However, you can use deleteContainerIfExists() which should continue to work even if the container is no longer there.

Also note: this works even if blobs within the container have snapshots.


问:
Extracting data from website
I am new to python and I wanted to do a technical analysis of equities.
Following is the website from which I can get data by defining start and end dates.
http://www.scstrade.com/StockScreening/SS_CompanySnapShotHP.aspx?symbol=LOTCHEM

I am familiar with pandas and numpy. After doing a search on web I came across a library BeautifulSoup which can help extract data. My question is that will above mentioned library would be sufficient enough to extract data from the above mentioned link by defining start and end dates. Or if someone can suggest of any other library or another smart way to extract data.

答:
There are 3 options in my opinion:

use the module requests if you need a simple scraping.

use the selenium module in order to simulate actual browser activity with a browser driver. If the page populate the data with JavaScript, selenium may come in handy.

another good options is mechanize,

For more information about them: requests or selenium or mechanize.

Title: Extracting data from website


问:
Jquery Animation cloud9 carousel add active class
Here I'm using http://specious.github.io/cloud9carousel/ slider,
 I would like to add active class when image rotate on front of side.</p>

答:
you can add "onRendered" callback function
i used it and working for me </p>

```<code>var showcase = $("#showcase")
var card = $("#showcase .card")
showcase.Cloud9Carousel( {
        yOrigin: 42,
        yRadius: 40,
        itemClass: "card",
        buttonLeft: $(".nav2.prev"),
        buttonRight: $(".nav2.next"),
        bringToFront: true,
        onRendered: showcaseUpdated,
        onLoaded: function() {
          showcase.css( 'visibility', 'visible' )
          showcase.css( 'display', 'none' )
          showcase.fadeIn( 1500 )
        }
      } )
      function showcaseUpdated( showcase ) {
        $(card).removeClass('active');
        var index = showcase.nearestIndex();
        $(showcase.items[index].element).addClass('active');
      }
</code>```

Body:
you can add "onRendered" callback function
i used it and working for me

var showcase = $("#showcase")
var card = $("#showcase .card")
showcase.Cloud9Carousel( {
        yOrigin: 42,
        yRadius: 40,
        itemClass: "card",
        buttonLeft: $(".nav2.prev"),
        buttonRight: $(".nav2.next"),
        bringToFront: true,
        onRendered: showcaseUpdated,
        onLoaded: function() {
          showcase.css( 'visibility', 'visible' )
          showcase.css( 'display', 'none' )
          showcase.fadeIn( 1500 )
        }
      } )
      function showcaseUpdated( showcase ) {
        $(card).removeClass('active');
        var index = showcase.nearestIndex();
        $(showcase.items[index].element).addClass('active');
      }


问:
jsViews checking length returns error
I am using jSViews and getting data back via JSON and then linking to the template.

The template shows the data I am sending it, however I have a simple post template with an array of comments.

If I try and check that the length of the array is greater than 0, using lenth, it crashed with:

0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference

here is a snippet of code:

```<code>$.getJSON("/students/dashboard/GetDashboardPosts")
.done(function (json) {
    posts_data = json;

    if (posts_data) {
       if (posts_data.length > 0) {
            var posts_html = $("#posts-template").render(posts_data);
            $(".posts .row").html(posts_html);

            $.templates("#post-detail-template").link(".single-post-detail .row", post_detail); // post_detail is initially an empty object
        }

    }

$(".post").on("click", "#posts-section", function (event) {
    // get the index of the clicked item - should be able to do this with $.view but it isnt working - check it out.
    var idx = $(this).closest(".dashboard-post").attr("data-index");

    // update it observably so we dont have to traverse the DOM.
    $.observable(post_detail).setProperty(
        (posts_data[idx])
    );
    $("body").addClass("has-overlay");
    $(".single-post-detail").addClass("expanded");

});

script id="post-detail-template" type="text/x-jsrender">
<div class="col s12 m12 l6 post">
    ...
    ...
            {^{if comments.length > 0}}
                {^{include comments tmpl="#post-detail-comments-template"/}}:
            {{/if}}
        </div>
</script>

script id="post-detail-comments-template" type="text/x-jsrender">
<section class="comments-section">
    <ul class="comments-list">
        {^{for #data}}
        <li class="comment-item">
           ...
        </li>
        {{/for}}
    </ul>
</section>
</code>```

I can hack it using a helper:

```<code>{^{if ~hasLength(comments)}}
                {^{include comments tmpl="#post-detail-comments-template"/}}:
 {{/if}}

var viewHelpers = {
    hasLength: function (arr) {
        if (!arr) { return false; }

        var x = arr;
        if (x.length > 0) {
            return true;
        }
        return false;

    }
};

$.views.helpers(viewHelpers);
</code>```

however I cant understand why it is giving me this error as ideally, I just want to include the comments template IF there are comments and not have to use an if at all, but this is the only way I can get it to work

答:
If the post_detail has no comments property then {^{if comments.length}} will indeed produce an error. If you include a 'null check' it should work:

```<code>{^{if comments && comments.length > 0}}...{{/if}}
</code>```

Title: jsViews checking length returns error

Body:
I am using jSViews and getting data back via JSON and then linking to the template.

The template shows the data I am sending it, however I have a simple post template with an array of comments.

If I try and check that the length of the array is greater than 0, using lenth, it crashed with:

0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference

here is a snippet of code:

$.getJSON("/students/dashboard/GetDashboardPosts")
.done(function (json) {
    posts_data = json;

    if (posts_data) {
       if (posts_data.length > 0) {
            var posts_html = $("#posts-template").render(posts_data);
            $(".posts .row").html(posts_html);

            $.templates("#post-detail-template").link(".single-post-detail .row", post_detail); // post_detail is initially an empty object
        }

    }

$(".post").on("click", "#posts-section", function (event) {
    // get the index of the clicked item - should be able to do this with $.view but it isnt working - check it out.
    var idx = $(this).closest(".dashboard-post").attr("data-index");

    // update it observably so we dont have to traverse the DOM.
    $.observable(post_detail).setProperty(
        (posts_data[idx])
    );
    $("body").addClass("has-overlay");
    $(".single-post-detail").addClass("expanded");

});

script id="post-detail-template" type="text/x-jsrender">

    ...
    ...
            {^{if comments.length > 0}}
                {^{include comments tmpl="#post-detail-comments-template"/}}:
            {{/if}}

</script>

script id="post-detail-comments-template" type="text/x-jsrender">

        {^{for #data}}

           ...

        {{/for}}

I can hack it using a helper:

{^{if ~hasLength(comments)}}
                {^{include comments tmpl="#post-detail-comments-template"/}}:
 {{/if}}

var viewHelpers = {
    hasLength: function (arr) {
        if (!arr) { return false; }

        var x = arr;
        if (x.length > 0) {
            return true;
        }
        return false;

    }
};

$.views.helpers(viewHelpers);

however I cant understand why it is giving me this error as ideally, I just want to include the comments template IF there are comments and not have to use an if at all, but this is the only way I can get it to work

Body:
If the post_detail has no comments property then {^{if comments.length}} will indeed produce an error. If you include a 'null check' it should work:

{^{if comments && comments.length > 0}}...{{/if}}


问:
Is there any benefit to using getters/setters inside a class for its own fields?
Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

答:
If there is any business logic around those values (or there is the potential for such logic), then there is a benefit to using getters and setters even for internal calls.

For example, your setter might do validation on its inputs, and throw an exception rather than store an invalid value. Having all your code use that setter rather than simply setting values directly means that the error is caught at the time it is made rather than a long time later when that value is used. A similar case for a getter is when there is a logical default value, which should be used in case of a null. By using a getter, you can safely write local methods without needing continuous null checks or default options.

That said, if there's no business logic in those methods, and no side effects caused by them, then it's mostly a stylistic thing. It is essentially the responsibility of the class to be internally consistent, and as long as it remains so then it's mostly personal/professional preference whether you access the variables directly or through wrapping methods.


问:
EC2 IAM policy to require tags
AWS just released required tag support for EC2/EBS:
New – Tag EC2 Instances & EBS Volumes on Creation.

However, the example given only checks if tags have a fixed value which isn't useful to us because our users can enter free form values for required tags. How can a policy be written to check tags are present?

For example, we need something like this:

```<code>"Statement": [
    {
      "Sid": "DenyMissingTags",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:us-east-1:accountid:instance/*",
      "Condition": {
        "StringExists": [
          "aws:RequestTag/costcenter",
          "aws:RequestTag/stack",
         ]
       }
     }
]
</code>```

Obviously, I made up StringExists

答:
That page actually lists the tag enforcement as:

```<code>  "Condition": {
    "StringEquals": {
      "aws:RequestTag/costcenter": "115",
      "aws:RequestTag/stack": "prod"
     },
     "ForAllValues:StringEquals": {
         "aws:TagKeys": ["costcenter","stack"]
     }
   }
</code>```

The documentation for ForAllValues says:

the ForAllValues qualifier requires all requested values to be listed in the policy

So, that part probably enforces the presence of a tag, without enforcing the actual contents.

Title: EC2 IAM policy to require tags

Body:
AWS just released required tag support for EC2/EBS:
New – Tag EC2 Instances & EBS Volumes on Creation.

However, the example given only checks if tags have a fixed value which isn't useful to us because our users can enter free form values for required tags. How can a policy be written to check tags are present?

For example, we need something like this:

"Statement": [
    {
      "Sid": "DenyMissingTags",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:us-east-1:accountid:instance/*",
      "Condition": {
        "StringExists": [
          "aws:RequestTag/costcenter",
          "aws:RequestTag/stack",
         ]
       }
     }
]

Obviously, I made up StringExists

Body:
That page actually lists the tag enforcement as:

  "Condition": {
    "StringEquals": {
      "aws:RequestTag/costcenter": "115",
      "aws:RequestTag/stack": "prod"
     },
     "ForAllValues:StringEquals": {
         "aws:TagKeys": ["costcenter","stack"]
     }
   }

The documentation for ForAllValues says:

the ForAllValues qualifier requires all requested values to be listed in the policy

So, that part probably enforces the presence of a tag, without enforcing the actual contents.


答:
I figured it out... For the direct case, the "sender" is never checked. But the PropertyChangedManager uses it as a key for subscriptions. My:

```<code>m.Raise(x=>x.PropertyChanged += null, this, new PropertyChangedEventArgs("Foo"));
</code>```

Should have been:

```<code>m.Raise(x=>x.PropertyChanged += null, m.Object, new PropertyChangedEventArgs("Foo"));
</code>```

Title: PropertyChangedEventManager and Moq'd Interfaces

Body:
I figured it out... For the direct case, the "sender" is never checked. But the PropertyChangedManager uses it as a key for subscriptions. My:

m.Raise(x=>x.PropertyChanged += null, this, new PropertyChangedEventArgs("Foo"));

Should have been:

m.Raise(x=>x.PropertyChanged += null, m.Object, new PropertyChangedEventArgs("Foo"));


问:
How to remove file with invalid name (Ubuntu)?
By mistake I have createad file with name:

```<code>0);          if (count($keys->toArray())  0) {              $this->obj->api(messages.send, [                 access_token > $this->group->getAccessToken(),                 user_id > $this->userId,                 message > Я
</code>```

I'm not able to remove it via ssh or sftp.

Is there any way?

答: You can just delete it with  rm ./0)  (and tab to complete).</p>

Body:
By mistake I have createad file with name:

0);          if (count($keys->toArray())  0) {              $this->obj->api(messages.send, [                 access_token > $this->group->getAccessToken(),                 user_id > $this->userId,                 message > Я

I'm not able to remove it via ssh or sftp.

Is there any way?


问:
Getting the number rows if the datetime colum value is with a certain interval
I have a start-date value of 2015-01-13 12:00 and end-date value of 2015-01-16 12:00, which is a 4-day interval. I want to get the number of days a student had an activity in each day of this interval. For example given this dataframe (please consider that there are duplicates as well):

```<code>userid  |  activityday
111        2015-01-13 12:00
111        2015-01-13 12:00
111        2015-01-14 12:00
222        2015-01-13 12:00
222        2015-01-14 12:00
222        2015-01-15 12:00
333        2015-01-13 12:00
333        2015-01-14 12:00
333        2015-01-15 12:00
333        2015-01-15 12:00
333        2015-01-16 12:00
</code>```

I want to obtain:

```<code>userid |  days_active
111    |  2
222    |  3
333    |  4
</code>```

I am able to do this using a loop but it takes very long. I wonder if there a handy way to achieve this?

答:
```<code>df.activityday.dt.date.groupby(df.userid).nunique()

userid
111    2
222    3
333    4
Name: activityday, dtype: int64
</code>```

what's happening

you can access many datetime related vectorized functions via the dt accessor.  dt.date simply returns the date part of the datetime values.  This is the part that we are concerned with in regards to number of activities within the day.

I then groupby 'useid' and use the nunique function (number unique) and viola.

You can add one small bit of formatting to get exactly what you asked for.  Namely reset_index

```<code>df.activityday.dt.date.groupby(
    df.userid
).nunique().reset_index(name='days_active')

   userid  days_active
0     111            2
1     222            3
2     333            4
</code>```

Body:
I have a start-date value of 2015-01-13 12:00 and end-date value of 2015-01-16 12:00, which is a 4-day interval. I want to get the number of days a student had an activity in each day of this interval. For example given this dataframe (please consider that there are duplicates as well):

userid  |  activityday
111        2015-01-13 12:00
111        2015-01-13 12:00
111        2015-01-14 12:00
222        2015-01-13 12:00
222        2015-01-14 12:00
222        2015-01-15 12:00
333        2015-01-13 12:00
333        2015-01-14 12:00
333        2015-01-15 12:00
333        2015-01-15 12:00
333        2015-01-16 12:00

I want to obtain:

userid |  days_active
111    |  2
222    |  3
333    |  4

I am able to do this using a loop but it takes very long. I wonder if there a handy way to achieve this?

Body:
df.activityday.dt.date.groupby(df.userid).nunique()

userid
111    2
222    3
333    4
Name: activityday, dtype: int64

what's happening

you can access many datetime related vectorized functions via the dt accessor.  dt.date simply returns the date part of the datetime values.  This is the part that we are concerned with in regards to number of activities within the day.

I then groupby 'useid' and use the nunique function (number unique) and viola.

You can add one small bit of formatting to get exactly what you asked for.  Namely reset_index

df.activityday.dt.date.groupby(
    df.userid
).nunique().reset_index(name='days_active')

   userid  days_active
0     111            2
1     222            3
2     333            4


问:
Understanding a malicious js file
I am trying my hand a reversing a malicious js script to find out what it does. the script is really long but there is one part I dont fully understand and hope you can help. I will only show a small part of the script with the relevant parts to help with this problem so as to avoid anyone accidentally running it.

The following line calls the function UU multiple times:

```<code>ib[0] = O(Arw,UU(1017-980)+UU(19+81)+UU(32*3)+UU(51+25)+UU(4508/98+0)+UU(671-606)+UU(1677/43+0)+UU(631-522)+UU(5*23)+UU(7719/83-0)+UU(6+93)+UU(4*23));
</code>```

The function UU has the following setup:

```<code>function UU(s)
{
    var Ea = ",!)Q ;Zrvz2^@HgS{I~1(O`ba'&l%$mqVCXG9#w0]d.-8W_34[kA5<n/RBDLsFN\\tpY6E7fy?oi|+\"xJ>ThUc=uKjeM:}*P";
    var h=30090;
    var yz=h+29060;
    var mm=yz/650;
    var PF=mm-60;  31
    var i = Ea[L(s)](s-PF);
    return i;
}
</code>```

Part of the operation to get the return value "i" calls the function L:

```<code>function L(R)
{
    return "\x63\x68\x61\x72A\x74";
}
</code>```

Question: what is function L returning?

I believe the function L is trying to obfuscate its return value so as to make analysis harder. I am not sure if I need to convert this to ASCII or Decimal in order to accurately complete the string lookup in function UU

答:
Those are escape characters. It is fairly easy to look up the values in the ASCII table, but you can also console.log the string to see the resulting value.

console.log("\x63\x68\x61\x72A\x74");```

It evaluates to charAt.

Title: Understanding a malicious js file

Body:
I am trying my hand a reversing a malicious js script to find out what it does. the script is really long but there is one part I dont fully understand and hope you can help. I will only show a small part of the script with the relevant parts to help with this problem so as to avoid anyone accidentally running it.

The following line calls the function UU multiple times:

ib[0] = O(Arw,UU(1017-980)+UU(19+81)+UU(32*3)+UU(51+25)+UU(4508/98+0)+UU(671-606)+UU(1677/43+0)+UU(631-522)+UU(5*23)+UU(7719/83-0)+UU(6+93)+UU(4*23));

The function UU has the following setup:

function UU(s)
{
    var Ea = ",!)Q ;Zrvz2^@HgS{I~1(O`ba'&l%$mqVCXG9#w0]d.-8W_34[kA5<n/RBDLsFN\\tpY6E7fy?oi|+\"xJ>ThUc=uKjeM:}*P";
    var h=30090;
    var yz=h+29060;
    var mm=yz/650;
    var PF=mm-60;  31
    var i = Ea[L(s)](s-PF);
    return i;
}

Part of the operation to get the return value "i" calls the function L:

function L(R)
{
    return "\x63\x68\x61\x72A\x74";
}

Question: what is function L returning?

I believe the function L is trying to obfuscate its return value so as to make analysis harder. I am not sure if I need to convert this to ASCII or Decimal in order to accurately complete the string lookup in function UU

Body:
Those are escape characters. It is fairly easy to look up the values in the ASCII table, but you can also console.log the string to see the resulting value.

console.log("\x63\x68\x61\x72A\x74");

It evaluates to charAt.


问:
The type initializer "Class" threw an exception.LoadLibrary failed
I have a service that tries to load a DLL. My service works fine on my development laptop, but when trying it two other laptops I get the following exception:

```<code>The type initializer for "NanoProtoApi.Interop" threw an exception. --->System.Exception: LoadLibrary failed: C:\Program Files\Proj\x64\Nanomsg.dll.
</code>```

I've checked the dll location and it is definitely there. I have no idea what is going on. Does anyone know what is going on and how to fix this issue?

Here is the exception stack trace:

```<code>System.TypeInitializationException: The type initializer for 'NanoProtoApi.Interop' threw an exception. ---> System.Exception: LoadLibrary failed: C:\Program Files\Proj\x64\Nanomsg.dll
   at NanoProtoApi.NanomsgLibraryLoader.LoadWindowsLibrary(String libName, SymbolLookupDelegate& symbolLookup)
   at NanoProtoApi.Interop..cctor()
   --- End of inner exception stack trace ---
   at NanoProtoApi.NanomsgSocketBase..ctor(Domain domain, Protocol protocol)
   at NanoProtoApi.Protocols.SubscribeSocket..ctor()
   at MK18.ATR.GATR.GatrProcessingClient.<>c.<runDetectReportFilteredTask>b__26_0() in C:\Users\user\Documents\MK 18\src\coin\mk18atr\project\Utilities\GatrProcessingClient.cs:line 238
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MK18.ATR.GATR.GatrProcessingClient.<SubscribeToDetectReportFiltered>d__25.MoveNext() in C:\Users\user\Documents\MK 18\src\coin\mk18atr\project\Utilities\GatrProcessingClient.cs:line 219
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
</code>```

答:
This usually means that some class in the library three an exception during static construction.  Since the exception happened the load fails.  In general libraries should take this into account and handle the failures at load time.
Since this works for you and there are some traces of network communication in the stack trace I am guessing that there is a problem trying to reach some remote resource.  Does this component require connections to other machines?  Can those machines be reached from the server?</p>

Body:
I have a service that tries to load a DLL. My service works fine on my development laptop, but when trying it two other laptops I get the following exception:

The type initializer for "NanoProtoApi.Interop" threw an exception. --->System.Exception: LoadLibrary failed: C:\Program Files\Proj\x64\Nanomsg.dll.

I've checked the dll location and it is definitely there. I have no idea what is going on. Does anyone know what is going on and how to fix this issue?

Here is the exception stack trace:

System.TypeInitializationException: The type initializer for 'NanoProtoApi.Interop' threw an exception. ---> System.Exception: LoadLibrary failed: C:\Program Files\Proj\x64\Nanomsg.dll
   at NanoProtoApi.NanomsgLibraryLoader.LoadWindowsLibrary(String libName, SymbolLookupDelegate& symbolLookup)
   at NanoProtoApi.Interop..cctor()
   --- End of inner exception stack trace ---
   at NanoProtoApi.NanomsgSocketBase..ctor(Domain domain, Protocol protocol)
   at NanoProtoApi.Protocols.SubscribeSocket..ctor()
   at MK18.ATR.GATR.GatrProcessingClient.<>c.<runDetectReportFilteredTask>b__26_0() in C:\Users\user\Documents\MK 18\src\coin\mk18atr\project\Utilities\GatrProcessingClient.cs:line 238
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MK18.ATR.GATR.GatrProcessingClient.<SubscribeToDetectReportFiltered>d__25.MoveNext() in C:\Users\user\Documents\MK 18\src\coin\mk18atr\project\Utilities\GatrProcessingClient.cs:line 219
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()


问:
Origin http://localhost:8080 not found in Access-Control-Allow-Origin header
I am running an html file on my localhost. I am accessing a php file on my server.

Javascript being run on localhost:

```<code>var url = "http://www.chartmygolf.com/_TEST_DELETE/exclude.php";
var method = "GET";
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    // CORS not supported.
    xhr = null;
}

if (!xhr) {
    alert('CORS not supported');
    return;
}
// Response handlers.
xhr.onload = function (data) {
    var text = xhr.responseText;
    alert('Response: ' + text);
};
xhr.onerror = function (data) {
    alert('Woops, there was an error making the request.');
};
xhr.send();
</code>```

The php on my server www.mysite.com:

```<code><?php
$referrer = $_SERVER['HTTP_REFERER'];
$parts = parse_url($referrer);
$domain = $parts['host'];
header("Access-Control-Allow-Origin: http://" . $domain);
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$arr = array("181K2", "4V419");
echo json_encode($arr);
?>
</code>```

In Chrome and Edge it goes into alert('Woops, there was an error making the request.');

Edge Error:

SEC7120: Origin http://localhost:8080 not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80700013, Could not complete the operation due to error 80700013.

Chrome Error:

XMLHttpRequest cannot load http://www.chartmygolf.com/_TEST_DELETE/exclude.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

This is driving me insane. I have tried ajax and now this method and I get inconsistent results. I have read loads of threads here on stackoverflow and none of the answers work. (However, these threads seem to be ages old.)

Note: I get the same error if I use

header("Access-Control-Allow-Origin: *");

Please help. I am losing all grip on my sanity.

答:
OK. Found it. I do not have access to php settings on my server. It is a Windows server.

Putting this into a web.config file in the directory where the php script is does the trick.

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>
</code>```

If you are not on a windows server, you will need to do the .htaccess exquivalent of the above.

Body:
I am running an html file on my localhost. I am accessing a php file on my server.

Javascript being run on localhost:

var url = "http://www.chartmygolf.com/_TEST_DELETE/exclude.php";
var method = "GET";
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    // CORS not supported.
    xhr = null;
}

if (!xhr) {
    alert('CORS not supported');
    return;
}
// Response handlers.
xhr.onload = function (data) {
    var text = xhr.responseText;
    alert('Response: ' + text);
};
xhr.onerror = function (data) {
    alert('Woops, there was an error making the request.');
};
xhr.send();

The php on my server www.mysite.com:

<?php
$referrer = $_SERVER['HTTP_REFERER'];
$parts = parse_url($referrer);
$domain = $parts['host'];
header("Access-Control-Allow-Origin: http://" . $domain);
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$arr = array("181K2", "4V419");
echo json_encode($arr);
?>

In Chrome and Edge it goes into alert('Woops, there was an error making the request.');

Edge Error:

SEC7120: Origin http://localhost:8080 not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80700013, Could not complete the operation due to error 80700013.

Chrome Error:

XMLHttpRequest cannot load http://www.chartmygolf.com/_TEST_DELETE/exclude.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

This is driving me insane. I have tried ajax and now this method and I get inconsistent results. I have read loads of threads here on stackoverflow and none of the answers work. (However, these threads seem to be ages old.)

Note: I get the same error if I use

header("Access-Control-Allow-Origin: *");

Please help. I am losing all grip on my sanity.

Body:
OK. Found it. I do not have access to php settings on my server. It is a Windows server.

Putting this into a web.config file in the directory where the php script is does the trick.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

If you are not on a windows server, you will need to do the .htaccess exquivalent of the above.


问:
Can I bind to multiple consumer groups with Spring Cloud Stream?
I am writing an application that will process event messages (posted to the topic file-upload-completed). I have multiple endpoints that should consume these messages (metadata-reader and quota-checker), and for pragmatic reasons I would like to deploy these endpoints together in an aggregated package.

With Spring Cloud Stream, I could use spring.cloud.stream.bindings.file-upload-completed.group=metadata-reader to set the consumer group for the first endpoint; I would also like to process messages under the quota-check group, but the property-based configuration only permits one consumer group binding per message queue.

Is there a way to configure Spring Cloud Stream so that I can bind to a single message queue under multiple consumer groups in the same application?

答: AFAIK consumer group means singleton consumer in cluster. If both your endpoints are in the same app, no reason to extract new consumer group. You can just publish-subscribe an incoming message to all your endpoints internally.


问:
Match string to regex in bash
In the below code, either T1 should be set or T2 must follow the regex, else print "error", but it doesn't work.

And is there an better way to check if T2 has pattern string with underscore >:<space separated strings>; please note the colon and semicolon.

```<code>#!/bin/bash

T1="TEST"
T2="TST_1:one two three;"

if [[ -z ${T1} && ! ${T2} =~ .*":".*";" ]]; then
    echo "error"
    exit 1
fi
</code>```

答:
You can use this regex:

```<code>re='^[^:_]+_[^:_]:[^[:blank:];]+([[:blank:]]+[^[:blank:];]+)+;$'

T1="TEST"
T2="TST_1:one two three;"

if [[ -z "$T1" && ! $T2 =~ $re ]]; then
    echo "error"
    exit 1
fi
</code>```

RegEx Demo

Title: Match string to regex in bash

Body:
In the below code, either T1 should be set or T2 must follow the regex, else print "error", but it doesn't work.

And is there an better way to check if T2 has pattern :<space separated strings>; please note the colon and semicolon.

#!/bin/bash

T1="TEST"
T2="TST_1:one two three;"

if [[ -z ${T1} && ! ${T2} =~ .*":".*";" ]]; then
    echo "error"
    exit 1
fi

Body:
You can use this regex:

re='^[^:_]+_[^:_]:[^[:blank:];]+([[:blank:]]+[^[:blank:];]+)+;$'

T1="TEST"
T2="TST_1:one two three;"

if [[ -z "$T1" && ! $T2 =~ $re ]]; then
    echo "error"
    exit 1
fi

RegEx Demo


问:
How to pass a ResourceDictionary to ViewModelLocator
Hi i created a property in ViewModelLocator to allow a ResourceDictionary to pass to the ViewModelLocator. In my app.xaml i have this defined:

```<code><vm:ViewModelLocator x:Key="Locator">
  <vm:ViewModelLocator.DefaultUIResourceDictionary>
    <ResourceDictionary Source="Resources/DefaultUIResource.xaml"/>
  </vm:ViewModelLocator.DefaultUIResourceDictionary>
</vm:ViewModelLocator>
</code>```

It runs fine, however, when i try to reference the dictionary, it has 0 items in it, which i'm sure DefaultUIResource.xaml has an item defined. Not sure what is wrong.

Another question is, the resources defined in the App.Resources property is only created when referenced? Can anyone tell me the life cycle of the App class? when is the items in the Resources property created? After the constructor?

答:
ok i found a solution:

i created another ResourceDictionary and defined inside it as follows:

```<code><ResourceDictionary x:Key="Default" Source="/Resources/DefaultUIResource.xaml"/>

<vm:ViewModelLocator x:Key="Locator" DefaultUIResourceDictionary="{StaticResource Default}"/>
</code>```

then in the App.Resources i just use ResourceDictionary's MergedDictionaries to link to this new ResourceDictionary.

Body:
Hi i created a property in ViewModelLocator to allow a ResourceDictionary to pass to the ViewModelLocator. In my app.xaml i have this defined:

<vm:ViewModelLocator x:Key="Locator">
  <vm:ViewModelLocator.DefaultUIResourceDictionary>
    <ResourceDictionary Source="Resources/DefaultUIResource.xaml"/>
  </vm:ViewModelLocator.DefaultUIResourceDictionary>
</vm:ViewModelLocator>

It runs fine, however, when i try to reference the dictionary, it has 0 items in it, which i'm sure DefaultUIResource.xaml has an item defined. Not sure what is wrong.

Another question is, the resources defined in the App.Resources property is only created when referenced? Can anyone tell me the life cycle of the App class? when is the items in the Resources property created? After the constructor?

Body:
ok i found a solution:

i created another ResourceDictionary and defined inside it as follows:

<ResourceDictionary x:Key="Default" Source="/Resources/DefaultUIResource.xaml"/>

<vm:ViewModelLocator x:Key="Locator" DefaultUIResourceDictionary="{StaticResource Default}"/>

then in the App.Resources i just use ResourceDictionary's MergedDictionaries to link to this new ResourceDictionary.


问:
Html / php not updating sql database
I've been working on this for hours now and including rebuilding my whole code I cannot figure out what is wrong. The HTML form is supposed to populate the patients SQL database but it is not working. I have a similar form that I am using on another part of the website that works flawlessly but this on doesn't seem to and a can't figure out why.

I have checked if the $_POST 's are coming through and they are but the $message values are not.

thanks for your help
Here is a picture of the database fields: database fields

Heres the code:

```<code><?php

require 'connection.php';

$message = '';

if(!empty($_POST['name']) && !empty($_POST['dob']) && !empty($_POST['nok']) && !empty($_POST['nok_add']) && !empty($_POST['nok_phone'])&& !empty($_POST['doa'])&& !empty($_POST['allergies'])):

  // Enter the new user in the database
  $sql = "INSERT INTO patients (name, dob, nok, nok_add, nok_phone, doa, allergies) VALUES (:name, :dob, :nok, :nok_add, :nok_phone, :doa, :allergies)";
  $stmt = $conn->prepare($sql);

  $stmt->bindParam(':name', $_POST['name']);
  $stmt->bindParam(':dob', $_POST['dob']);
  $stmt->bindParam(':nok', $_POST['nok']);
  $stmt->bindParam(':nok_add', $_POST['nok_add']);
  $stmt->bindParam(':nok_phone', $_POST['nok_phone']);
  $stmt->bindParam(':doa', $_POST['doa']);
  $stmt->bindParam(':allergies', $_POST['allergies']);

  if( $stmt->execute() ):
    $message = 'Successfully created new user';
  else:
    $message = 'Sorry there must have been an issue creating your account';
  endif;

endif;

?>

<html>
  <head>
    <title>Patient Add</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" type="text/css" href="assets/css/style.css">
      <link href="//fonts.googleapis.com/css?fami=Roboto:400,300,200,100&subset=latin,cyrillic" rel="stylesheet">
<style type="text/css">
        #headline {
        padding: 0.8em;
        color: white;
        font-family: Roboto, helvetica, arial, sans-serif;
        background-color: black;
        background-image: url(backgroundimage.jpg);
        background-size: cover;
      }

</style>

  </head>
  <body>

    <div id="headline">
      <div class="container">
        <header>
          <h1>Patient Add</h1>
          <p></p>
        </header>

    <button onClick="window.location='manager_select.php';" class="_button">Back</button>
    <form method="POST" id="add">

      <h2>Enter the Patient's Details</h2>

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

      <label for="dob">Date of Birth:</label>
      <input type="text" name="dob">

      <label for="nok">Next of Kin:</label>
      <input type="text" name="nok">

      <label for="nok_add">Address:</label>
      <input type="text" name="nok_add">

      <label for="nok_phone">Phone:</label>
      <input type="text" name="nok_phone">

      <label for="doa">Date of Admission:</label>
      <input type="text" name="dob">

      <label for="allergies">Allergies:</label>
      <input type="text" name="allergies">

      <?php if(!empty($message)): ?>
        <p><?= $message ?></p>
      <?php endif; ?>
      <input type="submit">

    </form>
        <br>
      </div>
    </div>

  <!-- // [START footer] -->
      <footer>
        <div class="container">
          <p>Copyright Ghyll Court Residental Home 2017</p>
        </div>
      </footer>
      <!-- // [END footer] -->

  </script>
      <script type="text/javascript">
        function init() {
          window.matchMedia("(max-width: 600px)").addListener(hitMQ);
        }

        function hitMQ(evt) {
          sampleCompleted("GettingStarted-ContentWithStyles");
        }

        init();

      </script>

  </body>
</html>
</code>```

答:
Your if-statement checks !empty($_POST['doa']), but your form does not contain a doa:

```<code><label for="doa">Date of Admission:</label>
<input type="text" name="dob">
</code>```

This <input> should probably have name="doa" instead of dob.

Title: Html / php not updating sql database

Body:
I've been working on this for hours now and including rebuilding my whole code I cannot figure out what is wrong. The HTML form is supposed to populate the patients SQL database but it is not working. I have a similar form that I am using on another part of the website that works flawlessly but this on doesn't seem to and a can't figure out why.

I have checked if the $_POST 's are coming through and they are but the $message values are not.

thanks for your help
Here is a picture of the database fields: database fields

Heres the code:

<?php

require 'connection.php';

$message = '';

if(!empty($_POST['name']) && !empty($_POST['dob']) && !empty($_POST['nok']) && !empty($_POST['nok_add']) && !empty($_POST['nok_phone'])&& !empty($_POST['doa'])&& !empty($_POST['allergies'])):

  // Enter the new user in the database
  $sql = "INSERT INTO patients (name, dob, nok, nok_add, nok_phone, doa, allergies) VALUES (:name, :dob, :nok, :nok_add, :nok_phone, :doa, :allergies)";
  $stmt = $conn->prepare($sql);

  $stmt->bindParam(':name', $_POST['name']);
  $stmt->bindParam(':dob', $_POST['dob']);
  $stmt->bindParam(':nok', $_POST['nok']);
  $stmt->bindParam(':nok_add', $_POST['nok_add']);
  $stmt->bindParam(':nok_phone', $_POST['nok_phone']);
  $stmt->bindParam(':doa', $_POST['doa']);
  $stmt->bindParam(':allergies', $_POST['allergies']);

  if( $stmt->execute() ):
    $message = 'Successfully created new user';
  else:
    $message = 'Sorry there must have been an issue creating your account';
  endif;

endif;

?>

    <title>Patient Add</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" type="text/css" href="assets/css/style.css">
      <link href="//fonts.googleapis.com/css?fami=Roboto:400,300,200,100&subset=latin,cyrillic" rel="stylesheet">

Patient Add

    <button onClick="window.location='manager_select.php';" class="_button">Back</button>
    <form method="POST" id="add">

Enter the Patient's Details

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

      Date of Birth:
      <input type="text" name="dob">

      Next of Kin:
      <input type="text" name="nok">

      Address:
      <input type="text" name="nok_add">

      Phone:
      <input type="text" name="nok_phone">

      Date of Admission:
      <input type="text" name="dob">

      Allergies:
      <input type="text" name="allergies">

      <?php if(!empty($message)): ?>

<?= $message ?>

      <?php endif; ?>
      <input type="submit">

    </form>

Copyright Ghyll Court Residental Home 2017

  </script>

Body:
Your if-statement checks !empty($_POST['doa']), but your form does not contain a doa:

<label for="doa">Date of Admission:</label>
<input type="text" name="dob">

This <input> should probably have name="doa" instead of dob.


问:
How to execute tasks conditionally using the maven-antrun-plugin?
I need to execute some ant commands depending on an environment variable passed in as a parameter to the maven build command.

At the moment I have 3 tasks blocks and only the tasks block with no condition is being executed.

```<code><tasks name="isProdCheck">
  <condition property="isProd">
    <equals arg1="${environment}" arg2="PROD" />
  </condition>
</tasks>

<tasks if="isProd" depends="isProdCheck">
...
</tasks>

<tasks>
... I am the only block executed
</tasks>
</code>```

What am I doing wrong, is there a better way to do this?

答:
runable example here https://www.surasint.com/run-ant-with-if-from-maven/

Another solution would be: keep the ant-contrib-1.0b3.jar to a path and then define it like this

```<code><property name="runningLocation" location="" />
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
        <pathelement location="${runningLocation}/ant-contrib-1.0b3.jar" />
    </classpath>
</taskdef>
</code>```

then

```<code><target name="doSomething">
    <if>
        <equals arg1="${someProp}" arg2="YES" />
        <then>
            <echo message="It is YES" />
        </then>
        <else>
            <echo message="It is not YES" />
        </else>
    </if>
</target>
</code>```

I put full code example here which you can download https://www.surasint.com/2017/04/09/run-ant-with-if-from-maven/

Body:
I need to execute some ant commands depending on an environment variable passed in as a parameter to the maven build command.

At the moment I have 3 tasks blocks and only the tasks block with no condition is being executed.

<tasks name="isProdCheck">
  <condition property="isProd">
    <equals arg1="${environment}" arg2="PROD" />
  </condition>
</tasks>

<tasks if="isProd" depends="isProdCheck">
...
</tasks>

<tasks>
... I am the only block executed
</tasks>

What am I doing wrong, is there a better way to do this?

Body:
runable example here https://www.surasint.com/run-ant-with-if-from-maven/

Another solution would be: keep the ant-contrib-1.0b3.jar to a path and then define it like this

<property name="runningLocation" location="" />
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
        <pathelement location="${runningLocation}/ant-contrib-1.0b3.jar" />
    </classpath>
</taskdef>

then

<target name="doSomething">
    <if>
        <equals arg1="${someProp}" arg2="YES" />
        <then>
            <echo message="It is YES" />
        </then>
        <else>
            <echo message="It is not YES" />
        </else>
    </if>
</target>

I put full code example here which you can download https://www.surasint.com/2017/04/09/run-ant-with-if-from-maven/


问:
Parse remote notifications and timezones
I'm looking at remote notifications with the Parse SDK and background jobs since I want my application to execute a background job (Which is pushing a notification from cloud code) at 7 am every morning.

The thing I'm confused about is that the background jobs are scheduled at 7 am UTC time, so I'm assuming that the function would execute for users at 7 am in the UTC timezone but for other users who are not in this time zone, they will receive this notification as well.

So my question is there a way to make sure users only receive the notification at 7 am based on their local timezone rather than UTC timezone which the background job is depending on?

答:
As discussed in https://github.com/ParsePlatform/parse-dashboard/issues/542, you could either use node-schedule or a third-party SDK (CleverTap/PushWoosh/OneSignal)

List of alternative Push SDKs recommended by the community:
https://github.com/ParsePlatform/parse-server/wiki#push-notifications-alternative-services


问:
PHP server outputting warning about FD_SETSIZE
I'm currently a newbie with PHP and MySQL, however, I'm trying to run a PHP server code for a Club Penguin Emulator, however, i am having no luck as more people join and make it incredibly hard to join due to PHP warnings and errors.

I had a open file limit which i changed by following this tutorial

However, my PHP code runs, very slowly, however, it keeps outputting this:

socket_select(): You MUST recompile PHP with a larger value of
  FD_SETSIZE.

It is set to 1024, but you have descriptors numbered at least as high as 1978.

--enable-fd-setsize=2048 is recommended, but you may want to set it to equal the maximum number of open files supported by your system, in order to avoid this error at a later date.

Now my question is, how can i recompile PHP and how can i change this value?

答:
Use the command wget to download the latest php sources. You will get probably an archive or something. Unzip the archive and run the setup with your configurations.

Otherwise consult de FAQ http://php.net/manual/en/faq.build.php


问:
setting hidden form field values with jquery
I'm using js.cookie.js to set cookie values after reading URL parameters. Next I want to populate a number of hidden fields with the cookie values. Reading the URL values and setting the cookie is working, but setting the values in the hidden fields is not working.

Here's the script:

```
</div>
</div>
</p>

<p>And here is are the hidden fields within the form with the id="contact-form"</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Visitor ID: -->
  <input id="00N4100000NglQ2" maxlength="255" name="00N4100000NglQ2" size="20" type="hidden" value="" />

  <!-- Medium: -->
  <input id="00N4100000NgleO" maxlength="255" name="00N4100000NgleO" size="20" type="hidden" value="" />
  <!-- Source: -->

  <input id="00N4100000NglpC" maxlength="255" name="00N4100000NglpC" size="20" type="hidden" value="" />
  <!-- Campaign: -->
  <input id="00N4100000NglyY" maxlength="255" name="00N4100000NglyY" size="20" type="hidden" value="" />

  <!-- Content: -->
  <input id="00N4100000NgmBh" maxlength="255" name="00N4100000NgmBh" size="20" type="hidden" value="" />

  <!-- Term: -->
  <input id="00N4100000NgmIs" maxlength="255" name="00N4100000NgmIs" size="20" type="hidden" value="" />

  <!-- Count of Sessions: -->
  <input id="00N4100000NgmQw" maxlength="255" name="00N4100000NgmQw" size="20" type="hidden" value="" />

  <!-- Count of Pageviews: -->
  <input id="00N4100000NgmZ5" maxlength="255" name="00N4100000NgmZ5" size="20" type="hidden" value="" /> </code>```

I'm wondering if it's a problem with the hidden field names,"00N4100000NgmZ5" for example, which are custom field names from salesforce.com

Thanks for your help.

答:
Try to declare all your variables above your function getParameterByName(), and load the variables with their values inside your function, set your cookies right after and add the jQuery function right after you finish loading the variables as a simple $(function(){}).

I guess the problem is that when your $(document).ready() function executes WHEN the page is loaded and there are no values to load YET.

```

Body:
I'm using js.cookie.js to set cookie values after reading URL parameters. Next I want to populate a number of hidden fields with the cookie values. Reading the URL values and setting the cookie is working, but setting the values in the hidden fields is not working.

Here's the script:

And here is are the hidden fields within the form with the id="contact-form"

  <input id="00N4100000NglQ2" maxlength="255" name="00N4100000NglQ2" size="20" type="hidden" value="" />

  <input id="00N4100000NgleO" maxlength="255" name="00N4100000NgleO" size="20" type="hidden" value="" />

  <input id="00N4100000NglpC" maxlength="255" name="00N4100000NglpC" size="20" type="hidden" value="" />

  <input id="00N4100000NglyY" maxlength="255" name="00N4100000NglyY" size="20" type="hidden" value="" />

  <input id="00N4100000NgmBh" maxlength="255" name="00N4100000NgmBh" size="20" type="hidden" value="" />

  <input id="00N4100000NgmIs" maxlength="255" name="00N4100000NgmIs" size="20" type="hidden" value="" />

  <input id="00N4100000NgmQw" maxlength="255" name="00N4100000NgmQw" size="20" type="hidden" value="" />

  <input id="00N4100000NgmZ5" maxlength="255" name="00N4100000NgmZ5" size="20" type="hidden" value="" />

I'm wondering if it's a problem with the hidden field names,"00N4100000NgmZ5" for example, which are custom field names from salesforce.com

Thanks for your help.

Body:
Try to declare all your variables above your function getParameterByName(), and load the variables with their values inside your function, set your cookies right after and add the jQuery function right after you finish loading the variables as a simple $(function(){}).

I guess the problem is that when your $(document).ready() function executes WHEN the page is loaded and there are no values to load YET.

<script>

  var visitor_id;
  var medium;
  var source;
  var campaign;
  var content;
  var term;
  var count_of_sessions;
  var count_of_page_views;

// Parse the URL
function getParameterByName(name) {
 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  results = regex.exec(location.search);
 return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

  // Give the URL parameters variable names
  visitor_id = getParameterByName('utm_visitor_id');
  medium = getParameterByName('utm_medium');
  source = getParameterByName('utm_source');
  campaign = getParameterByName('utm_campaign');
  content = getParameterByName('utm_content');
  term = getParameterByName('utm_term');
  count_of_sessions = getParameterByName('utm_count_of_sessions');
  count_of_page_views = getParameterByName('utm_count_of_page_views');

  // Set the cookies

  Cookies.set('utm_visitor_id', visitor_id, { expires: 90 });
  Cookies.set('utm_medium', medium, { expires: 90 });
  Cookies.set('utm_source', source, { expires: 90 });
  Cookies.set('utm_campaign', campaign, { expires: 90 });
  Cookies.set('utm_content', content, { expires: 90 });
  Cookies.set('utm_term', term, { expires: 90 });
  Cookies.set('utm_count_of_sessions', count_of_sessions, { expires: 90 });
  Cookies.set('utm_count_of_page_views', count_of_page_views, { expires: 90 });

  // Grab the cookie value and set the form field values
  $(function(){
    $('input[name=00N4100000NglQ2').val(utm_visitor_id);
    $('input[name=00N4100000NgleO').val(utm_medium);
    $('input[name=00N4100000NglpC').val(utm_source);
    $('input[name=00N4100000NglyY').val(utm_campaign);
    $('input[name=00N4100000NgmBh').val(utm_content);
    $('input[name=00N4100000NgmIs').val(utm_term);
    $('input[name=00N4100000NgmQw').val(utm_count_of_sessions);
    $('input[name=00N4100000NgmZ5').val(utm_count_of_page_views);
  });
}

</script>


问:
Why does defining an implicit function as an object property work in Firefox and Chrome?
How does this even work on Firefox and Chrome, but error on IE. As far as I can see, this should always produce an error, but somehow Firefox and Chrome allow you to do this.

Is this actually a part of one of the ES standards or is this just some weirdness.

```<code>var Greeter = {
   sayHi( name )
   {
      alert( name );
   }
};

Greeter.sayHi( 'kevin' );
</code>```

答:
You are using ES6 syntax.

For using the object with ES5, you could use a function expression instead.

var Greeter = {
        sayHi: function(name) {
            alert(name);
        }
    };

Greeter.sayHi('kevin');```

Body:
How does this even work on Firefox and Chrome, but error on IE. As far as I can see, this should always produce an error, but somehow Firefox and Chrome allow you to do this.

Is this actually a part of one of the ES standards or is this just some weirdness.

var Greeter = {
   sayHi( name )
   {
      alert( name );
   }
};

Greeter.sayHi( 'kevin' );


答:
This is ES2015 (aka "ES6"): It's the new method syntax.

It doesn't work in IE because IE doesn't support it, having been released years before the ES2015 spec was completed. It would work just fine in Edge.

Title: Why does defining an implicit function as an object property work in Firefox and Chrome?


问:
How to use in cypher escape character in file URL
I know that cyphers escape character is backtick, but when importing CSV from local file I do not how to use it properly. Basically this is what I am trying to achieve:

```<code>LOAD CSV WITH HEADERS FROM "file:///General Hospital Information.csv" as row
return row limit 5
</code>```

But this returns an error.

java.net.URISyntaxException: Illegal character in path at index 13:
  file:/General Hospital Information.csv

I have tried putting backtick in the path to file string as a solution, but it does not work since it is in a string. Any idea how one can achieve this ? I mean besides renaming my file.

答:
Since these are urls, try using %20 or + to replace the spaces:

```<code>LOAD CSV WITH HEADERS FROM "file:///General%20Hospital%20Information.csv" as row
RETURN row LIMIT 5
</code>```

There is an APOC function to url encode strings:

```<code>WITH apoc.text.urlencode("General Hospital Information.csv") AS f
LOAD CSV WITH HEADERS FROM "file:///"+f as row
return row limit 5
</code>```

Body:
I know that cyphers escape character is backtick, but when importing CSV from local file I do not how to use it properly. Basically this is what I am trying to achieve:

LOAD CSV WITH HEADERS FROM "file:///General Hospital Information.csv" as row
return row limit 5

But this returns an error.

java.net.URISyntaxException: Illegal character in path at index 13:
  file:/General Hospital Information.csv

I have tried putting backtick in the path to file string as a solution, but it does not work since it is in a string. Any idea how one can achieve this ? I mean besides renaming my file.

Body:
Since these are urls, try using %20 or + to replace the spaces:

LOAD CSV WITH HEADERS FROM "file:///General%20Hospital%20Information.csv" as row
RETURN row LIMIT 5

There is an APOC function to url encode strings:

WITH apoc.text.urlencode("General Hospital Information.csv") AS f
LOAD CSV WITH HEADERS FROM "file:///"+f as row
return row limit 5


问:
Received odd RVM error in workspace, now rails commands aren't working
I just logged into my Ubuntu workspace on Cloud9. Upon logging in I saw an error.

```<code>RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does
that too, you can ignore these warnings with 'rvm rvmrc warning ignore
/home/ubuntu/workspace/Simutronix/Gemfile'. To ignore the warning for
all files run 'rvm rvmrc warning ignore allGemfiles'.
</code>```

Which I've not seen before and wasn't occurring when I last used the workspace. I then attempted to run the Rails server.

```<code>rails server -b $IP -p $PORT
</code>```

I got an error message back.

```<code>bash: rails: command not found
</code>```

I then tried to run bundle install which also came back with command not found.

ruby -v returns ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux].

What's likely to have happened to cause this to happen in between logins and what can I do to fix it?

答:
Likely the Ruby version defined in your Gemfile and/or .ruby-version changed, which means you will have to install bundler and bundle the gems again. Running this should solve the issue:

```<code>gem install bundler
bundle install
</code>```

Body:
I just logged into my Ubuntu workspace on Cloud9. Upon logging in I saw an error.

RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does
that too, you can ignore these warnings with 'rvm rvmrc warning ignore
/home/ubuntu/workspace/Simutronix/Gemfile'. To ignore the warning for
all files run 'rvm rvmrc warning ignore allGemfiles'.

Which I've not seen before and wasn't occurring when I last used the workspace. I then attempted to run the Rails server.

rails server -b $IP -p $PORT

I got an error message back.

bash: rails: command not found

I then tried to run bundle install which also came back with command not found.

ruby -v returns ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux].

What's likely to have happened to cause this to happen in between logins and what can I do to fix it?

Body:
Likely the Ruby version defined in your Gemfile and/or .ruby-version changed, which means you will have to install bundler and bundle the gems again. Running this should solve the issue:

gem install bundler
bundle install


问:
Mercurial v Git v Subversion
I need to choose a VCS to embed within a Java application I'm developing. The Java application will interact with the VCS via an API, but the user will also interact with it directly via an Eclipse plugin.

3 candidate VCS have been identified: Mercurial, Git and Subversion. I need to choose one based on the following criteria (in no particular order):

Java API. This is not 100% necessary, because the application could issue VCS commands via the command-line if no Java API is available. However, an API would obviously be preferable

Eclipse plugin

Simplicity. The people using the VCS (indirectly via the application or directly via Eclipse), will be software developers, but probably not the most sophisticated of the species.

Licensing. The license must permit to use of the VCS (in the manner described above) in a commercial application

There may be other considerations I've overlooked, I'll update the question if any more spring to mind.

Thanks!

答:
First of all, I'd scratch out Subversion unless your application has a workflow that works especially well with a centralized VCS.  And even then I'd try to use Mercurial or git since svn is just so slow.

Regarding Mercurial (hg) vs Git, I personally would choose git.  On one hand, hg is simpler and more intuitive, but git is much faster and has much more mindshare than hg does.

Scriptability might be an issue though.  Git is really made to be scriptable from a Unix shell (although it will run on windows with some gnu software installed).  Hg has a python interface, but if I recall correctly has some C extensions that will probably make it impossible to use with jython.  That said, it looks like there is a third-party git library for Java:  http://eclipse.org/jgit/

Regarding licensing, hg and git are both GPLed, but if you shell out to them that shouldn't be an issue.  SVN uses an Apache license, so it might win on this front (basically, you can do whatever you want with it).

Title: Mercurial v Git v Subversion


问:
Android Studio rendering errors, while the app works correctly
In Android Studio I used a SeekBar  from external source.
The app works correctly, but I still get two Rendering errors:

"Failed to find style 'discreteSeekBarStyle' in current theme"

"Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references."

What can be the problem?

答:
If the app works fine maybe you can fix it just restarting Android Studio.
It append to me very often and I solve it just restarting Android Studio.</p>


问:
VoIP push with new token-based auth?
I'm able to get the new token-based push working (without using certificates) just fine with normal push notifications and using a simple node.js file for the backend.

But, I can't get it to work with VoIP push. I've tried just using the token derived from PushKit - creditials.token but I always get a 400 error.

I can't seem to find any info on this online. Just the mention from WWDC that token-based auth could also be used for VoIP push.

答:
I used the description from http://gobiko.com/blog/token-based-authentication-http2-example-apns/ to send token-based push notifications with python.

It worked well with normal push notifications, but when I tried a voip token instead of my normal push token, I also got a 400 error code. In the error description it said {"reason":"TopicDisallowed"}. Here, I had set my bundle id as apns-topic. I could fix the error by appending .voip to the bundle id.

Note that the voip notifications are silent notifications. Further, if you want to send a complication, according to https://www.foraker.com/blog/pushing-data-to-apple-watch-complications-with-pushkit you should try to append your bundle id with .complication instead.

Title: VoIP push with new token-based auth?


问:
Xcode Storyboards - iPhone 7 Plus has no status bar?
Why does the iPhone 7 Plus storyboard have no Status Bar visible in Xcode where as the other sizes do (iPhone 7, 5s). When running the app in the iPhone 7 Plus it has a status bar but on the storyboard it doesn't?

iPhone 7 Plus and has no status bar:

iPhone 7 storyboard that has status bar:

答:
My guess is the status bar was disabled on that size class for some reason:

If that is so, change it to 'inferred' and that should fix it.


问:
Resize qtvirtualkeyboard according to QObject
I'm using the qml qtvirtual keyboard: https://github.com/qt/qtvirtualkeyboard

I'm trying to "connect" it with the rest of my Qt app which is based on widgets. For example, when I click on a QLineEdit, I want the keyboard to show up and to act like a physical one in the app context.

To do so, I installed what's in qtvirtualkeyboard/src (qmake && make && make install) and here is my main.cpp :

```<code>#include <QQuickView>
#include <QApplication>
#include <QQmlEngine>
#include <QQmlContext>

int main(int argc, char *argv[]){

    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));

    QApplication app(argc, argv);
    MainWindow w();  // This is a QWidget / QMainWindow
    w.setFixedSize(800, 480);
    w.show();

    return app.exec();
}
</code>```

When I execute this on my desktop, the Keyboard takes half of my screen despite that my app is 800x480.

And when I execute it on my Raspberry Pi with its 7" touchscreen, the keyboard takes half of the page and a black border appears on the top.

I want to fix the keyboard size myself. When I create a QML file with an Item and so on, the keyboard doesn't show up anymore.

答:
I have wrestled the QtVirtualKeyboard monster for the past month or so. Hopefully you can benefit from my trial and error.

The Pieces to the QtVirtualKeyboard Puzzle

The thing to know/remember is that there are essentially four separate pieces that inform the overall function and implementation of the keyboard:

qtvirtualkeyboard (function)

layout (structure)

style (presentation)

Qml within your application (implementation)

If you are using the default layouts and styles that come with qtvirtualkeyboard (in other words, you haven't created any custom styles or layouts), it is worth taking a look at them to get a better idea of what is going on behind the scenes. You can find them here:

layouts: /path/to/qtvirtualkeyboard/src/virtualkeyboard/content/layouts

styles: /path/to/qtvirtualkeyboard/src/virtualkeyboard/content/styles

Positioning The Keyboard

Here is a (bit of an oversimplified) example Qml file that demonstrates how to position the keyboard. In your case, since you are concerned with how much vertical screen real estate that is being consumed by the keyboard, the keyboard's y property is the first thing you'll want to target.

To start, set the keyboard.y to whatever the height of your screen is (e.g. parent.height or however you want to get that info). Placing the top of your keyboard to the bottom of the screen hides it from view.

Then, when you click in a TextInput field, invoking QtVirtualKeyboard, change the keyboard.y property to the bottom of the TextInput field during the state change from default/initial to "visible". An added benefit of handling this via state change is that you gain control over the keyboard animation.

```<code>import QtQuick 2.7
import QtQuick.VirtualKeyboard 2.1

Item {
    id: appSectionWithTextInput

    property int screenHeight: parent.height; // the height of the screen/display
    anchors.fill: parent;

    TextInput {
        id: textInput;
        height: 120;
        width: parent.width - 2;

        color: "#000000"; // black

        // http://doc.qt.io/qt-5/qinputmethod.html#properties
        focus: Qt.inputMethod.visible;

        verticalAlignment: TextInput.AlignVCenter;
    }

    InputPanel {
        id: keyboard;
        y: screenHeight; // position the top of the keyboard to the bottom of the screen/display

        anchors.left: parent.left;
        anchors.right: parent.right;

        states: State {
            name: "visible";
            when: keyboard.active;
            PropertyChanges {
                target: keyboard;
                // position the top of the keyboard to the bottom of the text input field
                y: textInput.height;
            }
        }
        transitions: Transition {
            from: ""; // default initial state
            to: "visible";
            reversible: true; // toggle visibility with reversible: true;
            ParallelAnimation {
                NumberAnimation {
                    properties: "y";
                    duration: 250;
                    easing.type: Easing.InOutQuad;
                }
            }
        }
    }
}
</code>```

Custom Layout

If you would like to create your own custom layout(s), your best bet is to copy one of the existing layouts that come with qtvirtualkeyboard (e.g. en_GB) to a directory of your choosing. Once there, rename it to whatever you like and add the following environment var: QT_VIRTUALKEYBOARD_LAYOUT_PATH=/path/to/custom/keyboard-layout/mycustomlayout.

Note: The QT_VIRTUALKEYBOARD_LAYOUT_PATH environment variable should be set to the file system directory containing the custom keyboard layouts before running the application.

Custom Style

If you would like to create  your own custom keyboard style, refer to this page for the specific directory where you should create your custom style directory.

Once there, add the following environment var: QT_VIRTUALKEYBOARD_STYLE=mycustomstyle.

If you would like to directly manipulate the size of the keyboard, you can access/change those properties in the style.qml file located in your custom style directory.

```<code>// Properties
keyboardDesignWidth
keyboardDesignHeight
keyboardRelativetopMargin
keyboardRelativerightMargin
keyboardRelativeBottomMargin
keyboardRelativeLeftMargin
</code>```

You can find a full list of those properties here.

Best of luck!

Body:
I'm using the qml qtvirtual keyboard: https://github.com/qt/qtvirtualkeyboard

I'm trying to "connect" it with the rest of my Qt app which is based on widgets. For example, when I click on a QLineEdit, I want the keyboard to show up and to act like a physical one in the app context.

To do so, I installed what's in qtvirtualkeyboard/src (qmake && make && make install) and here is my main.cpp :

#include <QQuickView>
#include <QApplication>
#include <QQmlEngine>
#include <QQmlContext>

int main(int argc, char *argv[]){

    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));

    QApplication app(argc, argv);
    MainWindow w();  // This is a QWidget / QMainWindow
    w.setFixedSize(800, 480);
    w.show();

    return app.exec();
}

When I execute this on my desktop, the Keyboard takes half of my screen despite that my app is 800x480.

And when I execute it on my Raspberry Pi with its 7" touchscreen, the keyboard takes half of the page and a black border appears on the top.

I want to fix the keyboard size myself. When I create a QML file with an Item and so on, the keyboard doesn't show up anymore.

Body:
I have wrestled the QtVirtualKeyboard monster for the past month or so. Hopefully you can benefit from my trial and error.

The Pieces to the QtVirtualKeyboard Puzzle

The thing to know/remember is that there are essentially four separate pieces that inform the overall function and implementation of the keyboard:

qtvirtualkeyboard (function)

layout (structure)

style (presentation)

Qml within your application (implementation)

If you are using the default layouts and styles that come with qtvirtualkeyboard (in other words, you haven't created any custom styles or layouts), it is worth taking a look at them to get a better idea of what is going on behind the scenes. You can find them here:

layouts: /path/to/qtvirtualkeyboard/src/virtualkeyboard/content/layouts

styles: /path/to/qtvirtualkeyboard/src/virtualkeyboard/content/styles

Positioning The Keyboard

Here is a (bit of an oversimplified) example Qml file that demonstrates how to position the keyboard. In your case, since you are concerned with how much vertical screen real estate that is being consumed by the keyboard, the keyboard's y property is the first thing you'll want to target.

To start, set the keyboard.y to whatever the height of your screen is (e.g. parent.height or however you want to get that info). Placing the top of your keyboard to the bottom of the screen hides it from view.

Then, when you click in a TextInput field, invoking QtVirtualKeyboard, change the keyboard.y property to the bottom of the TextInput field during the state change from default/initial to "visible". An added benefit of handling this via state change is that you gain control over the keyboard animation.

import QtQuick 2.7
import QtQuick.VirtualKeyboard 2.1

Item {
    id: appSectionWithTextInput

    property int screenHeight: parent.height; // the height of the screen/display
    anchors.fill: parent;

    TextInput {
        id: textInput;
        height: 120;
        width: parent.width - 2;

        color: "#000000"; // black

        // http://doc.qt.io/qt-5/qinputmethod.html#properties
        focus: Qt.inputMethod.visible;

        verticalAlignment: TextInput.AlignVCenter;
    }

    InputPanel {
        id: keyboard;
        y: screenHeight; // position the top of the keyboard to the bottom of the screen/display

        anchors.left: parent.left;
        anchors.right: parent.right;

        states: State {
            name: "visible";
            when: keyboard.active;
            PropertyChanges {
                target: keyboard;
                // position the top of the keyboard to the bottom of the text input field
                y: textInput.height;
            }
        }
        transitions: Transition {
            from: ""; // default initial state
            to: "visible";
            reversible: true; // toggle visibility with reversible: true;
            ParallelAnimation {
                NumberAnimation {
                    properties: "y";
                    duration: 250;
                    easing.type: Easing.InOutQuad;
                }
            }
        }
    }
}

Custom Layout

If you would like to create your own custom layout(s), your best bet is to copy one of the existing layouts that come with qtvirtualkeyboard (e.g. en_GB) to a directory of your choosing. Once there, rename it to whatever you like and add the following environment var: QT_VIRTUALKEYBOARD_LAYOUT_PATH=/path/to/custom/keyboard-layout/mycustomlayout.

Note: The QT_VIRTUALKEYBOARD_LAYOUT_PATH environment variable should be set to the file system directory containing the custom keyboard layouts before running the application.

Custom Style

If you would like to create  your own custom keyboard style, refer to this page for the specific directory where you should create your custom style directory.

Once there, add the following environment var: QT_VIRTUALKEYBOARD_STYLE=mycustomstyle.

If you would like to directly manipulate the size of the keyboard, you can access/change those properties in the style.qml file located in your custom style directory.

// Properties
keyboardDesignWidth
keyboardDesignHeight
keyboardRelativetopMargin
keyboardRelativerightMargin
keyboardRelativeBottomMargin
keyboardRelativeLeftMargin

You can find a full list of those properties here.

Best of luck!